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 thefakename = `application/activity+json`
60var falsenames = []string{
61 `application/ld+json`,
62 `application/activity+json`,
63}
64var itiswhatitis = "https://www.w3.org/ns/activitystreams"
65var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
66
67func friendorfoe(ct string) bool {
68 ct = strings.ToLower(ct)
69 for _, at := range falsenames {
70 if strings.HasPrefix(ct, at) {
71 return true
72 }
73 }
74 return false
75}
76
77func PostJunk(keyname string, key *rsa.PrivateKey, url string, j map[string]interface{}) error {
78 var buf bytes.Buffer
79 WriteJunk(&buf, j)
80 return PostMsg(keyname, key, url, buf.Bytes())
81}
82
83func PostMsg(keyname string, key *rsa.PrivateKey, url string, msg []byte) error {
84 client := http.DefaultClient
85 req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
86 if err != nil {
87 return err
88 }
89 req.Header.Set("Content-Type", theonetruename)
90 zig(keyname, key, req, msg)
91 resp, err := client.Do(req)
92 if err != nil {
93 return err
94 }
95 resp.Body.Close()
96 switch resp.StatusCode {
97 case 200:
98 case 201:
99 case 202:
100 default:
101 return fmt.Errorf("http post status: %d", resp.StatusCode)
102 }
103 log.Printf("successful post: %s %d", url, resp.StatusCode)
104 return nil
105}
106
107type gzCloser struct {
108 r *gzip.Reader
109 under io.ReadCloser
110}
111
112func (gz *gzCloser) Read(p []byte) (int, error) {
113 return gz.r.Read(p)
114}
115
116func (gz *gzCloser) Close() error {
117 defer gz.under.Close()
118 return gz.r.Close()
119}
120
121func GetJunk(url string) (map[string]interface{}, error) {
122 client := http.DefaultClient
123 req, err := http.NewRequest("GET", url, nil)
124 if err != nil {
125 return nil, err
126 }
127 at := thefakename
128 if strings.Contains(url, ".well-known/webfinger?resource") {
129 at = "application/jrd+json"
130 }
131 req.Header.Set("Accept", at)
132 req.Header.Set("Accept-Encoding", "gzip")
133 resp, err := client.Do(req)
134 if err != nil {
135 return nil, err
136 }
137 if resp.StatusCode != 200 {
138 resp.Body.Close()
139 return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
140 }
141 if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
142 gz, err := gzip.NewReader(resp.Body)
143 if err != nil {
144 resp.Body.Close()
145 return nil, err
146 }
147 resp.Body = &gzCloser{r: gz, under: resp.Body}
148 }
149 defer resp.Body.Close()
150 j, err := ReadJunk(resp.Body)
151 return j, err
152}
153
154func jsonfindinterface(ii interface{}, keys []string) interface{} {
155 for _, key := range keys {
156 idx, err := strconv.Atoi(key)
157 if err == nil {
158 m := ii.([]interface{})
159 if idx >= len(m) {
160 return nil
161 }
162 ii = m[idx]
163 } else {
164 m := ii.(map[string]interface{})
165 ii = m[key]
166 if ii == nil {
167 return nil
168 }
169 }
170 }
171 return ii
172}
173func jsonfindstring(j interface{}, keys []string) (string, bool) {
174 s, ok := jsonfindinterface(j, keys).(string)
175 return s, ok
176}
177func jsonfindarray(j interface{}, keys []string) ([]interface{}, bool) {
178 a, ok := jsonfindinterface(j, keys).([]interface{})
179 return a, ok
180}
181func jsonfindmap(j interface{}, keys []string) (map[string]interface{}, bool) {
182 m, ok := jsonfindinterface(j, keys).(map[string]interface{})
183 return m, ok
184}
185func jsongetstring(j interface{}, key string) (string, bool) {
186 return jsonfindstring(j, []string{key})
187}
188func jsongetarray(j interface{}, key string) ([]interface{}, bool) {
189 return jsonfindarray(j, []string{key})
190}
191func jsongetmap(j interface{}, key string) (map[string]interface{}, bool) {
192 return jsonfindmap(j, []string{key})
193}
194
195func savedonk(url string, name, media string) *Donk {
196 var donk Donk
197 row := stmtFindFile.QueryRow(url)
198 err := row.Scan(&donk.FileID)
199 if err == nil {
200 return &donk
201 }
202 log.Printf("saving donk: %s", url)
203 if err != nil && err != sql.ErrNoRows {
204 log.Printf("error querying: %s", err)
205 }
206 resp, err := http.Get(url)
207 if err != nil {
208 log.Printf("error fetching %s: %s", url, err)
209 return nil
210 }
211 defer resp.Body.Close()
212 if resp.StatusCode != 200 {
213 return nil
214 }
215 var buf bytes.Buffer
216 io.Copy(&buf, resp.Body)
217
218 xid := xfiltrate()
219
220 res, err := stmtSaveFile.Exec(xid, name, url, media, buf.Bytes())
221 if err != nil {
222 log.Printf("error saving file %s: %s", url, err)
223 return nil
224 }
225 donk.FileID, _ = res.LastInsertId()
226 return &donk
227}
228
229func needxonk(user *WhatAbout, x *Honk) bool {
230 if x == nil {
231 return false
232 }
233 if x.What == "eradicate" {
234 return true
235 }
236 return needxonkid(user, x.XID)
237}
238func needxonkid(user *WhatAbout, xid string) bool {
239 if strings.HasPrefix(xid, user.URL+"/h/") {
240 return false
241 }
242 row := stmtFindXonk.QueryRow(user.ID, xid)
243 var id int64
244 err := row.Scan(&id)
245 if err == nil {
246 return false
247 }
248 if err != sql.ErrNoRows {
249 log.Printf("err querying xonk: %s", err)
250 }
251 return true
252}
253
254func savexonk(user *WhatAbout, x *Honk) {
255 if x.What == "eradicate" {
256 log.Printf("eradicating %s by %s", x.RID, x.Honker)
257 _, err := stmtDeleteHonk.Exec(x.RID, x.Honker, user.ID)
258 if err != nil {
259 log.Printf("error eradicating: %s", err)
260 }
261 return
262 }
263 dt := x.Date.UTC().Format(dbtimeformat)
264 aud := strings.Join(x.Audience, " ")
265 whofore := 0
266 if strings.Contains(aud, user.URL) {
267 whofore = 1
268 }
269 res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud,
270 x.Noise, x.Convoy, whofore)
271 if err != nil {
272 log.Printf("err saving xonk: %s", err)
273 return
274 }
275 x.ID, _ = res.LastInsertId()
276 for _, d := range x.Donks {
277 _, err = stmtSaveDonk.Exec(x.ID, d.FileID)
278 if err != nil {
279 log.Printf("err saving donk: %s", err)
280 return
281 }
282 }
283}
284
285type Box struct {
286 In string
287 Out string
288 Shared string
289}
290
291var boxofboxes = make(map[string]*Box)
292var boxlock sync.Mutex
293var boxinglock sync.Mutex
294
295func getboxes(ident string) (*Box, error) {
296 boxlock.Lock()
297 b, ok := boxofboxes[ident]
298 boxlock.Unlock()
299 if ok {
300 return b, nil
301 }
302
303 boxinglock.Lock()
304 defer boxinglock.Unlock()
305
306 boxlock.Lock()
307 b, ok = boxofboxes[ident]
308 boxlock.Unlock()
309 if ok {
310 return b, nil
311 }
312
313 db := opendatabase()
314
315 row := db.QueryRow("select ibox, obox, sbox from xonkers where xid = ?", ident)
316 b = &Box{}
317 err := row.Scan(&b.In, &b.Out, &b.Shared)
318 if err != nil {
319 j, err := GetJunk(ident)
320 if err != nil {
321 return nil, err
322 }
323 inbox, _ := jsongetstring(j, "inbox")
324 outbox, _ := jsongetstring(j, "outbox")
325 sbox, _ := jsonfindstring(j, []string{"endpoints", "sharedInbox"})
326 b = &Box{In: inbox, Out: outbox, Shared: sbox}
327 if inbox != "" {
328 db.Exec("insert into xonkers (xid, ibox, obox, sbox, pubkey) values (?, ?, ?, ?, ?)",
329 ident, inbox, outbox, sbox, "")
330 }
331 }
332 boxlock.Lock()
333 boxofboxes[ident] = b
334 boxlock.Unlock()
335 return b, nil
336}
337
338func peeppeep() {
339 user, _ := butwhatabout("htest")
340 honkers := gethonkers(user.ID)
341 for _, f := range honkers {
342 if f.Flavor != "peep" {
343 continue
344 }
345 log.Printf("getting updates: %s", f.XID)
346 box, err := getboxes(f.XID)
347 if err != nil {
348 log.Printf("error getting outbox: %s", err)
349 continue
350 }
351 log.Printf("getting outbox")
352 j, err := GetJunk(box.Out)
353 if err != nil {
354 log.Printf("err: %s", err)
355 continue
356 }
357 t, _ := jsongetstring(j, "type")
358 if t == "OrderedCollection" {
359 items, _ := jsongetarray(j, "orderedItems")
360 if items == nil {
361 page1, _ := jsongetstring(j, "first")
362 j, err = GetJunk(page1)
363 if err != nil {
364 log.Printf("err: %s", err)
365 continue
366 }
367 items, _ = jsongetarray(j, "orderedItems")
368 }
369
370 for _, item := range items {
371 xonk := xonkxonk(user, item)
372 if needxonk(user, xonk) {
373 xonk.UserID = user.ID
374 savexonk(user, xonk)
375 }
376 }
377 }
378 }
379}
380
381func whosthere(xid string) ([]string, string) {
382 obj, err := GetJunk(xid)
383 if err != nil {
384 log.Printf("error getting remote xonk: %s", err)
385 return nil, ""
386 }
387 convoy, _ := jsongetstring(obj, "context")
388 if convoy == "" {
389 convoy, _ = jsongetstring(obj, "conversation")
390 }
391 return newphone(nil, obj), convoy
392}
393
394func newphone(a []string, obj map[string]interface{}) []string {
395 for _, addr := range []string{"to", "cc", "attributedTo"} {
396 who, _ := jsongetstring(obj, addr)
397 if who != "" {
398 a = append(a, who)
399 }
400 whos, _ := jsongetarray(obj, addr)
401 for _, w := range whos {
402 who, _ := w.(string)
403 if who != "" {
404 a = append(a, who)
405 }
406 }
407 }
408 return a
409}
410
411func xonkxonk(user *WhatAbout, item interface{}) *Honk {
412 depth := 0
413 maxdepth := 4
414 var xonkxonkfn func(item interface{}) *Honk
415
416 saveoneup := func(xid string) {
417 log.Printf("getting oneup: %s", xid)
418 if depth >= maxdepth {
419 log.Printf("in too deep")
420 return
421 }
422 obj, err := GetJunk(xid)
423 if err != nil {
424 log.Printf("error getting oneup: %s", err)
425 return
426 }
427 depth++
428 xonk := xonkxonkfn(obj)
429 if needxonk(user, xonk) {
430 xonk.UserID = user.ID
431 savexonk(user, xonk)
432 }
433 depth--
434 }
435
436 xonkxonkfn = func(item interface{}) *Honk {
437 // id, _ := jsongetstring(item, "id")
438 what, _ := jsongetstring(item, "type")
439 dt, _ := jsongetstring(item, "published")
440
441 var audience []string
442 var err error
443 var xid, rid, url, content, convoy string
444 var obj map[string]interface{}
445 var ok bool
446 switch what {
447 case "Announce":
448 xid, ok = jsongetstring(item, "object")
449 if ok {
450 if !needxonkid(user, xid) {
451 return nil
452 }
453 log.Printf("getting bonk: %s", xid)
454 obj, err = GetJunk(xid)
455 if err != nil {
456 log.Printf("error regetting: %s", err)
457 }
458 } else {
459 obj, _ = jsongetmap(item, "object")
460 }
461 what = "bonk"
462 case "Create":
463 obj, _ = jsongetmap(item, "object")
464 what = "honk"
465 case "Note":
466 obj = item.(map[string]interface{})
467 what = "honk"
468 case "Delete":
469 obj, _ = jsongetmap(item, "object")
470 rid, _ = jsongetstring(item, "object")
471 what = "eradicate"
472 default:
473 log.Printf("unknown activity: %s", what)
474 return nil
475 }
476
477 var xonk Honk
478 who, _ := jsongetstring(item, "actor")
479 if obj != nil {
480 if who == "" {
481 who, _ = jsongetstring(obj, "attributedTo")
482 }
483 ot, _ := jsongetstring(obj, "type")
484 url, _ = jsongetstring(obj, "url")
485 if ot == "Note" || ot == "Article" {
486 audience = newphone(audience, obj)
487 xid, _ = jsongetstring(obj, "id")
488 content, _ = jsongetstring(obj, "content")
489 summary, _ := jsongetstring(obj, "summary")
490 if !strings.HasPrefix(content, "<p>") {
491 content = "<p>" + content
492 }
493 if summary != "" {
494 content = "<p>summary: " + summary + content
495 }
496 rid, _ = jsongetstring(obj, "inReplyTo")
497 convoy, _ = jsongetstring(obj, "context")
498 if convoy == "" {
499 convoy, _ = jsongetstring(obj, "conversation")
500 }
501 if what == "honk" && rid != "" {
502 what = "tonk"
503 if needxonkid(user, rid) {
504 saveoneup(rid)
505 }
506 }
507 }
508 if ot == "Tombstone" {
509 rid, _ = jsongetstring(obj, "id")
510 }
511 atts, _ := jsongetarray(obj, "attachment")
512 for _, att := range atts {
513 at, _ := jsongetstring(att, "type")
514 mt, _ := jsongetstring(att, "mediaType")
515 u, _ := jsongetstring(att, "url")
516 name, _ := jsongetstring(att, "name")
517 if at == "Document" {
518 mt = strings.ToLower(mt)
519 log.Printf("attachment: %s %s", mt, u)
520 if mt == "image/jpeg" || mt == "image/png" ||
521 mt == "image/gif" || mt == "text/plain" {
522 donk := savedonk(u, name, mt)
523 if donk != nil {
524 xonk.Donks = append(xonk.Donks, donk)
525 }
526 }
527 }
528 }
529 tags, _ := jsongetarray(obj, "tag")
530 for _, tag := range tags {
531 tt, _ := jsongetstring(tag, "type")
532 name, _ := jsongetstring(tag, "name")
533 if tt == "Emoji" {
534 icon, _ := jsongetmap(tag, "icon")
535 mt, _ := jsongetstring(icon, "mediaType")
536 u, _ := jsongetstring(icon, "url")
537 donk := savedonk(u, name, mt)
538 if donk != nil {
539 xonk.Donks = append(xonk.Donks, donk)
540 }
541 }
542 }
543 }
544 audience = append(audience, who)
545
546 audience = oneofakind(audience)
547
548 xonk.What = what
549 xonk.Honker = who
550 xonk.XID = xid
551 xonk.RID = rid
552 xonk.Date, _ = time.Parse(time.RFC3339, dt)
553 xonk.URL = url
554 xonk.Noise = content
555 xonk.Audience = audience
556 xonk.Convoy = convoy
557
558 return &xonk
559 }
560
561 return xonkxonkfn(item)
562}
563
564func rubadubdub(user *WhatAbout, req map[string]interface{}) {
565 xid, _ := jsongetstring(req, "id")
566 reqactor, _ := jsongetstring(req, "actor")
567 j := NewJunk()
568 j["@context"] = itiswhatitis
569 j["id"] = user.URL + "/dub/" + xid
570 j["type"] = "Accept"
571 j["actor"] = user.URL
572 j["to"] = reqactor
573 j["published"] = time.Now().UTC().Format(time.RFC3339)
574 j["object"] = req
575
576 WriteJunk(os.Stdout, j)
577
578 actor, _ := jsongetstring(req, "actor")
579 box, err := getboxes(actor)
580 if err != nil {
581 log.Printf("can't get dub box: %s", err)
582 return
583 }
584 keyname, key := ziggy(user.Name)
585 err = PostJunk(keyname, key, box.In, j)
586 if err != nil {
587 log.Printf("can't rub a dub: %s", err)
588 return
589 }
590 stmtSaveDub.Exec(user.ID, actor, actor, "dub")
591}
592
593func subsub(user *WhatAbout, xid string) {
594 j := NewJunk()
595 j["@context"] = itiswhatitis
596 j["id"] = user.URL + "/sub/" + xid
597 j["type"] = "Follow"
598 j["actor"] = user.URL
599 j["to"] = xid
600 j["object"] = xid
601 j["published"] = time.Now().UTC().Format(time.RFC3339)
602
603 box, err := getboxes(xid)
604 if err != nil {
605 log.Printf("can't send follow: %s", err)
606 return
607 }
608 WriteJunk(os.Stdout, j)
609 keyname, key := ziggy(user.Name)
610 err = PostJunk(keyname, key, box.In, j)
611 if err != nil {
612 log.Printf("failed to subsub: %s", err)
613 }
614}
615
616func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
617 dt := h.Date.Format(time.RFC3339)
618 var jo map[string]interface{}
619 j := NewJunk()
620 j["id"] = user.URL + "/" + h.What + "/" + h.XID
621 j["actor"] = user.URL
622 j["published"] = dt
623 j["to"] = h.Audience[0]
624 if len(h.Audience) > 1 {
625 j["cc"] = h.Audience[1:]
626 }
627
628 switch h.What {
629 case "zonk":
630 fallthrough
631 case "tonk":
632 fallthrough
633 case "honk":
634 j["type"] = "Create"
635 if h.What == "zonk" {
636 j["type"] = "Delete"
637 }
638
639 jo = NewJunk()
640 jo["id"] = user.URL + "/h/" + h.XID
641 jo["type"] = "Note"
642 if h.What == "zonk" {
643 jo["type"] = "Tombstone"
644 }
645 jo["published"] = dt
646 jo["url"] = user.URL + "/h/" + h.XID
647 jo["attributedTo"] = user.URL
648 if h.RID != "" {
649 jo["inReplyTo"] = h.RID
650 }
651 if h.Convoy != "" {
652 jo["context"] = h.Convoy
653 jo["conversation"] = h.Convoy
654 }
655 jo["to"] = h.Audience[0]
656 if len(h.Audience) > 1 {
657 jo["cc"] = h.Audience[1:]
658 }
659 jo["content"] = mentionize(h.Noise)
660 jo["summary"] = nil
661 var tags []interface{}
662 g := bunchofgrapes(h.Noise)
663 for _, m := range g {
664 t := NewJunk()
665 t["type"] = "Mention"
666 t["name"] = m.who
667 t["href"] = m.where
668 tags = append(tags, t)
669 }
670 herd := herdofemus(h.Noise)
671 for _, e := range herd {
672 t := NewJunk()
673 t["id"] = e.ID
674 t["type"] = "Emoji"
675 t["name"] = e.Name
676 i := NewJunk()
677 i["type"] = "Image"
678 i["mediaType"] = "image/png"
679 i["url"] = e.ID
680 t["icon"] = i
681 tags = append(tags, t)
682 }
683 if len(tags) > 0 {
684 jo["tag"] = tags
685 }
686 var atts []interface{}
687 for _, d := range h.Donks {
688 if re_emus.MatchString(d.Name) {
689 continue
690 }
691 jd := NewJunk()
692 jd["mediaType"] = d.Media
693 jd["name"] = d.Name
694 jd["type"] = "Document"
695 jd["url"] = d.URL
696 atts = append(atts, jd)
697 }
698 if len(atts) > 0 {
699 jo["attachment"] = atts
700 }
701 j["object"] = jo
702 case "bonk":
703 j["type"] = "Announce"
704 j["object"] = h.XID
705 }
706
707 return j, jo
708}
709
710func honkworldwide(user *WhatAbout, honk *Honk) {
711 jonk, _ := jonkjonk(user, honk)
712 jonk["@context"] = itiswhatitis
713 var buf bytes.Buffer
714 WriteJunk(&buf, jonk)
715 msg := buf.Bytes()
716
717 rcpts := make(map[string]bool)
718 for _, a := range honk.Audience {
719 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
720 box, _ := getboxes(a)
721 if box != nil && box.Shared != "" {
722 rcpts["%"+box.Shared] = true
723 } else {
724 rcpts[a] = true
725 }
726 }
727 }
728 for _, f := range getdubs(user.ID) {
729 box, _ := getboxes(f.XID)
730 if box != nil && box.Shared != "" {
731 rcpts["%"+box.Shared] = true
732 } else {
733 rcpts[f.XID] = true
734 }
735 }
736 for a := range rcpts {
737 go deliverate(0, user.Name, a, msg)
738 }
739}
740
741func asjonker(user *WhatAbout) map[string]interface{} {
742 about := obfusbreak(user.About)
743
744 j := NewJunk()
745 j["@context"] = itiswhatitis
746 j["id"] = user.URL
747 j["type"] = "Person"
748 j["inbox"] = user.URL + "/inbox"
749 j["outbox"] = user.URL + "/outbox"
750 j["followers"] = user.URL + "/followers"
751 j["following"] = user.URL + "/following"
752 j["name"] = user.Display
753 j["preferredUsername"] = user.Name
754 j["summary"] = about
755 j["url"] = user.URL
756 a := NewJunk()
757 a["type"] = "icon"
758 a["mediaType"] = "image/png"
759 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
760 j["icon"] = a
761 k := NewJunk()
762 k["id"] = user.URL + "#key"
763 k["owner"] = user.URL
764 k["publicKeyPem"] = user.Key
765 j["publicKey"] = k
766
767 return j
768}