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