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 req.Header.Set("Accept", theonetruename)
123 req.Header.Set("Accept-Encoding", "gzip")
124 resp, err := client.Do(req)
125 if err != nil {
126 return nil, err
127 }
128 if resp.StatusCode != 200 {
129 resp.Body.Close()
130 return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
131 }
132 if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
133 gz, err := gzip.NewReader(resp.Body)
134 if err != nil {
135 resp.Body.Close()
136 return nil, err
137 }
138 resp.Body = &gzCloser{r: gz, under: resp.Body}
139 }
140 defer resp.Body.Close()
141 j, err := ReadJunk(resp.Body)
142 return j, err
143}
144
145func jsonfindinterface(ii interface{}, keys []string) interface{} {
146 for _, key := range keys {
147 idx, err := strconv.Atoi(key)
148 if err == nil {
149 m := ii.([]interface{})
150 if idx >= len(m) {
151 return nil
152 }
153 ii = m[idx]
154 } else {
155 m := ii.(map[string]interface{})
156 ii = m[key]
157 if ii == nil {
158 return nil
159 }
160 }
161 }
162 return ii
163}
164func jsonfindstring(j interface{}, keys []string) (string, bool) {
165 s, ok := jsonfindinterface(j, keys).(string)
166 return s, ok
167}
168func jsonfindarray(j interface{}, keys []string) ([]interface{}, bool) {
169 a, ok := jsonfindinterface(j, keys).([]interface{})
170 return a, ok
171}
172func jsonfindmap(j interface{}, keys []string) (map[string]interface{}, bool) {
173 m, ok := jsonfindinterface(j, keys).(map[string]interface{})
174 return m, ok
175}
176func jsongetstring(j interface{}, key string) (string, bool) {
177 return jsonfindstring(j, []string{key})
178}
179func jsongetarray(j interface{}, key string) ([]interface{}, bool) {
180 return jsonfindarray(j, []string{key})
181}
182func jsongetmap(j interface{}, key string) (map[string]interface{}, bool) {
183 return jsonfindmap(j, []string{key})
184}
185
186func savedonk(url string, name, media string) *Donk {
187 log.Printf("saving donk: %s", url)
188 var donk Donk
189 row := stmtFindFile.QueryRow(url)
190 err := row.Scan(&donk.FileID)
191 if err == nil {
192 return &donk
193 }
194 if err != nil && err != sql.ErrNoRows {
195 log.Printf("err querying: %s", err)
196 }
197 resp, err := http.Get(url)
198 if err != nil {
199 log.Printf("errer fetching %s: %s", url, err)
200 return nil
201 }
202 defer resp.Body.Close()
203 if resp.StatusCode != 200 {
204 return nil
205 }
206 var buf bytes.Buffer
207 io.Copy(&buf, resp.Body)
208
209 xid := xfiltrate()
210
211 res, err := stmtSaveFile.Exec(xid, name, url, media, buf.Bytes())
212 if err != nil {
213 log.Printf("error saving file %s: %s", url, err)
214 return nil
215 }
216 donk.FileID, _ = res.LastInsertId()
217 return &donk
218}
219
220func needxonk(user *WhatAbout, x *Honk) bool {
221 if strings.HasPrefix(x.XID, user.URL+"/h/") {
222 return false
223 }
224 if x.What == "eradicate" {
225 return true
226 }
227 row := stmtFindXonk.QueryRow(user.ID, x.XID)
228 err := row.Scan(&x.ID)
229 if err == nil {
230 return false
231 }
232 if err != sql.ErrNoRows {
233 log.Printf("err querying xonk: %s", err)
234 }
235 return true
236}
237
238func savexonk(x *Honk) {
239 if x.What == "eradicate" {
240 log.Printf("eradicating %s by %s", x.RID, x.Honker)
241 _, err := stmtDeleteHonk.Exec(x.RID, x.Honker)
242 if err != nil {
243 log.Printf("error eradicating: %s", err)
244 }
245 return
246 }
247 dt := x.Date.UTC().Format(dbtimeformat)
248 aud := strings.Join(x.Audience, " ")
249 res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud, x.Noise)
250 if err != nil {
251 log.Printf("err saving xonk: %s", err)
252 return
253 }
254 x.ID, _ = res.LastInsertId()
255 for _, d := range x.Donks {
256 _, err = stmtSaveDonk.Exec(x.ID, d.FileID)
257 if err != nil {
258 log.Printf("err saving donk: %s", err)
259 return
260 }
261 }
262}
263
264var boxofboxes = make(map[string]string)
265var boxlock sync.Mutex
266
267func getboxes(ident string) (string, string, error) {
268 boxlock.Lock()
269 b, ok := boxofboxes[ident]
270 boxlock.Unlock()
271 if ok {
272 m := strings.Split(b, "\n")
273 return m[0], m[1], nil
274 }
275 j, err := GetJunk(ident)
276 if err != nil {
277 return "", "", err
278 }
279 inbox, _ := jsongetstring(j, "inbox")
280 outbox, _ := jsongetstring(j, "outbox")
281 boxlock.Lock()
282 boxofboxes[ident] = inbox + "\n" + outbox
283 boxlock.Unlock()
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, 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 xonkxonk(item interface{}) *Honk {
357 // id, _ := jsongetstring(item, "id")
358 what, _ := jsongetstring(item, "type")
359 dt, _ := jsongetstring(item, "published")
360
361 var audience []string
362 var err error
363 var xid, rid, url, content string
364 var obj map[string]interface{}
365 switch what {
366 case "Announce":
367 xid, _ = jsongetstring(item, "object")
368 log.Printf("getting bonk: %s", xid)
369 obj, err = GetJunk(xid)
370 if err != nil {
371 log.Printf("error regetting: %s", err)
372 }
373 what = "bonk"
374 case "Create":
375 obj, _ = jsongetmap(item, "object")
376 what = "honk"
377 case "Delete":
378 obj, _ = jsongetmap(item, "object")
379 what = "eradicate"
380 default:
381 log.Printf("unknown activity: %s", what)
382 return nil
383 }
384 who, _ := jsongetstring(item, "actor")
385
386 var xonk Honk
387 if obj != nil {
388 ot, _ := jsongetstring(obj, "type")
389 url, _ = jsongetstring(obj, "url")
390 if ot == "Note" || ot == "Article" {
391 audience = newphone(audience, obj)
392 xid, _ = jsongetstring(obj, "id")
393 content, _ = jsongetstring(obj, "content")
394 summary, _ := jsongetstring(obj, "summary")
395 if summary != "" {
396 content = "<p>summary: " + summary + content
397 }
398 rid, _ = jsongetstring(obj, "inReplyTo")
399 if what == "honk" && rid != "" {
400 what = "tonk"
401 }
402 }
403 if ot == "Tombstone" {
404 rid, _ = jsongetstring(obj, "id")
405 }
406 atts, _ := jsongetarray(obj, "attachment")
407 for _, att := range atts {
408 at, _ := jsongetstring(att, "type")
409 mt, _ := jsongetstring(att, "mediaType")
410 u, _ := jsongetstring(att, "url")
411 name, _ := jsongetstring(att, "name")
412 if at == "Document" {
413 mt = strings.ToLower(mt)
414 log.Printf("attachment: %s %s", mt, u)
415 if mt == "image/jpeg" || mt == "image/png" ||
416 mt == "image/gif" {
417 donk := savedonk(u, name, mt)
418 if donk != nil {
419 xonk.Donks = append(xonk.Donks, donk)
420 }
421 }
422 }
423 }
424 tags, _ := jsongetarray(obj, "tag")
425 for _, tag := range tags {
426 tt, _ := jsongetstring(tag, "type")
427 name, _ := jsongetstring(tag, "name")
428 if tt == "Emoji" {
429 icon, _ := jsongetmap(tag, "icon")
430 mt, _ := jsongetstring(icon, "mediaType")
431 u, _ := jsongetstring(icon, "url")
432 donk := savedonk(u, name, mt)
433 if donk != nil {
434 xonk.Donks = append(xonk.Donks, donk)
435 }
436 }
437 }
438 }
439 audience = append(audience, who)
440
441 audience = oneofakind(audience)
442
443 xonk.What = what
444 xonk.Honker = who
445 xonk.XID = xid
446 xonk.RID = rid
447 xonk.Date, _ = time.Parse(time.RFC3339, dt)
448 xonk.URL = url
449 xonk.Noise = content
450 xonk.Audience = audience
451
452 return &xonk
453}
454
455func rubadubdub(user *WhatAbout, req map[string]interface{}) {
456 xid, _ := jsongetstring(req, "id")
457 reqactor, _ := jsongetstring(req, "actor")
458 j := NewJunk()
459 j["@context"] = itiswhatitis
460 j["id"] = user.URL + "/dub/" + xid
461 j["type"] = "Accept"
462 j["actor"] = user.URL
463 j["to"] = reqactor
464 j["published"] = time.Now().UTC().Format(time.RFC3339)
465 j["object"] = req
466
467 WriteJunk(os.Stdout, j)
468
469 actor, _ := jsongetstring(req, "actor")
470 inbox, _, err := getboxes(actor)
471 if err != nil {
472 log.Printf("can't get dub box: %s", err)
473 return
474 }
475 keyname, key := ziggy(user.Name)
476 err = PostJunk(keyname, key, inbox, j)
477 if err != nil {
478 log.Printf("can't rub a dub: %s", err)
479 return
480 }
481 stmtSaveDub.Exec(user.ID, actor, actor, "dub")
482}
483
484func subsub(user *WhatAbout, xid string) {
485 j := NewJunk()
486 j["@context"] = itiswhatitis
487 j["id"] = user.URL + "/sub/" + xid
488 j["type"] = "Follow"
489 j["actor"] = user.URL
490 j["to"] = xid
491 j["object"] = xid
492 j["published"] = time.Now().UTC().Format(time.RFC3339)
493
494 inbox, _, err := getboxes(xid)
495 if err != nil {
496 log.Printf("can't send follow: %s", err)
497 return
498 }
499 WriteJunk(os.Stdout, j)
500 keyname, key := ziggy(user.Name)
501 err = PostJunk(keyname, key, inbox, j)
502 if err != nil {
503 log.Printf("failed to subsub: %s", err)
504 }
505}
506
507func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
508 dt := h.Date.Format(time.RFC3339)
509 var jo map[string]interface{}
510 j := NewJunk()
511 j["id"] = user.URL + "/" + h.What + "/" + h.XID
512 j["actor"] = user.URL
513 j["published"] = dt
514 j["to"] = h.Audience[0]
515 if len(h.Audience) > 1 {
516 j["cc"] = h.Audience[1:]
517 }
518
519 switch h.What {
520 case "tonk":
521 fallthrough
522 case "honk":
523 j["type"] = "Create"
524 jo = NewJunk()
525 jo["id"] = user.URL + "/h/" + h.XID
526 jo["type"] = "Note"
527 jo["published"] = dt
528 jo["url"] = user.URL + "/h/" + h.XID
529 jo["attributedTo"] = user.URL
530 if h.RID != "" {
531 jo["inReplyTo"] = h.RID
532 }
533 jo["to"] = h.Audience[0]
534 if len(h.Audience) > 1 {
535 jo["cc"] = h.Audience[1:]
536 }
537 jo["content"] = h.Noise
538 var tags []interface{}
539 g := bunchofgrapes(h.Noise)
540 for _, m := range g {
541 t := NewJunk()
542 t["type"] = "Mention"
543 t["name"] = m.who
544 t["href"] = m.where
545 tags = append(tags, t)
546 }
547 herd := herdofemus(h.Noise)
548 for _, e := range herd {
549 t := NewJunk()
550 t["id"] = e.ID
551 t["type"] = "Emoji"
552 t["name"] = e.Name
553 i := NewJunk()
554 i["type"] = "Image"
555 i["mediaType"] = "image/png"
556 i["url"] = e.ID
557 t["icon"] = i
558 tags = append(tags, t)
559 }
560 if len(tags) > 0 {
561 jo["tag"] = tags
562 }
563 var atts []interface{}
564 for _, d := range h.Donks {
565 if re_emus.MatchString(d.Name) {
566 continue
567 }
568 jd := NewJunk()
569 jd["mediaType"] = d.Media
570 jd["name"] = d.Name
571 jd["type"] = "Document"
572 jd["url"] = d.URL
573 atts = append(atts, jd)
574 }
575 if len(atts) > 0 {
576 jo["attachment"] = atts
577 }
578 j["object"] = jo
579 case "bonk":
580 j["type"] = "Announce"
581 j["object"] = h.XID
582 }
583
584 return j, jo
585}
586
587func honkworldwide(user *WhatAbout, honk *Honk) {
588 rcpts := make(map[string]bool)
589 for _, a := range honk.Audience {
590 if a != thewholeworld && a != user.URL {
591 rcpts[a] = true
592 }
593 }
594 jonk, _ := jonkjonk(user, honk)
595 jonk["@context"] = itiswhatitis
596 var buf bytes.Buffer
597 WriteJunk(&buf, jonk)
598 msg := buf.Bytes()
599 for _, f := range getdubs(user.ID) {
600 deliverate(0, user.Name, f.XID, msg)
601 delete(rcpts, f.XID)
602 }
603 for a := range rcpts {
604 if !strings.HasSuffix(a, "/followers") {
605 deliverate(0, user.Name, a, msg)
606 }
607 }
608}
609
610func asjonker(user *WhatAbout) map[string]interface{} {
611 about := obfusbreak(user.About)
612
613 j := NewJunk()
614 j["@context"] = itiswhatitis
615 j["id"] = user.URL
616 j["type"] = "Person"
617 j["inbox"] = user.URL + "/inbox"
618 j["outbox"] = user.URL + "/outbox"
619 j["name"] = user.Display
620 j["preferredUsername"] = user.Name
621 j["summary"] = about
622 j["url"] = user.URL
623 a := NewJunk()
624 a["type"] = "icon"
625 a["mediaType"] = "image/png"
626 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
627 j["icon"] = a
628 k := NewJunk()
629 k["id"] = user.URL + "#key"
630 k["owner"] = user.URL
631 k["publicKeyPem"] = user.Key
632 j["publicKey"] = k
633
634 return j
635}