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 if mt == "" {
537 mt = "image/png"
538 }
539 u, _ := jsongetstring(icon, "url")
540 donk := savedonk(u, name, mt)
541 if donk != nil {
542 xonk.Donks = append(xonk.Donks, donk)
543 }
544 }
545 }
546 }
547 audience = append(audience, who)
548
549 audience = oneofakind(audience)
550
551 xonk.What = what
552 xonk.Honker = who
553 xonk.XID = xid
554 xonk.RID = rid
555 xonk.Date, _ = time.Parse(time.RFC3339, dt)
556 xonk.URL = url
557 xonk.Noise = content
558 xonk.Audience = audience
559 xonk.Convoy = convoy
560
561 return &xonk
562 }
563
564 return xonkxonkfn(item)
565}
566
567func rubadubdub(user *WhatAbout, req map[string]interface{}) {
568 xid, _ := jsongetstring(req, "id")
569 reqactor, _ := jsongetstring(req, "actor")
570 j := NewJunk()
571 j["@context"] = itiswhatitis
572 j["id"] = user.URL + "/dub/" + xid
573 j["type"] = "Accept"
574 j["actor"] = user.URL
575 j["to"] = reqactor
576 j["published"] = time.Now().UTC().Format(time.RFC3339)
577 j["object"] = req
578
579 WriteJunk(os.Stdout, j)
580
581 actor, _ := jsongetstring(req, "actor")
582 box, err := getboxes(actor)
583 if err != nil {
584 log.Printf("can't get dub box: %s", err)
585 return
586 }
587 keyname, key := ziggy(user.Name)
588 err = PostJunk(keyname, key, box.In, j)
589 if err != nil {
590 log.Printf("can't rub a dub: %s", err)
591 return
592 }
593 stmtSaveDub.Exec(user.ID, actor, actor, "dub")
594}
595
596func subsub(user *WhatAbout, xid string) {
597 j := NewJunk()
598 j["@context"] = itiswhatitis
599 j["id"] = user.URL + "/sub/" + xid
600 j["type"] = "Follow"
601 j["actor"] = user.URL
602 j["to"] = xid
603 j["object"] = xid
604 j["published"] = time.Now().UTC().Format(time.RFC3339)
605
606 box, err := getboxes(xid)
607 if err != nil {
608 log.Printf("can't send follow: %s", err)
609 return
610 }
611 WriteJunk(os.Stdout, j)
612 keyname, key := ziggy(user.Name)
613 err = PostJunk(keyname, key, box.In, j)
614 if err != nil {
615 log.Printf("failed to subsub: %s", err)
616 }
617}
618
619func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
620 dt := h.Date.Format(time.RFC3339)
621 var jo map[string]interface{}
622 j := NewJunk()
623 j["id"] = user.URL + "/" + h.What + "/" + h.XID
624 j["actor"] = user.URL
625 j["published"] = dt
626 j["to"] = h.Audience[0]
627 if len(h.Audience) > 1 {
628 j["cc"] = h.Audience[1:]
629 }
630
631 switch h.What {
632 case "zonk":
633 fallthrough
634 case "tonk":
635 fallthrough
636 case "honk":
637 j["type"] = "Create"
638 if h.What == "zonk" {
639 j["type"] = "Delete"
640 }
641
642 jo = NewJunk()
643 jo["id"] = user.URL + "/h/" + h.XID
644 jo["type"] = "Note"
645 if h.What == "zonk" {
646 jo["type"] = "Tombstone"
647 }
648 jo["published"] = dt
649 jo["url"] = user.URL + "/h/" + h.XID
650 jo["attributedTo"] = user.URL
651 if h.RID != "" {
652 jo["inReplyTo"] = h.RID
653 }
654 if h.Convoy != "" {
655 jo["context"] = h.Convoy
656 jo["conversation"] = h.Convoy
657 }
658 jo["to"] = h.Audience[0]
659 if len(h.Audience) > 1 {
660 jo["cc"] = h.Audience[1:]
661 }
662 jo["content"] = mentionize(h.Noise)
663 jo["summary"] = nil
664 var tags []interface{}
665 g := bunchofgrapes(h.Noise)
666 for _, m := range g {
667 t := NewJunk()
668 t["type"] = "Mention"
669 t["name"] = m.who
670 t["href"] = m.where
671 tags = append(tags, t)
672 }
673 herd := herdofemus(h.Noise)
674 for _, e := range herd {
675 t := NewJunk()
676 t["id"] = e.ID
677 t["type"] = "Emoji"
678 t["name"] = e.Name
679 i := NewJunk()
680 i["type"] = "Image"
681 i["mediaType"] = "image/png"
682 i["url"] = e.ID
683 t["icon"] = i
684 tags = append(tags, t)
685 }
686 if len(tags) > 0 {
687 jo["tag"] = tags
688 }
689 var atts []interface{}
690 for _, d := range h.Donks {
691 if re_emus.MatchString(d.Name) {
692 continue
693 }
694 jd := NewJunk()
695 jd["mediaType"] = d.Media
696 jd["name"] = d.Name
697 jd["type"] = "Document"
698 jd["url"] = d.URL
699 atts = append(atts, jd)
700 }
701 if len(atts) > 0 {
702 jo["attachment"] = atts
703 }
704 j["object"] = jo
705 case "bonk":
706 j["type"] = "Announce"
707 j["object"] = h.XID
708 }
709
710 return j, jo
711}
712
713func honkworldwide(user *WhatAbout, honk *Honk) {
714 jonk, _ := jonkjonk(user, honk)
715 jonk["@context"] = itiswhatitis
716 var buf bytes.Buffer
717 WriteJunk(&buf, jonk)
718 msg := buf.Bytes()
719
720 rcpts := make(map[string]bool)
721 for _, a := range honk.Audience {
722 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
723 box, _ := getboxes(a)
724 if box != nil && box.Shared != "" {
725 rcpts["%"+box.Shared] = true
726 } else {
727 rcpts[a] = true
728 }
729 }
730 }
731 for _, f := range getdubs(user.ID) {
732 box, _ := getboxes(f.XID)
733 if box != nil && box.Shared != "" {
734 rcpts["%"+box.Shared] = true
735 } else {
736 rcpts[f.XID] = true
737 }
738 }
739 for a := range rcpts {
740 go deliverate(0, user.Name, a, msg)
741 }
742}
743
744func asjonker(user *WhatAbout) map[string]interface{} {
745 about := obfusbreak(user.About)
746
747 j := NewJunk()
748 j["@context"] = itiswhatitis
749 j["id"] = user.URL
750 j["type"] = "Person"
751 j["inbox"] = user.URL + "/inbox"
752 j["outbox"] = user.URL + "/outbox"
753 j["followers"] = user.URL + "/followers"
754 j["following"] = user.URL + "/following"
755 j["name"] = user.Display
756 j["preferredUsername"] = user.Name
757 j["summary"] = about
758 j["url"] = user.URL
759 a := NewJunk()
760 a["type"] = "icon"
761 a["mediaType"] = "image/png"
762 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
763 j["icon"] = a
764 k := NewJunk()
765 k["id"] = user.URL + "#key"
766 k["owner"] = user.URL
767 k["publicKeyPem"] = user.Key
768 j["publicKey"] = k
769
770 return j
771}