underbbs/server/api.go

218 lines
6 KiB
Go
Raw Permalink Normal View History

2024-05-26 18:50:19 +00:00
package server
import (
2024-05-26 23:24:49 +00:00
"encoding/json"
"errors"
2024-06-02 16:17:12 +00:00
"fmt"
2024-05-26 23:24:49 +00:00
"forge.lightcrystal.systems/lightcrystal/underbbs/adapter"
"forge.lightcrystal.systems/lightcrystal/underbbs/models"
2024-05-26 18:50:19 +00:00
"hacklab.nilfm.cc/quartzgun/renderer"
"hacklab.nilfm.cc/quartzgun/router"
2024-05-26 23:24:49 +00:00
"hacklab.nilfm.cc/quartzgun/util"
2024-05-26 18:50:19 +00:00
"html/template"
2024-09-28 17:39:03 +00:00
"log"
2024-05-26 18:50:19 +00:00
"net/http"
2024-05-26 23:24:49 +00:00
"strings"
2024-05-26 18:50:19 +00:00
)
2024-05-26 23:24:49 +00:00
func getSubscriberKey(req *http.Request) (string, error) {
authHeader := req.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
return strings.Split(authHeader, "Bearer ")[1], nil
}
return "", errors.New("No subscriber key")
}
func getSubscriberByKey(key string, subscribers map[*Subscriber][]adapter.Adapter) *Subscriber {
for s, _ := range subscribers {
if s.key == key {
return s
}
}
return nil
}
func setAdaptersForSubscriber(key string, adapters []adapter.Adapter, subscribers map[*Subscriber][]adapter.Adapter) error {
var ptr *Subscriber = nil
2024-09-28 17:39:03 +00:00
log.Print("looking for subscriber in map...")
2024-05-26 23:24:49 +00:00
for s, _ := range subscribers {
if s.key == key {
ptr = s
}
}
if ptr != nil {
2024-09-28 17:39:03 +00:00
log.Print("setting adaters for the found subscriber: " + ptr.key)
2024-05-26 23:24:49 +00:00
subscribers[ptr] = adapters
return nil
}
return errors.New("subscriber not present in map")
}
func apiConfigureAdapters(next http.Handler, subscribers map[*Subscriber][]adapter.Adapter) http.Handler {
2024-05-26 18:50:19 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
2024-05-26 23:24:49 +00:00
// get subscriber key
skey, err := getSubscriberKey(req)
if err != nil {
w.WriteHeader(500)
return
}
subscriber := getSubscriberByKey(skey, subscribers)
if subscriber == nil {
w.WriteHeader(404)
return
}
// decode adapter config from request body
settings := make([]models.Settings, 0)
err = json.NewDecoder(req.Body).Decode(&settings)
if err != nil {
w.WriteHeader(400)
next.ServeHTTP(w, req)
return
}
// iterate through settings and create adapters
adapters := make([]adapter.Adapter, 0)
for _, s := range settings {
var a adapter.Adapter
switch s.Protocol {
case "nostr":
a = &adapter.NostrAdapter{}
case "mastodon":
a = &adapter.MastoAdapter{}
case "misskey":
a = &adapter.MisskeyAdapter{}
2024-05-26 23:24:49 +00:00
default:
break
}
2024-09-28 17:39:03 +00:00
err := a.Init(s, &subscriber.data)
2024-05-26 23:24:49 +00:00
if err != nil {
util.AddContextValue(req, "data", err.Error())
w.WriteHeader(500)
next.ServeHTTP(w, req)
2024-06-02 16:17:12 +00:00
return
2024-05-26 23:24:49 +00:00
}
2024-09-28 17:39:03 +00:00
log.Print("adapter initialized - subscribing with default filter")
2024-06-02 16:17:12 +00:00
errs := a.Subscribe(a.DefaultSubscriptionFilter())
if errs != nil {
errMsg := ""
for _, e := range errs {
2024-09-28 17:39:03 +00:00
log.Print("processing an error")
2024-06-02 16:17:12 +00:00
errMsg += fmt.Sprintf("- %s\n", e.Error())
}
util.AddContextValue(req, "data", errMsg)
w.WriteHeader(500)
next.ServeHTTP(w, req)
return
}
2024-09-28 17:39:03 +00:00
log.Print("adapter ready for use; adding to array")
2024-06-02 16:17:12 +00:00
2024-05-26 23:24:49 +00:00
adapters = append(adapters, a)
2024-09-28 17:39:03 +00:00
log.Print("adapter added to array")
2024-05-26 23:24:49 +00:00
}
// TODO: cancel subscriptions on any existing adapters
// store the adapters in the subscriber map
err = setAdaptersForSubscriber(skey, adapters, subscribers)
if err != nil {
util.AddContextValue(req, "data", err.Error())
w.WriteHeader(500)
next.ServeHTTP(w, req)
}
2024-05-26 18:50:19 +00:00
w.WriteHeader(201)
next.ServeHTTP(w, req)
})
}
func apiGetAdapters(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(201)
next.ServeHTTP(w, req)
})
}
func apiAdapterSubscribe(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(201)
next.ServeHTTP(w, req)
})
}
2024-05-26 23:24:49 +00:00
func ProtectWithSubscriberKey(next http.Handler, subscribers map[*Subscriber][]adapter.Adapter) http.Handler {
2024-05-26 18:50:19 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
2024-05-26 23:24:49 +00:00
authHeader := req.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
subscriberKey := strings.Split(authHeader, "Bearer ")[1]
if getSubscriberByKey(subscriberKey, subscribers) != nil {
2024-07-07 20:54:33 +00:00
next.ServeHTTP(w, req)
return
2024-05-26 23:24:49 +00:00
}
}
w.WriteHeader(http.StatusUnauthorized)
2024-05-26 18:50:19 +00:00
})
}
func apiAdapterFetch(next http.Handler, subscribers map[*Subscriber][]adapter.Adapter) http.Handler {
2024-07-07 20:54:33 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
authHeader := req.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
subscriberKey := strings.Split(authHeader, "Bearer ")[1]
s := getSubscriberByKey(subscriberKey, subscribers)
if s != nil {
2024-07-07 20:54:33 +00:00
apiParams := req.Context().Value("params").(map[string]string)
queryParams := req.URL.Query()
for _, a := range subscribers[s] {
if a.Name() == apiParams["adapter_id"] {
err := a.Fetch(queryParams["entity_type"][0], queryParams["entity_id"])
2024-07-07 20:54:33 +00:00
if err != nil {
2024-09-28 17:39:03 +00:00
log.Print(err.Error())
2024-07-07 20:54:33 +00:00
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusAccepted)
}
next.ServeHTTP(w, req)
return
}
}
}
}
w.WriteHeader(http.StatusUnauthorized)
})
}
2024-05-26 23:24:49 +00:00
func (self *BBSServer) apiMux() http.Handler {
2024-05-26 18:50:19 +00:00
errTemplate, err := template.New("err").Parse("{{ $params := (.Context).Value \"params\" }}<html><body><h1>ERROR {{ $params.ErrorCode }}</h1><p class='error'>{{ $params.ErrorMessage }}</p></body></html>")
if err != nil {
panic("error template was malformed")
}
rtr := &router.Router{
Fallback: *errTemplate,
}
// adapters (POST & GET)
2024-05-26 23:24:49 +00:00
rtr.Post("/adapters", ProtectWithSubscriberKey(
apiConfigureAdapters(renderer.JSON("data"), self.subscribers),
self.subscribers,
))
rtr.Get("/adapters", ProtectWithSubscriberKey(
apiGetAdapters(renderer.JSON("data")),
self.subscribers,
))
2024-05-26 18:50:19 +00:00
// adapters/:name/subscribe
2024-05-26 23:24:49 +00:00
rtr.Post(`/adapters/(?P<id>\S+)/subscribe`, ProtectWithSubscriberKey(
apiAdapterSubscribe(renderer.JSON("data")),
self.subscribers,
))
2024-07-07 20:54:33 +00:00
rtr.Get(`/adapters/(?P<adapter_id>\S+)/fetch`, ProtectWithSubscriberKey(
2024-07-07 20:54:33 +00:00
apiAdapterFetch(renderer.JSON("data"), self.subscribers),
self.subscribers,
))
2024-05-26 18:50:19 +00:00
return http.HandlerFunc(rtr.ServeHTTP)
}