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