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 // id, _ := jsongetstring(item, "id")
413 what, _ := jsongetstring(item, "type")
414 dt, _ := jsongetstring(item, "published")
415
416 var audience []string
417 var err error
418 var xid, rid, url, content, convoy string
419 var obj map[string]interface{}
420 var ok bool
421 switch what {
422 case "Announce":
423 xid, ok = jsongetstring(item, "object")
424 if ok {
425 if !needxonkid(user, xid) {
426 return nil
427 }
428 log.Printf("getting bonk: %s", xid)
429 obj, err = GetJunk(xid)
430 if err != nil {
431 log.Printf("error regetting: %s", err)
432 }
433 } else {
434 obj, _ = jsongetmap(item, "object")
435 }
436 what = "bonk"
437 case "Create":
438 obj, _ = jsongetmap(item, "object")
439 what = "honk"
440 case "Delete":
441 obj, _ = jsongetmap(item, "object")
442 rid, _ = jsongetstring(item, "object")
443 what = "eradicate"
444 default:
445 log.Printf("unknown activity: %s", what)
446 return nil
447 }
448 who, _ := jsongetstring(item, "actor")
449
450 var xonk Honk
451 if obj != nil {
452 ot, _ := jsongetstring(obj, "type")
453 url, _ = jsongetstring(obj, "url")
454 if ot == "Note" || ot == "Article" {
455 audience = newphone(audience, obj)
456 xid, _ = jsongetstring(obj, "id")
457 content, _ = jsongetstring(obj, "content")
458 summary, _ := jsongetstring(obj, "summary")
459 if !strings.HasPrefix(content, "<p>") {
460 content = "<p>" + content
461 }
462 if summary != "" {
463 content = "<p>summary: " + summary + content
464 }
465 rid, _ = jsongetstring(obj, "inReplyTo")
466 convoy, _ = jsongetstring(obj, "context")
467 if convoy == "" {
468 convoy, _ = jsongetstring(obj, "conversation")
469 }
470 if what == "honk" && rid != "" {
471 what = "tonk"
472 }
473 }
474 if ot == "Tombstone" {
475 rid, _ = jsongetstring(obj, "id")
476 }
477 atts, _ := jsongetarray(obj, "attachment")
478 for _, att := range atts {
479 at, _ := jsongetstring(att, "type")
480 mt, _ := jsongetstring(att, "mediaType")
481 u, _ := jsongetstring(att, "url")
482 name, _ := jsongetstring(att, "name")
483 if at == "Document" {
484 mt = strings.ToLower(mt)
485 log.Printf("attachment: %s %s", mt, u)
486 if mt == "image/jpeg" || mt == "image/png" ||
487 mt == "image/gif" || mt == "text/plain" {
488 donk := savedonk(u, name, mt)
489 if donk != nil {
490 xonk.Donks = append(xonk.Donks, donk)
491 }
492 }
493 }
494 }
495 tags, _ := jsongetarray(obj, "tag")
496 for _, tag := range tags {
497 tt, _ := jsongetstring(tag, "type")
498 name, _ := jsongetstring(tag, "name")
499 if tt == "Emoji" {
500 icon, _ := jsongetmap(tag, "icon")
501 mt, _ := jsongetstring(icon, "mediaType")
502 u, _ := jsongetstring(icon, "url")
503 donk := savedonk(u, name, mt)
504 if donk != nil {
505 xonk.Donks = append(xonk.Donks, donk)
506 }
507 }
508 }
509 }
510 audience = append(audience, who)
511
512 audience = oneofakind(audience)
513
514 xonk.What = what
515 xonk.Honker = who
516 xonk.XID = xid
517 xonk.RID = rid
518 xonk.Date, _ = time.Parse(time.RFC3339, dt)
519 xonk.URL = url
520 xonk.Noise = content
521 xonk.Audience = audience
522 xonk.Convoy = convoy
523
524 return &xonk
525}
526
527func rubadubdub(user *WhatAbout, req map[string]interface{}) {
528 xid, _ := jsongetstring(req, "id")
529 reqactor, _ := jsongetstring(req, "actor")
530 j := NewJunk()
531 j["@context"] = itiswhatitis
532 j["id"] = user.URL + "/dub/" + xid
533 j["type"] = "Accept"
534 j["actor"] = user.URL
535 j["to"] = reqactor
536 j["published"] = time.Now().UTC().Format(time.RFC3339)
537 j["object"] = req
538
539 WriteJunk(os.Stdout, j)
540
541 actor, _ := jsongetstring(req, "actor")
542 box, err := getboxes(actor)
543 if err != nil {
544 log.Printf("can't get dub box: %s", err)
545 return
546 }
547 keyname, key := ziggy(user.Name)
548 err = PostJunk(keyname, key, box.In, j)
549 if err != nil {
550 log.Printf("can't rub a dub: %s", err)
551 return
552 }
553 stmtSaveDub.Exec(user.ID, actor, actor, "dub")
554}
555
556func subsub(user *WhatAbout, xid string) {
557 j := NewJunk()
558 j["@context"] = itiswhatitis
559 j["id"] = user.URL + "/sub/" + xid
560 j["type"] = "Follow"
561 j["actor"] = user.URL
562 j["to"] = xid
563 j["object"] = xid
564 j["published"] = time.Now().UTC().Format(time.RFC3339)
565
566 box, err := getboxes(xid)
567 if err != nil {
568 log.Printf("can't send follow: %s", err)
569 return
570 }
571 WriteJunk(os.Stdout, j)
572 keyname, key := ziggy(user.Name)
573 err = PostJunk(keyname, key, box.In, j)
574 if err != nil {
575 log.Printf("failed to subsub: %s", err)
576 }
577}
578
579func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
580 dt := h.Date.Format(time.RFC3339)
581 var jo map[string]interface{}
582 j := NewJunk()
583 j["id"] = user.URL + "/" + h.What + "/" + h.XID
584 j["actor"] = user.URL
585 j["published"] = dt
586 j["to"] = h.Audience[0]
587 if len(h.Audience) > 1 {
588 j["cc"] = h.Audience[1:]
589 }
590
591 switch h.What {
592 case "zonk":
593 fallthrough
594 case "tonk":
595 fallthrough
596 case "honk":
597 j["type"] = "Create"
598 if h.What == "zonk" {
599 j["type"] = "Delete"
600 }
601
602 jo = NewJunk()
603 jo["id"] = user.URL + "/h/" + h.XID
604 jo["type"] = "Note"
605 if h.What == "zonk" {
606 jo["type"] = "Tombstone"
607 }
608 jo["published"] = dt
609 jo["url"] = user.URL + "/h/" + h.XID
610 jo["attributedTo"] = user.URL
611 if h.RID != "" {
612 jo["inReplyTo"] = h.RID
613 }
614 if h.Convoy != "" {
615 jo["context"] = h.Convoy
616 jo["conversation"] = h.Convoy
617 }
618 jo["to"] = h.Audience[0]
619 if len(h.Audience) > 1 {
620 jo["cc"] = h.Audience[1:]
621 }
622 jo["content"] = mentionize(h.Noise)
623 jo["summary"] = nil
624 var tags []interface{}
625 g := bunchofgrapes(h.Noise)
626 for _, m := range g {
627 t := NewJunk()
628 t["type"] = "Mention"
629 t["name"] = m.who
630 t["href"] = m.where
631 tags = append(tags, t)
632 }
633 herd := herdofemus(h.Noise)
634 for _, e := range herd {
635 t := NewJunk()
636 t["id"] = e.ID
637 t["type"] = "Emoji"
638 t["name"] = e.Name
639 i := NewJunk()
640 i["type"] = "Image"
641 i["mediaType"] = "image/png"
642 i["url"] = e.ID
643 t["icon"] = i
644 tags = append(tags, t)
645 }
646 if len(tags) > 0 {
647 jo["tag"] = tags
648 }
649 var atts []interface{}
650 for _, d := range h.Donks {
651 if re_emus.MatchString(d.Name) {
652 continue
653 }
654 jd := NewJunk()
655 jd["mediaType"] = d.Media
656 jd["name"] = d.Name
657 jd["type"] = "Document"
658 jd["url"] = d.URL
659 atts = append(atts, jd)
660 }
661 if len(atts) > 0 {
662 jo["attachment"] = atts
663 }
664 j["object"] = jo
665 case "bonk":
666 j["type"] = "Announce"
667 j["object"] = h.XID
668 }
669
670 return j, jo
671}
672
673func honkworldwide(user *WhatAbout, honk *Honk) {
674 jonk, _ := jonkjonk(user, honk)
675 jonk["@context"] = itiswhatitis
676 var buf bytes.Buffer
677 WriteJunk(&buf, jonk)
678 msg := buf.Bytes()
679
680 rcpts := make(map[string]bool)
681 for _, a := range honk.Audience {
682 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
683 box, _ := getboxes(a)
684 if box != nil && box.Shared != "" {
685 rcpts["%"+box.Shared] = true
686 } else {
687 rcpts[a] = true
688 }
689 }
690 }
691 for _, f := range getdubs(user.ID) {
692 box, _ := getboxes(f.XID)
693 if box != nil && box.Shared != "" {
694 rcpts["%"+box.Shared] = true
695 } else {
696 rcpts[f.XID] = true
697 }
698 }
699 for a := range rcpts {
700 go deliverate(0, user.Name, a, msg)
701 }
702}
703
704func asjonker(user *WhatAbout) map[string]interface{} {
705 about := obfusbreak(user.About)
706
707 j := NewJunk()
708 j["@context"] = itiswhatitis
709 j["id"] = user.URL
710 j["type"] = "Person"
711 j["inbox"] = user.URL + "/inbox"
712 j["outbox"] = user.URL + "/outbox"
713 j["followers"] = user.URL + "/followers"
714 j["following"] = user.URL + "/following"
715 j["name"] = user.Display
716 j["preferredUsername"] = user.Name
717 j["summary"] = about
718 j["url"] = user.URL
719 a := NewJunk()
720 a["type"] = "icon"
721 a["mediaType"] = "image/png"
722 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
723 j["icon"] = a
724 k := NewJunk()
725 k["id"] = user.URL + "#key"
726 k["owner"] = user.URL
727 k["publicKeyPem"] = user.Key
728 j["publicKey"] = k
729
730 return j
731}