activity.go (view raw)
1//
2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
3//
4// Permission to use, copy, modify, and distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19 "bytes"
20 "compress/gzip"
21 "crypto/rsa"
22 "database/sql"
23 "encoding/json"
24 "fmt"
25 "io"
26 "log"
27 "net/http"
28 "net/url"
29 "os"
30 "strconv"
31 "strings"
32 "sync"
33 "time"
34)
35
36func NewJunk() map[string]interface{} {
37 return make(map[string]interface{})
38}
39
40func WriteJunk(w io.Writer, j map[string]interface{}) error {
41 e := json.NewEncoder(w)
42 e.SetEscapeHTML(false)
43 e.SetIndent("", " ")
44 err := e.Encode(j)
45 return err
46}
47
48func ReadJunk(r io.Reader) (map[string]interface{}, error) {
49 decoder := json.NewDecoder(r)
50 var j map[string]interface{}
51 err := decoder.Decode(&j)
52 if err != nil {
53 return nil, err
54 }
55 return j, nil
56}
57
58var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
59var falsenames = []string{
60 `application/ld+json`,
61 `application/activity+json`,
62}
63var itiswhatitis = "https://www.w3.org/ns/activitystreams"
64var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
65
66func friendorfoe(ct string) bool {
67 ct = strings.ToLower(ct)
68 for _, at := range falsenames {
69 if strings.HasPrefix(ct, at) {
70 return true
71 }
72 }
73 return false
74}
75
76func PostJunk(keyname string, key *rsa.PrivateKey, url string, j map[string]interface{}) error {
77 var buf bytes.Buffer
78 WriteJunk(&buf, j)
79 return PostMsg(keyname, key, url, buf.Bytes())
80}
81
82func PostMsg(keyname string, key *rsa.PrivateKey, url string, msg []byte) error {
83 client := http.DefaultClient
84 req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
85 if err != nil {
86 return err
87 }
88 req.Header.Set("Content-Type", theonetruename)
89 zig(keyname, key, req, msg)
90 resp, err := client.Do(req)
91 if err != nil {
92 return err
93 }
94 if resp.StatusCode != 200 && resp.StatusCode != 202 {
95 resp.Body.Close()
96 return fmt.Errorf("http post status: %d", resp.StatusCode)
97 }
98 log.Printf("successful post: %s %d", url, resp.StatusCode)
99 return nil
100}
101
102type gzCloser struct {
103 r *gzip.Reader
104 under io.ReadCloser
105}
106
107func (gz *gzCloser) Read(p []byte) (int, error) {
108 return gz.r.Read(p)
109}
110
111func (gz *gzCloser) Close() error {
112 defer gz.under.Close()
113 return gz.r.Close()
114}
115
116func GetJunk(url string) (map[string]interface{}, error) {
117 client := http.DefaultClient
118 req, err := http.NewRequest("GET", url, nil)
119 if err != nil {
120 return nil, err
121 }
122 at := theonetruename
123 if strings.Contains(url, ".well-known/webfinger?resource") {
124 at = "application/jrd+json"
125 }
126 req.Header.Set("Accept", at)
127 req.Header.Set("Accept-Encoding", "gzip")
128 resp, err := client.Do(req)
129 if err != nil {
130 return nil, err
131 }
132 if resp.StatusCode != 200 {
133 resp.Body.Close()
134 return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
135 }
136 if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
137 gz, err := gzip.NewReader(resp.Body)
138 if err != nil {
139 resp.Body.Close()
140 return nil, err
141 }
142 resp.Body = &gzCloser{r: gz, under: resp.Body}
143 }
144 defer resp.Body.Close()
145 j, err := ReadJunk(resp.Body)
146 return j, err
147}
148
149func jsonfindinterface(ii interface{}, keys []string) interface{} {
150 for _, key := range keys {
151 idx, err := strconv.Atoi(key)
152 if err == nil {
153 m := ii.([]interface{})
154 if idx >= len(m) {
155 return nil
156 }
157 ii = m[idx]
158 } else {
159 m := ii.(map[string]interface{})
160 ii = m[key]
161 if ii == nil {
162 return nil
163 }
164 }
165 }
166 return ii
167}
168func jsonfindstring(j interface{}, keys []string) (string, bool) {
169 s, ok := jsonfindinterface(j, keys).(string)
170 return s, ok
171}
172func jsonfindarray(j interface{}, keys []string) ([]interface{}, bool) {
173 a, ok := jsonfindinterface(j, keys).([]interface{})
174 return a, ok
175}
176func jsonfindmap(j interface{}, keys []string) (map[string]interface{}, bool) {
177 m, ok := jsonfindinterface(j, keys).(map[string]interface{})
178 return m, ok
179}
180func jsongetstring(j interface{}, key string) (string, bool) {
181 return jsonfindstring(j, []string{key})
182}
183func jsongetarray(j interface{}, key string) ([]interface{}, bool) {
184 return jsonfindarray(j, []string{key})
185}
186func jsongetmap(j interface{}, key string) (map[string]interface{}, bool) {
187 return jsonfindmap(j, []string{key})
188}
189
190func savedonk(url string, name, media string) *Donk {
191 var donk Donk
192 row := stmtFindFile.QueryRow(url)
193 err := row.Scan(&donk.FileID)
194 if err == nil {
195 return &donk
196 }
197 log.Printf("saving donk: %s", url)
198 if err != nil && err != sql.ErrNoRows {
199 log.Printf("error querying: %s", err)
200 }
201 resp, err := http.Get(url)
202 if err != nil {
203 log.Printf("error fetching %s: %s", url, err)
204 return nil
205 }
206 defer resp.Body.Close()
207 if resp.StatusCode != 200 {
208 return nil
209 }
210 var buf bytes.Buffer
211 io.Copy(&buf, resp.Body)
212
213 xid := xfiltrate()
214
215 res, err := stmtSaveFile.Exec(xid, name, url, media, buf.Bytes())
216 if err != nil {
217 log.Printf("error saving file %s: %s", url, err)
218 return nil
219 }
220 donk.FileID, _ = res.LastInsertId()
221 return &donk
222}
223
224func needxonk(user *WhatAbout, x *Honk) bool {
225 if strings.HasPrefix(x.XID, user.URL+"/h/") {
226 return false
227 }
228 if x.What == "eradicate" {
229 return true
230 }
231 row := stmtFindXonk.QueryRow(user.ID, x.XID)
232 err := row.Scan(&x.ID)
233 if err == nil {
234 return false
235 }
236 if err != sql.ErrNoRows {
237 log.Printf("err querying xonk: %s", err)
238 }
239 return true
240}
241
242func savexonk(x *Honk) {
243 if x.What == "eradicate" {
244 log.Printf("eradicating %s by %s", x.RID, x.Honker)
245 _, err := stmtDeleteHonk.Exec(x.RID, x.Honker)
246 if err != nil {
247 log.Printf("error eradicating: %s", err)
248 }
249 return
250 }
251 dt := x.Date.UTC().Format(dbtimeformat)
252 aud := strings.Join(x.Audience, " ")
253 res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud, x.Noise)
254 if err != nil {
255 log.Printf("err saving xonk: %s", err)
256 return
257 }
258 x.ID, _ = res.LastInsertId()
259 for _, d := range x.Donks {
260 _, err = stmtSaveDonk.Exec(x.ID, d.FileID)
261 if err != nil {
262 log.Printf("err saving donk: %s", err)
263 return
264 }
265 }
266}
267
268type Box struct {
269 In string
270 Out string
271 Shared string
272}
273
274var boxofboxes = make(map[string]*Box)
275var boxlock sync.Mutex
276
277func getboxes(ident string) (*Box, error) {
278 boxlock.Lock()
279 b, ok := boxofboxes[ident]
280 boxlock.Unlock()
281 if ok {
282 return b, nil
283 }
284 j, err := GetJunk(ident)
285 if err != nil {
286 return nil, err
287 }
288 inbox, _ := jsongetstring(j, "inbox")
289 outbox, _ := jsongetstring(j, "outbox")
290 sbox, _ := jsonfindstring(j, []string{"endpoints", "sharedInbox"})
291 b = &Box{In: inbox, Out: outbox, Shared: sbox}
292 boxlock.Lock()
293 boxofboxes[ident] = b
294 boxlock.Unlock()
295 return b, nil
296}
297
298func peeppeep() {
299 user, _ := butwhatabout("")
300 honkers := gethonkers(user.ID)
301 for _, f := range honkers {
302 if f.Flavor != "peep" {
303 continue
304 }
305 log.Printf("getting updates: %s", f.XID)
306 box, err := getboxes(f.XID)
307 if err != nil {
308 log.Printf("error getting outbox: %s", err)
309 continue
310 }
311 log.Printf("getting outbox")
312 j, err := GetJunk(box.Out)
313 if err != nil {
314 log.Printf("err: %s", err)
315 continue
316 }
317 t, _ := jsongetstring(j, "type")
318 if t == "OrderedCollection" {
319 items, _ := jsongetarray(j, "orderedItems")
320 if items == nil {
321 page1, _ := jsongetstring(j, "first")
322 j, err = GetJunk(page1)
323 if err != nil {
324 log.Printf("err: %s", err)
325 continue
326 }
327 items, _ = jsongetarray(j, "orderedItems")
328 }
329
330 for _, item := range items {
331 xonk := xonkxonk(item)
332 if xonk != nil && needxonk(user, xonk) {
333 xonk.UserID = user.ID
334 savexonk(xonk)
335 }
336 }
337 }
338 }
339}
340
341func whosthere(xid string) []string {
342 obj, err := GetJunk(xid)
343 if err != nil {
344 log.Printf("error getting remote xonk: %s", err)
345 return nil
346 }
347 return newphone(nil, obj)
348}
349
350func newphone(a []string, obj map[string]interface{}) []string {
351 for _, addr := range []string{"to", "cc", "attributedTo"} {
352 who, _ := jsongetstring(obj, addr)
353 if who != "" {
354 a = append(a, who)
355 }
356 whos, _ := jsongetarray(obj, addr)
357 for _, w := range whos {
358 who, _ := w.(string)
359 if who != "" {
360 a = append(a, who)
361 }
362 }
363 }
364 return a
365}
366
367func xonkxonk(item interface{}) *Honk {
368 // id, _ := jsongetstring(item, "id")
369 what, _ := jsongetstring(item, "type")
370 dt, _ := jsongetstring(item, "published")
371
372 var audience []string
373 var err error
374 var xid, rid, url, content string
375 var obj map[string]interface{}
376 switch what {
377 case "Announce":
378 xid, _ = jsongetstring(item, "object")
379 log.Printf("getting bonk: %s", xid)
380 obj, err = GetJunk(xid)
381 if err != nil {
382 log.Printf("error regetting: %s", err)
383 }
384 what = "bonk"
385 case "Create":
386 obj, _ = jsongetmap(item, "object")
387 what = "honk"
388 case "Delete":
389 obj, _ = jsongetmap(item, "object")
390 rid, _ = jsongetstring(item, "object")
391 what = "eradicate"
392 default:
393 log.Printf("unknown activity: %s", what)
394 return nil
395 }
396 who, _ := jsongetstring(item, "actor")
397
398 var xonk Honk
399 if obj != nil {
400 ot, _ := jsongetstring(obj, "type")
401 url, _ = jsongetstring(obj, "url")
402 if ot == "Note" || ot == "Article" {
403 audience = newphone(audience, obj)
404 xid, _ = jsongetstring(obj, "id")
405 content, _ = jsongetstring(obj, "content")
406 summary, _ := jsongetstring(obj, "summary")
407 if summary != "" {
408 content = "<p>summary: " + summary + content
409 }
410 rid, _ = jsongetstring(obj, "inReplyTo")
411 if what == "honk" && rid != "" {
412 what = "tonk"
413 }
414 }
415 if ot == "Tombstone" {
416 rid, _ = jsongetstring(obj, "id")
417 }
418 atts, _ := jsongetarray(obj, "attachment")
419 for _, att := range atts {
420 at, _ := jsongetstring(att, "type")
421 mt, _ := jsongetstring(att, "mediaType")
422 u, _ := jsongetstring(att, "url")
423 name, _ := jsongetstring(att, "name")
424 if at == "Document" {
425 mt = strings.ToLower(mt)
426 log.Printf("attachment: %s %s", mt, u)
427 if mt == "image/jpeg" || mt == "image/png" ||
428 mt == "image/gif" || mt == "text/plain" {
429 donk := savedonk(u, name, mt)
430 if donk != nil {
431 xonk.Donks = append(xonk.Donks, donk)
432 }
433 }
434 }
435 }
436 tags, _ := jsongetarray(obj, "tag")
437 for _, tag := range tags {
438 tt, _ := jsongetstring(tag, "type")
439 name, _ := jsongetstring(tag, "name")
440 if tt == "Emoji" {
441 icon, _ := jsongetmap(tag, "icon")
442 mt, _ := jsongetstring(icon, "mediaType")
443 u, _ := jsongetstring(icon, "url")
444 donk := savedonk(u, name, mt)
445 if donk != nil {
446 xonk.Donks = append(xonk.Donks, donk)
447 }
448 }
449 }
450 }
451 audience = append(audience, who)
452
453 audience = oneofakind(audience)
454
455 xonk.What = what
456 xonk.Honker = who
457 xonk.XID = xid
458 xonk.RID = rid
459 xonk.Date, _ = time.Parse(time.RFC3339, dt)
460 xonk.URL = url
461 xonk.Noise = content
462 xonk.Audience = audience
463
464 return &xonk
465}
466
467func rubadubdub(user *WhatAbout, req map[string]interface{}) {
468 xid, _ := jsongetstring(req, "id")
469 reqactor, _ := jsongetstring(req, "actor")
470 j := NewJunk()
471 j["@context"] = itiswhatitis
472 j["id"] = user.URL + "/dub/" + xid
473 j["type"] = "Accept"
474 j["actor"] = user.URL
475 j["to"] = reqactor
476 j["published"] = time.Now().UTC().Format(time.RFC3339)
477 j["object"] = req
478
479 WriteJunk(os.Stdout, j)
480
481 actor, _ := jsongetstring(req, "actor")
482 box, err := getboxes(actor)
483 if err != nil {
484 log.Printf("can't get dub box: %s", err)
485 return
486 }
487 keyname, key := ziggy(user.Name)
488 err = PostJunk(keyname, key, box.In, j)
489 if err != nil {
490 log.Printf("can't rub a dub: %s", err)
491 return
492 }
493 stmtSaveDub.Exec(user.ID, actor, actor, "dub")
494}
495
496func subsub(user *WhatAbout, xid string) {
497 j := NewJunk()
498 j["@context"] = itiswhatitis
499 j["id"] = user.URL + "/sub/" + xid
500 j["type"] = "Follow"
501 j["actor"] = user.URL
502 j["to"] = xid
503 j["object"] = xid
504 j["published"] = time.Now().UTC().Format(time.RFC3339)
505
506 box, err := getboxes(xid)
507 if err != nil {
508 log.Printf("can't send follow: %s", err)
509 return
510 }
511 WriteJunk(os.Stdout, j)
512 keyname, key := ziggy(user.Name)
513 err = PostJunk(keyname, key, box.In, j)
514 if err != nil {
515 log.Printf("failed to subsub: %s", err)
516 }
517}
518
519func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
520 dt := h.Date.Format(time.RFC3339)
521 var jo map[string]interface{}
522 j := NewJunk()
523 j["id"] = user.URL + "/" + h.What + "/" + h.XID
524 j["actor"] = user.URL
525 j["published"] = dt
526 j["to"] = h.Audience[0]
527 if len(h.Audience) > 1 {
528 j["cc"] = h.Audience[1:]
529 }
530
531 switch h.What {
532 case "zonk":
533 fallthrough
534 case "tonk":
535 fallthrough
536 case "honk":
537 j["type"] = "Create"
538 if h.What == "zonk" {
539 j["type"] = "Delete"
540 }
541
542 jo = NewJunk()
543 jo["id"] = user.URL + "/h/" + h.XID
544 jo["type"] = "Note"
545 if h.What == "zonk" {
546 jo["type"] = "Tombstone"
547 }
548 jo["published"] = dt
549 jo["url"] = user.URL + "/h/" + h.XID
550 jo["attributedTo"] = user.URL
551 if h.RID != "" {
552 jo["inReplyTo"] = h.RID
553 }
554 jo["to"] = h.Audience[0]
555 if len(h.Audience) > 1 {
556 jo["cc"] = h.Audience[1:]
557 }
558 jo["content"] = h.Noise
559 jo["summary"] = nil
560 var tags []interface{}
561 g := bunchofgrapes(h.Noise)
562 for _, m := range g {
563 t := NewJunk()
564 t["type"] = "Mention"
565 t["name"] = m.who
566 t["href"] = m.where
567 tags = append(tags, t)
568 }
569 herd := herdofemus(h.Noise)
570 for _, e := range herd {
571 t := NewJunk()
572 t["id"] = e.ID
573 t["type"] = "Emoji"
574 t["name"] = e.Name
575 i := NewJunk()
576 i["type"] = "Image"
577 i["mediaType"] = "image/png"
578 i["url"] = e.ID
579 t["icon"] = i
580 tags = append(tags, t)
581 }
582 if len(tags) > 0 {
583 jo["tag"] = tags
584 }
585 var atts []interface{}
586 for _, d := range h.Donks {
587 if re_emus.MatchString(d.Name) {
588 continue
589 }
590 jd := NewJunk()
591 jd["mediaType"] = d.Media
592 jd["name"] = d.Name
593 jd["type"] = "Document"
594 jd["url"] = d.URL
595 atts = append(atts, jd)
596 }
597 if len(atts) > 0 {
598 jo["attachment"] = atts
599 }
600 j["object"] = jo
601 case "bonk":
602 j["type"] = "Announce"
603 j["object"] = h.XID
604 }
605
606 return j, jo
607}
608
609func honkworldwide(user *WhatAbout, honk *Honk) {
610 jonk, _ := jonkjonk(user, honk)
611 jonk["@context"] = itiswhatitis
612 var buf bytes.Buffer
613 WriteJunk(&buf, jonk)
614 msg := buf.Bytes()
615
616 rcpts := make(map[string]bool)
617 for _, a := range honk.Audience {
618 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
619 box, _ := getboxes(a)
620 if box != nil && box.Shared != "" {
621 rcpts["%"+box.Shared] = true
622 } else {
623 rcpts[a] = true
624 }
625 }
626 }
627 for _, f := range getdubs(user.ID) {
628 box, _ := getboxes(f.XID)
629 if box != nil && box.Shared != "" {
630 rcpts["%"+box.Shared] = true
631 } else {
632 rcpts[f.XID] = true
633 }
634 }
635 for a := range rcpts {
636 deliverate(0, user.Name, a, msg)
637 }
638}
639
640func asjonker(user *WhatAbout) map[string]interface{} {
641 about := obfusbreak(user.About)
642
643 j := NewJunk()
644 j["@context"] = itiswhatitis
645 j["id"] = user.URL
646 j["type"] = "Person"
647 j["inbox"] = user.URL + "/inbox"
648 j["outbox"] = user.URL + "/outbox"
649 j["name"] = user.Display
650 j["preferredUsername"] = user.Name
651 j["summary"] = about
652 j["url"] = user.URL
653 a := NewJunk()
654 a["type"] = "icon"
655 a["mediaType"] = "image/png"
656 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
657 j["icon"] = a
658 k := NewJunk()
659 k["id"] = user.URL + "#key"
660 k["owner"] = user.URL
661 k["publicKeyPem"] = user.Key
662 j["publicKey"] = k
663
664 return j
665}