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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
|
// quoting.go implements FEP-044f quote-posting logic for booster-bot.
//
// QuotePost, FollowAndQuote and DeleteQuote were originally part of the
// activitypub library but are specific to the booster-bot use-case, so they
// live here instead. They operate on an *activitypub.Server and a
// *quotingState which holds the bot-side pending-note/follow maps.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
"activitypub"
)
// ---------------------------------------------------------------------------
// Pending state
// ---------------------------------------------------------------------------
const pendingQuoteTTL = 30 * time.Second
const pendingFollowTTL = 10 * time.Second
type pendingQuote struct {
ch chan string // receives QuoteAuthorization URL on Accept
createdAt time.Time
}
type pendingFollow struct {
ch chan struct{} // closed on Accept{Follow}
createdAt time.Time
}
// quotingState holds all mutable state needed for the quote-posting workflow.
// One instance is created per actor server.
type quotingState struct {
mu sync.Mutex
// pendingNotes: notes created for a QuoteRequest but not yet in the outbox.
// Keyed by note URL.
pendingNotes map[string]map[string]any
// pendingQuotes: waiting for Accept{QuoteRequest}. Keyed by quoteRequestID.
pendingQuotes map[string]pendingQuote
// pendingFollows: waiting for Accept{Follow}. Keyed by follow activity ID.
pendingFollows map[string]pendingFollow
}
func newQuotingState() *quotingState {
return "ingState{
pendingNotes: make(map[string]map[string]any),
pendingQuotes: make(map[string]pendingQuote),
pendingFollows: make(map[string]pendingFollow),
}
}
// ---------------------------------------------------------------------------
// ServeNote hook
// ---------------------------------------------------------------------------
// serveNoteHook is the activitypub.Hooks.ServeNote implementation.
// It serves pending (pre-stamp) notes that are not yet in the outbox.
func (qs *quotingState) serveNoteHook(w http.ResponseWriter, r *http.Request, noteURL string) bool {
qs.mu.Lock()
note := qs.pendingNotes[noteURL]
qs.mu.Unlock()
if note == nil {
return false
}
w.Header().Set("Content-Type", "application/activity+json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
if err := enc.Encode(note); err != nil {
log.Printf("quoting: serveNoteHook: encode: %v", err)
}
return true
}
// ---------------------------------------------------------------------------
// Inbox hooks for QuoteRequest accept/reject and Follow accept
// ---------------------------------------------------------------------------
// onAccept is called from the library's OnAccept hook (if we add one later).
// For now booster-bot handles this by intercepting via a custom inbox hook
// — see handleAcceptHook below.
// handleAcceptActivity processes Accept{QuoteRequest} and Accept{Follow}
// activities received in the inbox. It is called by the booster-bot's OnAccept
// hook injected via the Hooks struct.
func (qs *quotingState) handleAcceptActivity(activity map[string]any) {
obj, ok := activity["object"].(map[string]any)
if !ok {
return
}
switch objType, _ := obj["type"].(string); objType {
case "Follow":
followID, _ := obj["id"].(string)
if followID != "" {
qs.resolvePendingFollow(followID)
}
case "QuoteRequest":
quoteRequestID, _ := obj["id"].(string)
var stampURL string
switch v := activity["result"].(type) {
case string:
stampURL = v
case map[string]any:
stampURL, _ = v["id"].(string)
}
log.Printf("quoting: Accept{QuoteRequest} id=%s stamp=%s", quoteRequestID, stampURL)
if quoteRequestID != "" && stampURL != "" {
qs.resolvePendingQuote(quoteRequestID, stampURL)
}
}
}
// handleRejectActivity processes Reject{QuoteRequest} activities.
func (qs *quotingState) handleRejectActivity(activity map[string]any) {
obj, ok := activity["object"].(map[string]any)
if !ok {
return
}
if objType, _ := obj["type"].(string); objType == "QuoteRequest" {
id, _ := obj["id"].(string)
if id != "" {
log.Printf("quoting: Reject{QuoteRequest} id=%s", id)
qs.rejectPendingQuote(id)
}
}
}
// ---------------------------------------------------------------------------
// QuotePost
// ---------------------------------------------------------------------------
// QuotePost creates and delivers a public Note that quote-posts objectURL
// (FEP-044f). It sends a QuoteRequest to authorActorURL's inbox and waits up
// to pendingQuoteTTL for a QuoteAuthorization stamp.
// Returns (true, nil) if the stamp arrived and the Note was delivered,
// (false, nil) on timeout/rejection (caller should fall back to Announce),
// or (false, err) on a hard error.
func QuotePost(srv *activitypub.Server, qs *quotingState, objectURL, authorActorURL string) (bool, error) {
now := time.Now().UTC().Format(time.RFC3339)
noteID := fmt.Sprintf("%s/notes/%d", srv.ActorURL(), time.Now().UnixNano())
createID := fmt.Sprintf("%s/creates/%d", srv.ActorURL(), time.Now().UnixNano())
quoteRequestID := fmt.Sprintf("%s/quote-requests/%d", srv.ActorURL(), time.Now().UnixNano())
fallback := fmt.Sprintf(
`<span class="quote-inline">RE: <a href="%s">%s</a></span>`,
objectURL, objectURL,
)
note := map[string]any{
"@context": []any{
"https://www.w3.org/ns/activitystreams",
map[string]any{
"quote": "https://w3id.org/fep/044f#quote",
"quoteUri": "http://fedibird.com/ns#quoteUri",
"_misskey_quote": "https://misskey-hub.net/ns#_misskey_quote",
"QuoteRequest": "https://w3id.org/fep/044f#QuoteRequest",
"quoteAuthorization": map[string]any{
"@id": "https://w3id.org/fep/044f#quoteAuthorization",
"@type": "@id",
},
},
},
"id": noteID,
"type": "Note",
"attributedTo": srv.ActorURL(),
"published": now,
"to": []string{"https://www.w3.org/ns/activitystreams#Public"},
"cc": []string{srv.ActorURL() + "/followers"},
"content": fallback,
"quote": objectURL,
"quoteUri": objectURL,
"_misskey_quote": objectURL,
}
createActivity := map[string]any{
"@context": "https://www.w3.org/ns/activitystreams",
"id": createID,
"type": "Create",
"actor": srv.ActorURL(),
"published": now,
"to": []string{"https://www.w3.org/ns/activitystreams#Public"},
"cc": []string{srv.ActorURL() + "/followers"},
"object": note,
}
// Store Note in pendingNotes so it's fetchable at its URL (needed by the
// remote server when processing the QuoteRequest), but do NOT add to the
// outbox yet — only do that once the stamp arrives.
qs.mu.Lock()
qs.pendingNotes[noteID] = note
qs.mu.Unlock()
// Resolve author's inbox and send QuoteRequest.
authorActor, err := srv.FetchObject(authorActorURL, activitypub.NoRedirects)
authorInbox := ""
if err == nil {
if ep, ok := authorActor["endpoints"].(map[string]any); ok {
if si, ok := ep["sharedInbox"].(string); ok && si != "" {
authorInbox = si
}
}
if authorInbox == "" {
authorInbox, _ = authorActor["inbox"].(string)
}
}
if authorInbox == "" {
log.Printf("quoting: QuotePost: resolve inbox for %s: %v — no QuoteRequest sent", authorActorURL, err)
qs.mu.Lock()
delete(qs.pendingNotes, noteID)
qs.mu.Unlock()
return false, nil
}
quoteRequest := map[string]any{
"@context": []any{
"https://www.w3.org/ns/activitystreams",
map[string]any{
"QuoteRequest": "https://w3id.org/fep/044f#QuoteRequest",
},
},
"id": quoteRequestID,
"type": "QuoteRequest",
"actor": srv.ActorURL(),
"object": objectURL,
"instrument": noteID,
"to": []string{authorActorURL},
}
ch := qs.registerPendingQuote(quoteRequestID)
if err := srv.PostToInbox(authorInbox, quoteRequest); err != nil {
// Log but don't bail — same rationale as before.
log.Printf("quoting: QuotePost: send QuoteRequest to %s: %v (still waiting for Accept)", authorInbox, err)
} else {
log.Printf("quoting: QuotePost: sent QuoteRequest %s to %s, waiting up to %s", quoteRequestID, authorInbox, pendingQuoteTTL)
}
// Wait for QuoteAuthorization stamp.
select {
case stampURL, ok := <-ch:
if !ok || stampURL == "" {
log.Printf("quoting: QuotePost: quote request rejected/expired for %s", objectURL)
qs.mu.Lock()
delete(qs.pendingNotes, noteID)
qs.mu.Unlock()
return false, nil
}
log.Printf("quoting: QuotePost: got stamp %s for %s", stampURL, objectURL)
qs.mu.Lock()
delete(qs.pendingNotes, noteID)
qs.mu.Unlock()
note["quoteAuthorization"] = stampURL
if err := srv.PublishCreate(createActivity); err != nil {
log.Printf("quoting: QuotePost: publish Create: %v", err)
return false, err
}
return true, nil
case <-time.After(pendingQuoteTTL):
log.Printf("quoting: QuotePost: timeout waiting for stamp for %s", objectURL)
qs.mu.Lock()
delete(qs.pendingNotes, noteID)
qs.mu.Unlock()
// Fire-and-forget a Delete{QuoteRequest} to retract the request.
go func() {
deleteActivity := map[string]any{
"@context": "https://www.w3.org/ns/activitystreams",
"id": fmt.Sprintf("%s#delete/%d", quoteRequestID, time.Now().UnixNano()),
"type": "Delete",
"actor": srv.ActorURL(),
"object": quoteRequestID,
"to": []string{authorActorURL},
}
if err := srv.PostToInbox(authorInbox, deleteActivity); err != nil {
log.Printf("quoting: QuotePost: send Delete{QuoteRequest}: %v", err)
}
}()
return false, nil
}
}
// ---------------------------------------------------------------------------
// DeleteQuote
// ---------------------------------------------------------------------------
// DeleteQuote sends a Delete{Note} for any Create{Note} quote-post of
// objectURL in the outbox, replaces it with a Tombstone, and delivers the
// Delete to all followers. Matches against the Note's "quote" field inside
// the Create object.
func DeleteQuote(srv *activitypub.Server, objectURL string) error {
return srv.DeleteCreate(objectURL)
}
// ---------------------------------------------------------------------------
// FollowAndQuote
// ---------------------------------------------------------------------------
// FollowAndQuote follows authorActorURL, waits for the Accept{Follow}, then
// calls QuotePost. The follow is undone afterwards regardless of outcome.
// If the bot is already following the author, it skips straight to QuotePost.
func FollowAndQuote(srv *activitypub.Server, qs *quotingState, objectURL, authorActorURL string) (bool, error) {
followID, ch, err := qs.sendFollow(srv, authorActorURL)
if err != nil {
return false, err
}
select {
case <-ch:
log.Printf("quoting: FollowAndQuote: follow accepted by %s, proceeding with QuotePost", authorActorURL)
approved, err := QuotePost(srv, qs, objectURL, authorActorURL)
go qs.sendUnfollow(srv, authorActorURL, followID)
return approved, err
case <-time.After(pendingFollowTTL):
log.Printf("quoting: FollowAndQuote: follow not accepted by %s within %s", authorActorURL, pendingFollowTTL)
return false, nil
}
}
// ---------------------------------------------------------------------------
// Follow helpers
// ---------------------------------------------------------------------------
func (qs *quotingState) sendFollow(srv *activitypub.Server, actorURL string) (followID string, ch <-chan struct{}, err error) {
inbox, err := srv.ResolveInbox(actorURL)
if err != nil {
return "", nil, fmt.Errorf("resolve inbox for follow: %w", err)
}
followID = fmt.Sprintf("%s/follows/%d", srv.ActorURL(), time.Now().UnixNano())
follow := map[string]any{
"@context": "https://www.w3.org/ns/activitystreams",
"id": followID,
"type": "Follow",
"actor": srv.ActorURL(),
"object": actorURL,
}
ch = qs.registerPendingFollow(followID)
if err := srv.PostToInbox(inbox, follow); err != nil {
return "", nil, fmt.Errorf("post Follow: %w", err)
}
log.Printf("quoting: sent Follow %s to %s", followID, inbox)
return followID, ch, nil
}
func (qs *quotingState) sendUnfollow(srv *activitypub.Server, actorURL, followID string) {
inbox, err := srv.ResolveInbox(actorURL)
if err != nil {
log.Printf("quoting: sendUnfollow: resolve inbox for %s: %v", actorURL, err)
return
}
undo := map[string]any{
"@context": "https://www.w3.org/ns/activitystreams",
"id": fmt.Sprintf("%s#unfollows/%d", srv.ActorURL(), time.Now().UnixNano()),
"type": "Undo",
"actor": srv.ActorURL(),
"object": map[string]any{
"id": followID,
"type": "Follow",
"actor": srv.ActorURL(),
"object": actorURL,
},
}
if err := srv.PostToInbox(inbox, undo); err != nil {
log.Printf("quoting: sendUnfollow: post Undo{Follow} to %s: %v", inbox, err)
}
srv.RemoveFollowing(actorURL)
log.Printf("quoting: sent Undo{Follow} %s to %s", followID, inbox)
}
// ---------------------------------------------------------------------------
// Actor HTML profile page
// ---------------------------------------------------------------------------
// actorHTML renders a minimal HTML profile page for the actor, showing recent
// boosts and quotes. It is registered as the OnHTML hook so browsers get a
// human-readable page while AP clients receive the actor JSON document.
func actorHTML(w http.ResponseWriter, srv *activitypub.Server) {
items := buildOutboxItems(srv.Outbox(), "")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@%s@%s</title>
<style>
:root {
--bg: #ffffff; --bg2: #f4f4f4; --fg: #222222; --fg2: #666666;
--accent: #1d6fa5; --border: #dddddd; --border2: #eeeeee;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #1a1a1a; --bg2: #2a2a2a; --fg: #e8e8e8; --fg2: #aaaaaa;
--accent: #4da3d8; --border: #444444; --border2: #333333;
}
}
body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto;
padding: 0 1rem; background: var(--bg); color: var(--fg); }
h1 { margin-bottom: 0.25rem; }
.handle { color: var(--fg2); margin-top: 0; }
.stats { color: var(--fg2); font-size: 0.9rem; margin-bottom: 1.5rem; }
h2 { border-bottom: 1px solid var(--border); padding-bottom: 0.25rem; }
ul { list-style: none; padding: 0; }
li { padding: 0.6rem 0; border-bottom: 1px solid var(--border2); word-break: break-all; }
li:last-child { border-bottom: none; }
a { color: var(--accent); }
.ts { color: var(--fg2); font-size: 0.85rem; margin-top: 0.2rem; }
.kind { font-size: 0.8rem; font-weight: bold; text-transform: uppercase;
letter-spacing: 0.05em; color: var(--fg2); margin-bottom: 0.15rem; }
.snippet { color: var(--fg2); font-size: 0.9rem; margin-top: 0.2rem; font-style: italic; }
.empty { color: var(--fg2); font-style: italic; }
</style>
</head>
<body>
<h1>@%s@%s</h1>
<p class="stats"><a href="%s?format=json">AP actor JSON</a></p>
<h2>Recent activity</h2>
`,
srv.ActorName(), srv.Domain(),
srv.ActorName(), srv.Domain(),
srv.ActorURL(),
)
if len(items) == 0 {
fmt.Fprintf(w, `<p class="empty">No activity yet.</p>`)
} else {
fmt.Fprintf(w, "<ul>\n")
for _, item := range items {
fmt.Fprintf(w, " <li>\n")
fmt.Fprintf(w, " <div class=\"kind\">%s</div>\n", item.Kind)
fmt.Fprintf(w, " <a href=\"%s\">%s</a>\n", item.Object, item.Object)
if item.Snippet != "" {
fmt.Fprintf(w, " <div class=\"snippet\">%s</div>\n", item.Snippet)
}
fmt.Fprintf(w, " <div class=\"ts\">%s</div>\n", item.Published)
fmt.Fprintf(w, " </li>\n")
}
fmt.Fprintf(w, "</ul>\n")
}
fmt.Fprintf(w, "</body>\n</html>\n")
}
// ---------------------------------------------------------------------------
// Pending quote helpers
// ---------------------------------------------------------------------------
func (qs *quotingState) registerPendingQuote(quoteRequestID string) chan string {
ch := make(chan string, 1)
qs.mu.Lock()
defer qs.mu.Unlock()
for id, pq := range qs.pendingQuotes {
if time.Since(pq.createdAt) > pendingQuoteTTL {
close(pq.ch)
delete(qs.pendingQuotes, id)
}
}
qs.pendingQuotes[quoteRequestID] = pendingQuote{ch: ch, createdAt: time.Now()}
return ch
}
func (qs *quotingState) resolvePendingQuote(quoteRequestID, stampURL string) {
qs.mu.Lock()
pq, ok := qs.pendingQuotes[quoteRequestID]
if ok {
delete(qs.pendingQuotes, quoteRequestID)
}
qs.mu.Unlock()
if ok {
pq.ch <- stampURL
}
}
func (qs *quotingState) rejectPendingQuote(quoteRequestID string) {
qs.mu.Lock()
pq, ok := qs.pendingQuotes[quoteRequestID]
if ok {
delete(qs.pendingQuotes, quoteRequestID)
}
qs.mu.Unlock()
if ok {
pq.ch <- "" // empty string signals rejection
}
}
// ---------------------------------------------------------------------------
// Pending follow helpers
// ---------------------------------------------------------------------------
func (qs *quotingState) registerPendingFollow(followID string) <-chan struct{} {
ch := make(chan struct{}, 1)
qs.mu.Lock()
defer qs.mu.Unlock()
for id, pf := range qs.pendingFollows {
if time.Since(pf.createdAt) > pendingFollowTTL {
close(pf.ch)
delete(qs.pendingFollows, id)
}
}
qs.pendingFollows[followID] = pendingFollow{ch: ch, createdAt: time.Now()}
return ch
}
func (qs *quotingState) resolvePendingFollow(followID string) {
qs.mu.Lock()
pf, ok := qs.pendingFollows[followID]
if ok {
delete(qs.pendingFollows, followID)
}
qs.mu.Unlock()
if ok {
close(pf.ch)
}
}
|