Deliver Atom feed items on Misskey
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

88 lines
1.6 KiB

package publisher
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"time"
"github.com/mattn/go-mastodon"
)
// RequestTimout is the timeout of a request in seconds.
const RequestTimout = 10
// Mastodon publisher.
type Mastodon struct {
Client *mastodon.Client
}
const (
mastodonName = "mastodon"
)
// NewMastodon creates a new Mastodon publisher.
func NewMastodon(baseURL, token string) *Mastodon {
return &Mastodon{
Client: mastodon.NewClient(&mastodon.Config{
Server: baseURL,
AccessToken: token,
}),
}
}
// Name returns with the name of the publisher.
func (m *Mastodon) Name() string {
return mastodonName
}
// Publish simply publishes a Toot.
func (m *Mastodon) Publish(content, image string) error {
mediaIDs := []mastodon.ID{}
if image != "" {
fileReader := bytes.NewReader(m.downloadFile(image))
attachment, err := m.Client.UploadMediaFromReader(context.Background(), fileReader)
if err != nil {
return err
}
mediaIDs = append(mediaIDs, attachment.ID)
}
toot := &mastodon.Toot{
Status: content,
MediaIDs: mediaIDs,
}
_, err := m.Client.PostStatus(context.Background(), toot)
return err
}
func (m *Mastodon) downloadFile(url string) []byte {
req, err := http.NewRequestWithContext(context.Background(), "GET", url, nil)
if err != nil {
return []byte{}
}
httpClient := &http.Client{
Timeout: time.Second * RequestTimout,
}
resp, err := httpClient.Do(req)
if err != nil {
return []byte{}
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}
}
return content
}