/
followers.go
101 lines (73 loc) · 2.42 KB
/
followers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package www
import (
"encoding/json"
"net/http"
"time"
"github.com/sfomuseum/go-activitypub"
"github.com/sfomuseum/go-activitypub/ap"
"github.com/sfomuseum/go-activitypub/uris"
)
type FollowersHandlerOptions struct {
AccountsDatabase activitypub.AccountsDatabase
FollowersDatabase activitypub.FollowersDatabase
URIs *uris.URIs
}
func FollowersHandler(opts *FollowersHandlerOptions) (http.Handler, error) {
fn := func(rsp http.ResponseWriter, req *http.Request) {
ctx := req.Context()
logger := LoggerWithRequest(req, nil)
t1 := time.Now()
defer func() {
logger.Info("Time to serve request", "ms", time.Since(t1).Milliseconds())
}()
if req.Method != http.MethodGet {
logger.Error("Method not allowed")
http.Error(rsp, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if !IsActivityStreamRequest(req, "Accept") {
logger.Error("Not activitystream request")
http.Error(rsp, "Bad request", http.StatusBadRequest)
return
}
account_name, host, err := activitypub.ParseAddressFromRequest(req)
if err != nil {
logger.Error("Failed to parse address from request", "error", err)
http.Error(rsp, "Bad request", http.StatusBadRequest)
return
}
logger = logger.With("account name", account_name)
if host != "" && host != opts.URIs.Hostname {
logger.Error("Resouce has bunk hostname", "host", host)
http.Error(rsp, "Not found", http.StatusNotFound)
return
}
acct, err := opts.AccountsDatabase.GetAccountWithName(ctx, account_name)
if err != nil {
logger.Error("Failed to retrieve account", "error", err)
if err == activitypub.ErrNotFound {
http.Error(rsp, "Not found", http.StatusNotFound)
return
}
http.Error(rsp, "Internal server error", http.StatusInternalServerError)
return
}
logger = logger.With("account id", acct.Id)
resource, err := acct.FollowersResource(ctx, opts.URIs, opts.FollowersDatabase)
if err != nil {
logger.Error("Failed to create followers resource", "error", err)
http.Error(rsp, "Internal server error", http.StatusInternalServerError)
return
}
rsp.Header().Set("Content-type", ap.ACTIVITY_CONTENT_TYPE)
enc := json.NewEncoder(rsp)
err = enc.Encode(resource)
if err != nil {
logger.Error("Failed to encode followers resource", "error", err)
http.Error(rsp, "Internal server error", http.StatusInternalServerError)
return
}
return
}
return http.HandlerFunc(fn), nil
}