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 "crypto/sha256"
23 "database/sql"
24 "encoding/json"
25 "fmt"
26 "io"
27 "log"
28 "net/http"
29 "net/url"
30 "os"
31 "strconv"
32 "strings"
33 "sync"
34 "time"
35)
36
37func NewJunk() map[string]interface{} {
38 return make(map[string]interface{})
39}
40
41func WriteJunk(w io.Writer, j map[string]interface{}) error {
42 e := json.NewEncoder(w)
43 e.SetEscapeHTML(false)
44 e.SetIndent("", " ")
45 err := e.Encode(j)
46 return err
47}
48
49func ReadJunk(r io.Reader) (map[string]interface{}, error) {
50 decoder := json.NewDecoder(r)
51 var j map[string]interface{}
52 err := decoder.Decode(&j)
53 if err != nil {
54 return nil, err
55 }
56 return j, nil
57}
58
59var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
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 client := http.DefaultClient
79 var buf bytes.Buffer
80 WriteJunk(&buf, j)
81 req, err := http.NewRequest("POST", url, &buf)
82 if err != nil {
83 return err
84 }
85 req.Header.Set("Content-Type", theonetruename)
86 zig(keyname, key, req, buf.Bytes())
87 resp, err := client.Do(req)
88 if err != nil {
89 return err
90 }
91 if resp.StatusCode != 200 && resp.StatusCode != 202 {
92 resp.Body.Close()
93 return fmt.Errorf("http post status: %d", resp.StatusCode)
94 }
95 log.Printf("successful post: %s %d", url, resp.StatusCode)
96 return nil
97}
98
99type gzCloser struct {
100 r *gzip.Reader
101 under io.ReadCloser
102}
103
104func (gz *gzCloser) Read(p []byte) (int, error) {
105 return gz.r.Read(p)
106}
107
108func (gz *gzCloser) Close() error {
109 defer gz.under.Close()
110 return gz.r.Close()
111}
112
113func GetJunk(url string) (map[string]interface{}, error) {
114 client := http.DefaultClient
115 req, err := http.NewRequest("GET", url, nil)
116 if err != nil {
117 return nil, err
118 }
119 req.Header.Set("Accept", theonetruename)
120 req.Header.Set("Accept-Encoding", "gzip")
121 resp, err := client.Do(req)
122 if err != nil {
123 return nil, err
124 }
125 if resp.StatusCode != 200 {
126 resp.Body.Close()
127 return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
128 }
129 if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
130 gz, err := gzip.NewReader(resp.Body)
131 if err != nil {
132 resp.Body.Close()
133 return nil, err
134 }
135 resp.Body = &gzCloser{r: gz, under: resp.Body}
136 }
137 defer resp.Body.Close()
138 j, err := ReadJunk(resp.Body)
139 return j, err
140}
141
142func jsonfindinterface(ii interface{}, keys []string) interface{} {
143 for _, key := range keys {
144 idx, err := strconv.Atoi(key)
145 if err == nil {
146 m := ii.([]interface{})
147 if idx >= len(m) {
148 return nil
149 }
150 ii = m[idx]
151 } else {
152 m := ii.(map[string]interface{})
153 ii = m[key]
154 if ii == nil {
155 return nil
156 }
157 }
158 }
159 return ii
160}
161func jsonfindstring(j interface{}, keys []string) (string, bool) {
162 s, ok := jsonfindinterface(j, keys).(string)
163 return s, ok
164}
165func jsonfindarray(j interface{}, keys []string) ([]interface{}, bool) {
166 a, ok := jsonfindinterface(j, keys).([]interface{})
167 return a, ok
168}
169func jsonfindmap(j interface{}, keys []string) (map[string]interface{}, bool) {
170 m, ok := jsonfindinterface(j, keys).(map[string]interface{})
171 return m, ok
172}
173func jsongetstring(j interface{}, key string) (string, bool) {
174 return jsonfindstring(j, []string{key})
175}
176func jsongetarray(j interface{}, key string) ([]interface{}, bool) {
177 return jsonfindarray(j, []string{key})
178}
179func jsongetmap(j interface{}, key string) (map[string]interface{}, bool) {
180 return jsonfindmap(j, []string{key})
181}
182
183func sha256string(s string) string {
184 hasher := sha256.New()
185 io.WriteString(hasher, s)
186 sum := hasher.Sum(nil)
187 return fmt.Sprintf("%x", sum)
188}
189
190func savedonk(url string, name, media string) *Donk {
191 log.Printf("saving donk: %s", url)
192 var donk Donk
193 row := stmtFindFile.QueryRow(url)
194 err := row.Scan(&donk.FileID)
195 if err == nil {
196 return &donk
197 }
198 if err != nil && err != sql.ErrNoRows {
199 log.Printf("err querying: %s", err)
200 }
201 resp, err := http.Get(url)
202 if err != nil {
203 log.Printf("errer 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(userid int64, x *Honk) bool {
225 row := stmtFindXonk.QueryRow(userid, x.XID, x.What)
226 err := row.Scan(&x.ID)
227 if err == nil {
228 return false
229 }
230 if err != sql.ErrNoRows {
231 log.Printf("err querying xonk: %s", err)
232 }
233 return true
234}
235
236func savexonk(x *Honk) {
237 if x.What == "eradicate" {
238 log.Printf("eradicating %s by %s", x.RID, x.Honker)
239 _, err := stmtDeleteHonk.Exec(x.RID, x.Honker)
240 if err != nil {
241 log.Printf("error eradicating: %s", err)
242 }
243 return
244 }
245 dt := x.Date.UTC().Format(dbtimeformat)
246 aud := strings.Join(x.Audience, " ")
247 res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud, x.Noise)
248 if err != nil {
249 log.Printf("err saving xonk: %s", err)
250 return
251 }
252 x.ID, _ = res.LastInsertId()
253 for _, d := range x.Donks {
254 _, err = stmtSaveDonk.Exec(x.ID, d.FileID)
255 if err != nil {
256 log.Printf("err saving donk: %s", err)
257 return
258 }
259 }
260}
261
262var boxofboxes = make(map[string]string)
263var boxlock sync.Mutex
264
265func getboxes(ident string) (string, string, error) {
266 boxlock.Lock()
267 defer boxlock.Unlock()
268 b, ok := boxofboxes[ident]
269 if ok {
270 if b == "" {
271 return "", "", fmt.Errorf("error?")
272 }
273 m := strings.Split(b, "\n")
274 return m[0], m[1], nil
275 }
276 j, err := GetJunk(ident)
277 if err != nil {
278 boxofboxes[ident] = ""
279 return "", "", err
280 }
281 inbox, _ := jsongetstring(j, "inbox")
282 outbox, _ := jsongetstring(j, "outbox")
283 boxofboxes[ident] = inbox + "\n" + outbox
284 return inbox, outbox, err
285}
286
287func peeppeep() {
288 user, _ := butwhatabout("")
289 honkers := gethonkers(user.ID)
290 for _, f := range honkers {
291 if f.Flavor != "peep" {
292 continue
293 }
294 log.Printf("getting updates: %s", f.XID)
295 _, outbox, err := getboxes(f.XID)
296 if err != nil {
297 log.Printf("error getting outbox: %s", err)
298 continue
299 }
300 log.Printf("getting outbox")
301 j, err := GetJunk(outbox)
302 if err != nil {
303 log.Printf("err: %s", err)
304 continue
305 }
306 t, _ := jsongetstring(j, "type")
307 if t == "OrderedCollection" {
308 items, _ := jsongetarray(j, "orderedItems")
309 if items == nil {
310 page1, _ := jsongetstring(j, "first")
311 j, err = GetJunk(page1)
312 if err != nil {
313 log.Printf("err: %s", err)
314 continue
315 }
316 items, _ = jsongetarray(j, "orderedItems")
317 }
318
319 for _, item := range items {
320 xonk := xonkxonk(item)
321 if xonk != nil && needxonk(user.ID, xonk) {
322 xonk.UserID = user.ID
323 savexonk(xonk)
324 }
325 }
326 }
327 }
328}
329
330func whosthere(xid string) []string {
331 obj, err := GetJunk(xid)
332 if err != nil {
333 log.Printf("error getting remote xonk: %s", err)
334 return nil
335 }
336 return newphone(nil, obj)
337}
338
339func newphone(a []string, obj map[string]interface{}) []string {
340 for _, addr := range []string{"to", "cc", "attributedTo"} {
341 who, _ := jsongetstring(obj, addr)
342 if who != "" {
343 a = append(a, who)
344 }
345 whos, _ := jsongetarray(obj, addr)
346 for _, w := range whos {
347 who, _ := w.(string)
348 if who != "" {
349 a = append(a, who)
350 }
351 }
352 }
353 return a
354}
355
356func oneofakind(a []string) []string {
357 var x []string
358 for n, s := range a {
359 if s != "" {
360 x = append(x, s)
361 for i := n + 1; i < len(a); i++ {
362 if a[i] == s {
363 a[i] = ""
364 }
365 }
366 }
367 }
368 return x
369}
370
371func xonkxonk(item interface{}) *Honk {
372
373 // id, _ := jsongetstring(item, "id")
374 what, _ := jsongetstring(item, "type")
375 dt, _ := jsongetstring(item, "published")
376
377 var audience []string
378 var err error
379 var xid, rid, url, content string
380 var obj map[string]interface{}
381 switch what {
382 case "Announce":
383 xid, _ = jsongetstring(item, "object")
384 log.Printf("getting bonk: %s", xid)
385 obj, err = GetJunk(xid)
386 if err != nil {
387 log.Printf("error regetting: %s", err)
388 }
389 what = "bonk"
390 case "Create":
391 obj, _ = jsongetmap(item, "object")
392 what = "honk"
393 case "Delete":
394 obj, _ = jsongetmap(item, "object")
395 what = "eradicate"
396 default:
397 log.Printf("unknown activity: %s", what)
398 return nil
399 }
400 who, _ := jsongetstring(item, "actor")
401
402 var xonk Honk
403 if obj != nil {
404 ot, _ := jsongetstring(obj, "type")
405 url, _ = jsongetstring(obj, "url")
406 if ot == "Note" {
407 audience = newphone(audience, obj)
408 xid, _ = jsongetstring(obj, "id")
409 content, _ = jsongetstring(obj, "content")
410 rid, _ = jsongetstring(obj, "inReplyTo")
411 if what == "honk" && rid != "" {
412 what = "tonk"
413 }
414 }
415 if ot == "Tombstone" {
416 rid, _ = jsongetstring(obj, "id")
417 }
418 atts, _ := jsongetarray(obj, "attachment")
419 for _, att := range atts {
420 at, _ := jsongetstring(att, "type")
421 mt, _ := jsongetstring(att, "mediaType")
422 u, _ := jsongetstring(att, "url")
423 name, _ := jsongetstring(att, "name")
424 if at == "Document" {
425 mt = strings.ToLower(mt)
426 log.Printf("attachment: %s %s", mt, u)
427 if mt == "image/jpeg" || mt == "image/png" ||
428 mt == "image/gif" {
429 donk := savedonk(u, name, mt)
430 if donk != nil {
431 xonk.Donks = append(xonk.Donks, donk)
432 }
433 }
434 }
435 }
436 tags, _ := jsongetarray(obj, "tag")
437 for _, tag := range tags {
438 tt, _ := jsongetstring(tag, "type")
439 name, _ := jsongetstring(tag, "name")
440 if tt == "Emoji" {
441 icon, _ := jsongetmap(tag, "icon")
442 mt, _ := jsongetstring(icon, "mediaType")
443 u, _ := jsongetstring(icon, "url")
444 donk := savedonk(u, name, mt)
445 if donk != nil {
446 xonk.Donks = append(xonk.Donks, donk)
447 }
448 }
449 }
450 }
451 audience = append(audience, who)
452
453 audience = oneofakind(audience)
454
455 xonk.What = what
456 xonk.Honker = who
457 xonk.XID = xid
458 xonk.RID = rid
459 xonk.Date, _ = time.Parse(time.RFC3339, dt)
460 xonk.URL = url
461 xonk.Noise = content
462 xonk.Audience = audience
463
464 return &xonk
465}
466
467func rubadubdub(user *WhatAbout, req map[string]interface{}) {
468 xid, _ := jsongetstring(req, "id")
469 reqactor, _ := jsongetstring(req, "actor")
470 j := NewJunk()
471 j["@context"] = itiswhatitis
472 j["id"] = user.URL + "/dub/" + xid
473 j["type"] = "Accept"
474 j["actor"] = user.URL
475 j["to"] = reqactor
476 j["published"] = time.Now().UTC().Format(time.RFC3339)
477 j["object"] = req
478
479 WriteJunk(os.Stdout, j)
480
481 actor, _ := jsongetstring(req, "actor")
482 inbox, _, err := getboxes(actor)
483 if err != nil {
484 log.Printf("can't get dub box: %s", err)
485 return
486 }
487 keyname, key := ziggy(user)
488 err = PostJunk(keyname, key, inbox, j)
489 if err != nil {
490 log.Printf("can't rub a dub: %s", err)
491 return
492 }
493 stmtSaveDub.Exec(user.ID, actor, actor, "dub")
494}
495
496func subsub(user *WhatAbout, xid string) {
497
498 j := NewJunk()
499 j["@context"] = itiswhatitis
500 j["id"] = user.URL + "/sub/" + xid
501 j["type"] = "Follow"
502 j["actor"] = user.URL
503 j["to"] = xid
504 j["object"] = xid
505 j["published"] = time.Now().UTC().Format(time.RFC3339)
506
507 inbox, _, err := getboxes(xid)
508 if err != nil {
509 log.Printf("can't send follow: %s", err)
510 return
511 }
512 WriteJunk(os.Stdout, j)
513 keyname, key := ziggy(user)
514 err = PostJunk(keyname, key, inbox, j)
515 if err != nil {
516 log.Printf("failed to subsub: %s", err)
517 }
518}
519
520func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
521 dt := h.Date.Format(time.RFC3339)
522 var jo map[string]interface{}
523 j := NewJunk()
524 j["id"] = user.URL + "/" + h.What + "/" + h.XID
525 j["actor"] = user.URL
526 j["published"] = dt
527 j["to"] = h.Audience[0]
528 if len(h.Audience) > 1 {
529 j["cc"] = h.Audience[1:]
530 }
531
532 switch h.What {
533 case "tonk":
534 fallthrough
535 case "honk":
536 j["type"] = "Create"
537 jo = NewJunk()
538 jo["id"] = user.URL + "/h/" + h.XID
539 jo["type"] = "Note"
540 jo["published"] = dt
541 jo["url"] = user.URL + "/h/" + h.XID
542 jo["attributedTo"] = user.URL
543 if h.RID != "" {
544 jo["inReplyTo"] = h.RID
545 }
546 jo["to"] = h.Audience[0]
547 if len(h.Audience) > 1 {
548 jo["cc"] = h.Audience[1:]
549 }
550 jo["content"] = h.Noise
551 var tags []interface{}
552 g := bunchofgrapes(h.Noise)
553 for _, m := range g {
554 t := NewJunk()
555 t["type"] = "Mention"
556 t["name"] = m.who
557 t["href"] = m.where
558 tags = append(tags, t)
559 }
560 herd := herdofemus(h.Noise)
561 for _, e := range herd {
562 t := NewJunk()
563 t["id"] = e.ID
564 t["type"] = "Emoji"
565 t["name"] = e.Name
566 i := NewJunk()
567 i["type"] = "Image"
568 i["mediaType"] = "image/png"
569 i["url"] = e.ID
570 t["icon"] = i
571 tags = append(tags, t)
572 }
573 if len(tags) > 0 {
574 jo["tag"] = tags
575 }
576 var atts []interface{}
577 for _, d := range h.Donks {
578 jd := NewJunk()
579 jd["mediaType"] = d.Media
580 jd["name"] = d.Name
581 jd["type"] = "Document"
582 jd["url"] = d.URL
583 atts = append(atts, jd)
584 }
585 if len(atts) > 0 {
586 jo["attachment"] = atts
587 }
588 j["object"] = jo
589 case "bonk":
590 j["type"] = "Announce"
591 j["object"] = h.XID
592 }
593
594 return j, jo
595}
596
597func honkworldwide(user *WhatAbout, honk *Honk) {
598 aud := append([]string{}, honk.Audience...)
599 for i, a := range aud {
600 if a == thewholeworld || a == user.URL {
601 aud[i] = ""
602 }
603 }
604 keyname, key := ziggy(user)
605 jonk, _ := jonkjonk(user, honk)
606 jonk["@context"] = itiswhatitis
607 for _, f := range getdubs(user.ID) {
608 inbox, _, err := getboxes(f.XID)
609 if err != nil {
610 log.Printf("error getting inbox %s: %s", f.XID, err)
611 continue
612 }
613 err = PostJunk(keyname, key, inbox, jonk)
614 if err != nil {
615 log.Printf("failed to post json to %s: %s", inbox, err)
616 }
617 for i, a := range aud {
618 if a == f.XID {
619 aud[i] = ""
620 }
621 }
622 }
623 for _, a := range aud {
624 if a != "" && !strings.HasSuffix(a, "/followers") {
625 inbox, _, err := getboxes(a)
626 if err != nil {
627 log.Printf("error getting inbox %s: %s", a, err)
628 continue
629 }
630 err = PostJunk(keyname, key, inbox, jonk)
631 if err != nil {
632 log.Printf("failed to post json to %s: %s", inbox, err)
633 }
634 }
635 }
636}
637
638func asjonker(user *WhatAbout) map[string]interface{} {
639 whatabout := obfusbreak(user.About)
640
641 j := NewJunk()
642 j["@context"] = itiswhatitis
643 j["id"] = user.URL
644 j["type"] = "Person"
645 j["inbox"] = user.URL + "/inbox"
646 j["outbox"] = user.URL + "/outbox"
647 j["name"] = user.Display
648 j["preferredUsername"] = user.Name
649 j["summary"] = whatabout
650 j["url"] = user.URL
651 a := NewJunk()
652 a["type"] = "icon"
653 a["mediaType"] = "image/png"
654 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
655 j["icon"] = a
656 k := NewJunk()
657 k["id"] = user.URL + "#key"
658 k["owner"] = user.URL
659 k["publicKeyPem"] = user.Key
660 j["publicKey"] = k
661
662 return j
663}