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 strings.HasPrefix(x.XID, user.URL+"/h/") {
231 return false
232 }
233 if x.What == "eradicate" {
234 return true
235 }
236 row := stmtFindXonk.QueryRow(user.ID, x.XID)
237 err := row.Scan(&x.ID)
238 if err == nil {
239 return false
240 }
241 if err != sql.ErrNoRows {
242 log.Printf("err querying xonk: %s", err)
243 }
244 return true
245}
246
247func savexonk(user *WhatAbout, x *Honk) {
248 if x.What == "eradicate" {
249 log.Printf("eradicating %s by %s", x.RID, x.Honker)
250 _, err := stmtDeleteHonk.Exec(x.RID, x.Honker, user.ID)
251 if err != nil {
252 log.Printf("error eradicating: %s", err)
253 }
254 return
255 }
256 dt := x.Date.UTC().Format(dbtimeformat)
257 aud := strings.Join(x.Audience, " ")
258 whofore := 0
259 if strings.Contains(aud, user.URL) {
260 whofore = 1
261 }
262 res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud,
263 x.Noise, x.Convoy, whofore)
264 if err != nil {
265 log.Printf("err saving xonk: %s", err)
266 return
267 }
268 x.ID, _ = res.LastInsertId()
269 for _, d := range x.Donks {
270 _, err = stmtSaveDonk.Exec(x.ID, d.FileID)
271 if err != nil {
272 log.Printf("err saving donk: %s", err)
273 return
274 }
275 }
276}
277
278type Box struct {
279 In string
280 Out string
281 Shared string
282}
283
284var boxofboxes = make(map[string]*Box)
285var boxlock sync.Mutex
286var boxinglock sync.Mutex
287
288func getboxes(ident string) (*Box, error) {
289 boxlock.Lock()
290 b, ok := boxofboxes[ident]
291 boxlock.Unlock()
292 if ok {
293 return b, nil
294 }
295
296 boxinglock.Lock()
297 defer boxinglock.Unlock()
298
299 boxlock.Lock()
300 b, ok = boxofboxes[ident]
301 boxlock.Unlock()
302 if ok {
303 return b, nil
304 }
305
306 db := opendatabase()
307
308 row := db.QueryRow("select ibox, obox, sbox from xonkers where xid = ?", ident)
309 b = &Box{}
310 err := row.Scan(&b.In, &b.Out, &b.Shared)
311 if err != nil {
312 j, err := GetJunk(ident)
313 if err != nil {
314 return nil, err
315 }
316 inbox, _ := jsongetstring(j, "inbox")
317 outbox, _ := jsongetstring(j, "outbox")
318 sbox, _ := jsonfindstring(j, []string{"endpoints", "sharedInbox"})
319 b = &Box{In: inbox, Out: outbox, Shared: sbox}
320 if inbox != "" {
321 db.Exec("insert into xonkers (xid, ibox, obox, sbox, pubkey) values (?, ?, ?, ?, ?)",
322 ident, inbox, outbox, sbox, "")
323 }
324 }
325 boxlock.Lock()
326 boxofboxes[ident] = b
327 boxlock.Unlock()
328 return b, nil
329}
330
331func peeppeep() {
332 user, _ := butwhatabout("htest")
333 honkers := gethonkers(user.ID)
334 for _, f := range honkers {
335 if f.Flavor != "peep" {
336 continue
337 }
338 log.Printf("getting updates: %s", f.XID)
339 box, err := getboxes(f.XID)
340 if err != nil {
341 log.Printf("error getting outbox: %s", err)
342 continue
343 }
344 log.Printf("getting outbox")
345 j, err := GetJunk(box.Out)
346 if err != nil {
347 log.Printf("err: %s", err)
348 continue
349 }
350 t, _ := jsongetstring(j, "type")
351 if t == "OrderedCollection" {
352 items, _ := jsongetarray(j, "orderedItems")
353 if items == nil {
354 page1, _ := jsongetstring(j, "first")
355 j, err = GetJunk(page1)
356 if err != nil {
357 log.Printf("err: %s", err)
358 continue
359 }
360 items, _ = jsongetarray(j, "orderedItems")
361 }
362
363 for _, item := range items {
364 xonk := xonkxonk(item)
365 if xonk != nil && needxonk(user, xonk) {
366 xonk.UserID = user.ID
367 savexonk(user, xonk)
368 }
369 }
370 }
371 }
372}
373
374func whosthere(xid string) ([]string, string) {
375 obj, err := GetJunk(xid)
376 if err != nil {
377 log.Printf("error getting remote xonk: %s", err)
378 return nil, ""
379 }
380 convoy, _ := jsongetstring(obj, "context")
381 if convoy == "" {
382 convoy, _ = jsongetstring(obj, "conversation")
383 }
384 return newphone(nil, obj), convoy
385}
386
387func newphone(a []string, obj map[string]interface{}) []string {
388 for _, addr := range []string{"to", "cc", "attributedTo"} {
389 who, _ := jsongetstring(obj, addr)
390 if who != "" {
391 a = append(a, who)
392 }
393 whos, _ := jsongetarray(obj, addr)
394 for _, w := range whos {
395 who, _ := w.(string)
396 if who != "" {
397 a = append(a, who)
398 }
399 }
400 }
401 return a
402}
403
404func xonkxonk(item interface{}) *Honk {
405 // id, _ := jsongetstring(item, "id")
406 what, _ := jsongetstring(item, "type")
407 dt, _ := jsongetstring(item, "published")
408
409 var audience []string
410 var err error
411 var xid, rid, url, content, convoy string
412 var obj map[string]interface{}
413 var ok bool
414 switch what {
415 case "Announce":
416 xid, ok = jsongetstring(item, "object")
417 if ok {
418 log.Printf("getting bonk: %s", xid)
419 obj, err = GetJunk(xid)
420 if err != nil {
421 log.Printf("error regetting: %s", err)
422 }
423 } else {
424 obj, _ = jsongetmap(item, "object")
425 }
426 what = "bonk"
427 case "Create":
428 obj, _ = jsongetmap(item, "object")
429 what = "honk"
430 case "Delete":
431 obj, _ = jsongetmap(item, "object")
432 rid, _ = jsongetstring(item, "object")
433 what = "eradicate"
434 default:
435 log.Printf("unknown activity: %s", what)
436 return nil
437 }
438 who, _ := jsongetstring(item, "actor")
439
440 var xonk Honk
441 if obj != nil {
442 ot, _ := jsongetstring(obj, "type")
443 url, _ = jsongetstring(obj, "url")
444 if ot == "Note" || ot == "Article" {
445 audience = newphone(audience, obj)
446 xid, _ = jsongetstring(obj, "id")
447 content, _ = jsongetstring(obj, "content")
448 summary, _ := jsongetstring(obj, "summary")
449 if !strings.HasPrefix(content, "<p>") {
450 content = "<p>" + content
451 }
452 if summary != "" {
453 content = "<p>summary: " + summary + content
454 }
455 rid, _ = jsongetstring(obj, "inReplyTo")
456 convoy, _ = jsongetstring(obj, "context")
457 if convoy == "" {
458 convoy, _ = jsongetstring(obj, "conversation")
459 }
460 if what == "honk" && rid != "" {
461 what = "tonk"
462 }
463 }
464 if ot == "Tombstone" {
465 rid, _ = jsongetstring(obj, "id")
466 }
467 atts, _ := jsongetarray(obj, "attachment")
468 for _, att := range atts {
469 at, _ := jsongetstring(att, "type")
470 mt, _ := jsongetstring(att, "mediaType")
471 u, _ := jsongetstring(att, "url")
472 name, _ := jsongetstring(att, "name")
473 if at == "Document" {
474 mt = strings.ToLower(mt)
475 log.Printf("attachment: %s %s", mt, u)
476 if mt == "image/jpeg" || mt == "image/png" ||
477 mt == "image/gif" || mt == "text/plain" {
478 donk := savedonk(u, name, mt)
479 if donk != nil {
480 xonk.Donks = append(xonk.Donks, donk)
481 }
482 }
483 }
484 }
485 tags, _ := jsongetarray(obj, "tag")
486 for _, tag := range tags {
487 tt, _ := jsongetstring(tag, "type")
488 name, _ := jsongetstring(tag, "name")
489 if tt == "Emoji" {
490 icon, _ := jsongetmap(tag, "icon")
491 mt, _ := jsongetstring(icon, "mediaType")
492 u, _ := jsongetstring(icon, "url")
493 donk := savedonk(u, name, mt)
494 if donk != nil {
495 xonk.Donks = append(xonk.Donks, donk)
496 }
497 }
498 }
499 }
500 audience = append(audience, who)
501
502 audience = oneofakind(audience)
503
504 xonk.What = what
505 xonk.Honker = who
506 xonk.XID = xid
507 xonk.RID = rid
508 xonk.Date, _ = time.Parse(time.RFC3339, dt)
509 xonk.URL = url
510 xonk.Noise = content
511 xonk.Audience = audience
512 xonk.Convoy = convoy
513
514 return &xonk
515}
516
517func rubadubdub(user *WhatAbout, req map[string]interface{}) {
518 xid, _ := jsongetstring(req, "id")
519 reqactor, _ := jsongetstring(req, "actor")
520 j := NewJunk()
521 j["@context"] = itiswhatitis
522 j["id"] = user.URL + "/dub/" + xid
523 j["type"] = "Accept"
524 j["actor"] = user.URL
525 j["to"] = reqactor
526 j["published"] = time.Now().UTC().Format(time.RFC3339)
527 j["object"] = req
528
529 WriteJunk(os.Stdout, j)
530
531 actor, _ := jsongetstring(req, "actor")
532 box, err := getboxes(actor)
533 if err != nil {
534 log.Printf("can't get dub box: %s", err)
535 return
536 }
537 keyname, key := ziggy(user.Name)
538 err = PostJunk(keyname, key, box.In, j)
539 if err != nil {
540 log.Printf("can't rub a dub: %s", err)
541 return
542 }
543 stmtSaveDub.Exec(user.ID, actor, actor, "dub")
544}
545
546func subsub(user *WhatAbout, xid string) {
547 j := NewJunk()
548 j["@context"] = itiswhatitis
549 j["id"] = user.URL + "/sub/" + xid
550 j["type"] = "Follow"
551 j["actor"] = user.URL
552 j["to"] = xid
553 j["object"] = xid
554 j["published"] = time.Now().UTC().Format(time.RFC3339)
555
556 box, err := getboxes(xid)
557 if err != nil {
558 log.Printf("can't send follow: %s", err)
559 return
560 }
561 WriteJunk(os.Stdout, j)
562 keyname, key := ziggy(user.Name)
563 err = PostJunk(keyname, key, box.In, j)
564 if err != nil {
565 log.Printf("failed to subsub: %s", err)
566 }
567}
568
569func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
570 dt := h.Date.Format(time.RFC3339)
571 var jo map[string]interface{}
572 j := NewJunk()
573 j["id"] = user.URL + "/" + h.What + "/" + h.XID
574 j["actor"] = user.URL
575 j["published"] = dt
576 j["to"] = h.Audience[0]
577 if len(h.Audience) > 1 {
578 j["cc"] = h.Audience[1:]
579 }
580
581 switch h.What {
582 case "zonk":
583 fallthrough
584 case "tonk":
585 fallthrough
586 case "honk":
587 j["type"] = "Create"
588 if h.What == "zonk" {
589 j["type"] = "Delete"
590 }
591
592 jo = NewJunk()
593 jo["id"] = user.URL + "/h/" + h.XID
594 jo["type"] = "Note"
595 if h.What == "zonk" {
596 jo["type"] = "Tombstone"
597 }
598 jo["published"] = dt
599 jo["url"] = user.URL + "/h/" + h.XID
600 jo["attributedTo"] = user.URL
601 if h.RID != "" {
602 jo["inReplyTo"] = h.RID
603 }
604 if h.Convoy != "" {
605 jo["context"] = h.Convoy
606 jo["conversation"] = h.Convoy
607 }
608 jo["to"] = h.Audience[0]
609 if len(h.Audience) > 1 {
610 jo["cc"] = h.Audience[1:]
611 }
612 jo["content"] = mentionize(h.Noise)
613 jo["summary"] = nil
614 var tags []interface{}
615 g := bunchofgrapes(h.Noise)
616 for _, m := range g {
617 t := NewJunk()
618 t["type"] = "Mention"
619 t["name"] = m.who
620 t["href"] = m.where
621 tags = append(tags, t)
622 }
623 herd := herdofemus(h.Noise)
624 for _, e := range herd {
625 t := NewJunk()
626 t["id"] = e.ID
627 t["type"] = "Emoji"
628 t["name"] = e.Name
629 i := NewJunk()
630 i["type"] = "Image"
631 i["mediaType"] = "image/png"
632 i["url"] = e.ID
633 t["icon"] = i
634 tags = append(tags, t)
635 }
636 if len(tags) > 0 {
637 jo["tag"] = tags
638 }
639 var atts []interface{}
640 for _, d := range h.Donks {
641 if re_emus.MatchString(d.Name) {
642 continue
643 }
644 jd := NewJunk()
645 jd["mediaType"] = d.Media
646 jd["name"] = d.Name
647 jd["type"] = "Document"
648 jd["url"] = d.URL
649 atts = append(atts, jd)
650 }
651 if len(atts) > 0 {
652 jo["attachment"] = atts
653 }
654 j["object"] = jo
655 case "bonk":
656 j["type"] = "Announce"
657 j["object"] = h.XID
658 }
659
660 return j, jo
661}
662
663func honkworldwide(user *WhatAbout, honk *Honk) {
664 jonk, _ := jonkjonk(user, honk)
665 jonk["@context"] = itiswhatitis
666 var buf bytes.Buffer
667 WriteJunk(&buf, jonk)
668 msg := buf.Bytes()
669
670 rcpts := make(map[string]bool)
671 for _, a := range honk.Audience {
672 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
673 box, _ := getboxes(a)
674 if box != nil && box.Shared != "" {
675 rcpts["%"+box.Shared] = true
676 } else {
677 rcpts[a] = true
678 }
679 }
680 }
681 for _, f := range getdubs(user.ID) {
682 box, _ := getboxes(f.XID)
683 if box != nil && box.Shared != "" {
684 rcpts["%"+box.Shared] = true
685 } else {
686 rcpts[f.XID] = true
687 }
688 }
689 for a := range rcpts {
690 go deliverate(0, user.Name, a, msg)
691 }
692}
693
694func asjonker(user *WhatAbout) map[string]interface{} {
695 about := obfusbreak(user.About)
696
697 j := NewJunk()
698 j["@context"] = itiswhatitis
699 j["id"] = user.URL
700 j["type"] = "Person"
701 j["inbox"] = user.URL + "/inbox"
702 j["outbox"] = user.URL + "/outbox"
703 j["followers"] = user.URL + "/followers"
704 j["following"] = user.URL + "/following"
705 j["name"] = user.Display
706 j["preferredUsername"] = user.Name
707 j["summary"] = about
708 j["url"] = user.URL
709 a := NewJunk()
710 a["type"] = "icon"
711 a["mediaType"] = "image/png"
712 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
713 j["icon"] = a
714 k := NewJunk()
715 k["id"] = user.URL + "#key"
716 k["owner"] = user.URL
717 k["publicKeyPem"] = user.Key
718 j["publicKey"] = k
719
720 return j
721}