home/internal/entry/delivery/http/entry_http.go

105 lines
2.9 KiB
Go

package http
import (
"context"
"encoding/json"
"fmt"
"mime"
"net/http"
"github.com/go-ap/activitypub"
"source.toby3d.me/toby3d/home/internal/common"
"source.toby3d.me/toby3d/home/internal/domain"
"source.toby3d.me/toby3d/home/internal/entry"
"source.toby3d.me/toby3d/home/internal/site"
)
type (
Handler struct {
entries entry.UseCase
}
ActivityPubHandler struct{}
/* TODO(toby3d)
Profile struct {
*activitypub.Person
// Mastodon related
// Pinned posts. See [Featured collection].
//
// [Featured collection]: https://docs.joinmastodon.org/spec/activitypub/#featured
Featured []interface{} `json:"featured"`
// Required for Move activity.
AlsoKnownAs []string `json:"alsoKnownAs"`
// Will be shown as a locked account.
ManuallyApprovesFollowers bool `json:"manuallyApprovesFollowers"`
// Will be shown in the profile directory.
// See [Discoverability flag].
//
// [Discoverability flag]: https://docs.joinmastodon.org/spec/activitypub/#discoverable
Discoverable bool `json:"discoverable"`
}
*/
)
func NewHandler(sites site.UseCase, entries entry.UseCase) *Handler {
return &Handler{
entries: entries,
}
}
func (h *Handler) Handle(ctx context.Context, site *domain.Site, path string) (*domain.Entry, http.Handler, error) {
entry, err := h.entries.Do(ctx, site.Language, path)
if err != nil {
return nil, nil, fmt.Errorf("cannot handle entry: %w", err)
}
return entry, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contentType, _, _ := mime.ParseMediaType(r.Header.Get(common.HeaderAccept))
switch contentType {
case common.MIMEApplicationLdJSON:
h.ActivityPubHandler.Handle(s, e).ServeHTTP(w, r)
}
}), nil
}
func NewActivityPubHandler() *ActivityPubHandler {
return &ActivityPubHandler{}
}
func (ActivityPubHandler) Handle(s *domain.Site, e *domain.Entry) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set(common.HeaderContentType, common.MIMEApplicationActivityJSONCharsetUTF8)
encoder := json.NewEncoder(w)
/* TODO(toby3d): handle profiles on root page.
if head == "" { // NOTE(toby3d): base URL point to owner Profile.
langRef := activitypub.LangRef(lang.Lang())
person := activitypub.PersonNew(activitypub.IRI(s.BaseURL.String()))
person.URL = person.ID
person.Name.Add(activitypub.LangRefValueNew(langRef, "Maxim Lebedev"))
person.Summary.Add(activitypub.LangRefValueNew(langRef, "Creative dude from russia"))
person.PreferredUsername.Add(activitypub.LangRefValueNew(langRef, "toby3d"))
person.Published = time.Date(2009, time.February, 0, 0, 0, 0, 0, time.UTC)
_ = encoder.Encode(person)
return
}
*/
resp := activitypub.ObjectNew(activitypub.NoteType)
resp.ID = activitypub.ID(s.BaseURL.JoinPath(e.File.Path()).String())
resp.Content.Add(activitypub.LangRefValueNew(activitypub.NilLangRef, string(e.Content)))
_ = encoder.Encode(resp)
})
}