activityserve/remoteActor.go

113 lines
2.5 KiB
Go
Raw Normal View History

2019-09-10 04:21:39 -04:00
package activityserve
import (
"bytes"
"encoding/json"
2019-09-10 04:21:39 -04:00
"fmt"
"io/ioutil"
"net/http"
"github.com/gologme/log"
2019-09-10 04:21:39 -04:00
)
// RemoteActor is a type that holds an actor
// that we want to interact with
type RemoteActor struct {
iri, outbox, inbox, sharedInbox string
2023-04-28 14:02:47 -04:00
url string
info map[string]interface{}
2019-09-10 04:21:39 -04:00
}
// NewRemoteActor returns a remoteActor which holds
// all the info required for an actor we want to
// interact with (not essentially sitting in our instance)
func NewRemoteActor(iri string) (RemoteActor, error) {
info, err := get(iri)
if err != nil {
log.Info("Couldn't get remote actor information")
log.Error(err)
2019-09-10 04:21:39 -04:00
return RemoteActor{}, err
}
outbox, _ := info["outbox"].(string)
inbox, _ := info["inbox"].(string)
2023-04-28 14:02:47 -04:00
url, _ := info["url"].(string)
var endpoints map[string]interface{}
var sharedInbox string
if info["endpoints"] != nil {
endpoints = info["endpoints"].(map[string]interface{})
if val, ok := endpoints["sharedInbox"]; ok {
sharedInbox = val.(string)
}
}
2019-09-10 04:21:39 -04:00
return RemoteActor{
iri: iri,
outbox: outbox,
inbox: inbox,
sharedInbox: sharedInbox,
2023-04-28 14:02:47 -04:00
url: url,
2019-09-10 04:21:39 -04:00
}, err
}
func (ra RemoteActor) getLatestPosts(number int) (map[string]interface{}, error) {
return get(ra.outbox)
}
func get(iri string) (info map[string]interface{}, err error) {
buf := new(bytes.Buffer)
req, err := http.NewRequest("GET", iri, buf)
if err != nil {
log.Info(err)
return
}
req.Header.Add("Accept", "application/activity+json")
2019-09-10 04:21:39 -04:00
req.Header.Add("User-Agent", userAgent+" "+version)
req.Header.Add("Accept-Charset", "utf-8")
resp, err := client.Do(req)
if err != nil {
log.Info("Cannot perform the request")
log.Error(err)
2019-09-10 04:21:39 -04:00
return
}
responseData, _ := ioutil.ReadAll(resp.Body)
if !isSuccess(resp.StatusCode) {
err = fmt.Errorf("GET request to %s failed (%d): %s\nResponse: %s \nHeaders: %s", iri, resp.StatusCode, resp.Status, FormatJSON(responseData), FormatHeaders(req.Header))
log.Error(err)
2019-09-10 04:21:39 -04:00
return
}
var e interface{}
err = json.Unmarshal(responseData, &e)
if err != nil {
log.Info("something went wrong when unmarshalling the json")
log.Error(err)
return
2019-09-10 04:21:39 -04:00
}
info = e.(map[string]interface{})
return
}
2019-10-08 08:22:59 -04:00
// GetInbox returns the inbox url of the actor
func (ra RemoteActor) GetInbox() string {
return ra.inbox
}
// GetSharedInbox returns the inbox url of the actor
func (ra RemoteActor) GetSharedInbox() string {
if ra.sharedInbox == "" {
return ra.inbox
}
return ra.sharedInbox
}
2023-04-28 14:02:47 -04:00
func (ra RemoteActor) URL() string {
return ra.url
}