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 "crypto/rsa"
21 "database/sql"
22 "fmt"
23 "io"
24 "log"
25 notrand "math/rand"
26 "net/http"
27 "net/url"
28 "os"
29 "strings"
30 "sync"
31 "time"
32
33 "humungus.tedunangst.com/r/webs/httpsig"
34 "humungus.tedunangst.com/r/webs/image"
35 "humungus.tedunangst.com/r/webs/junk"
36)
37
38var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
39var thefakename = `application/activity+json`
40var falsenames = []string{
41 `application/ld+json`,
42 `application/activity+json`,
43}
44var itiswhatitis = "https://www.w3.org/ns/activitystreams"
45var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
46
47func friendorfoe(ct string) bool {
48 ct = strings.ToLower(ct)
49 for _, at := range falsenames {
50 if strings.HasPrefix(ct, at) {
51 return true
52 }
53 }
54 return false
55}
56
57func PostJunk(keyname string, key *rsa.PrivateKey, url string, j junk.Junk) error {
58 var buf bytes.Buffer
59 j.Write(&buf)
60 return PostMsg(keyname, key, url, buf.Bytes())
61}
62
63func PostMsg(keyname string, key *rsa.PrivateKey, url string, msg []byte) error {
64 client := http.DefaultClient
65 req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
66 if err != nil {
67 return err
68 }
69 req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
70 req.Header.Set("Content-Type", theonetruename)
71 httpsig.SignRequest(keyname, key, req, msg)
72 resp, err := client.Do(req)
73 if err != nil {
74 return err
75 }
76 resp.Body.Close()
77 switch resp.StatusCode {
78 case 200:
79 case 201:
80 case 202:
81 default:
82 return fmt.Errorf("http post status: %d", resp.StatusCode)
83 }
84 log.Printf("successful post: %s %d", url, resp.StatusCode)
85 return nil
86}
87
88func GetJunk(url string) (junk.Junk, error) {
89 return GetJunkTimeout(url, 30*time.Second)
90}
91
92func GetJunkFast(url string) (junk.Junk, error) {
93 return GetJunkTimeout(url, 5*time.Second)
94}
95
96func GetJunkHardMode(url string) (junk.Junk, error) {
97 j, err := GetJunk(url)
98 if err != nil {
99 emsg := err.Error()
100 if emsg == "http get status: 502" || strings.Contains(emsg, "timeout") {
101 log.Printf("trying again after error: %s", emsg)
102 time.Sleep(time.Duration(60+notrand.Int63n(60)) * time.Second)
103 j, err = GetJunk(url)
104 if err != nil {
105 log.Printf("still couldn't get it")
106 } else {
107 log.Printf("retry success!")
108 }
109 }
110 }
111 return j, err
112}
113
114func GetJunkTimeout(url string, timeout time.Duration) (junk.Junk, error) {
115 at := thefakename
116 if strings.Contains(url, ".well-known/webfinger?resource") {
117 at = "application/jrd+json"
118 }
119 return junk.Get(url, junk.GetArgs{
120 Accept: at,
121 Agent: "honksnonk/5.0; " + serverName,
122 Timeout: timeout,
123 })
124}
125
126func savedonk(url string, name, desc, media string, localize bool) *Donk {
127 if url == "" {
128 return nil
129 }
130 var donk Donk
131 row := stmtFindFile.QueryRow(url)
132 err := row.Scan(&donk.FileID)
133 if err == nil {
134 return &donk
135 }
136 log.Printf("saving donk: %s", url)
137 if err != nil && err != sql.ErrNoRows {
138 log.Printf("error querying: %s", err)
139 }
140 xid := xfiltrate()
141 data := []byte{}
142 if localize {
143 resp, err := http.Get(url)
144 if err != nil {
145 log.Printf("error fetching %s: %s", url, err)
146 localize = false
147 goto saveit
148 }
149 defer resp.Body.Close()
150 if resp.StatusCode != 200 {
151 localize = false
152 goto saveit
153 }
154 var buf bytes.Buffer
155 io.Copy(&buf, resp.Body)
156
157 data = buf.Bytes()
158 if strings.HasPrefix(media, "image") {
159 img, err := image.Vacuum(&buf,
160 image.Params{LimitSize: 4800 * 4800, MaxWidth: 2048, MaxHeight: 2048})
161 if err != nil {
162 log.Printf("unable to decode image: %s", err)
163 localize = false
164 data = []byte{}
165 goto saveit
166 }
167 data = img.Data
168 format := img.Format
169 media = "image/" + format
170 if format == "jpeg" {
171 format = "jpg"
172 }
173 xid = xid + "." + format
174 } else if len(data) > 100000 {
175 log.Printf("not saving large attachment")
176 localize = false
177 data = []byte{}
178 }
179 }
180saveit:
181 fileid, err := savefile(xid, name, desc, url, media, localize, data)
182 if err != nil {
183 log.Printf("error saving file %s: %s", url, err)
184 return nil
185 }
186 donk.FileID = fileid
187 return &donk
188}
189
190func iszonked(userid int64, xid string) bool {
191 row := stmtFindZonk.QueryRow(userid, xid)
192 var id int64
193 err := row.Scan(&id)
194 if err == nil {
195 return true
196 }
197 if err != sql.ErrNoRows {
198 log.Printf("err querying zonk: %s", err)
199 }
200 return false
201}
202
203func needxonk(user *WhatAbout, x *Honk) bool {
204 if thoudostbitethythumb(user.ID, x.Audience, x.XID) {
205 log.Printf("not saving thumb biter? %s via %s", x.XID, x.Honker)
206 return false
207 }
208 return needxonkid(user, x.XID)
209}
210func needxonkid(user *WhatAbout, xid string) bool {
211 if strings.HasPrefix(xid, user.URL+"/") {
212 return false
213 }
214 if thoudostbitethythumb(user.ID, nil, xid) {
215 log.Printf("don't need thumb biter? %s", xid)
216 return false
217 }
218 if iszonked(user.ID, xid) {
219 log.Printf("already zonked: %s", xid)
220 return false
221 }
222 row := stmtFindXonk.QueryRow(user.ID, xid)
223 var id int64
224 err := row.Scan(&id)
225 if err == nil {
226 return false
227 }
228 if err != sql.ErrNoRows {
229 log.Printf("err querying xonk: %s", err)
230 }
231 return true
232}
233
234func eradicatexonk(userid int64, xid string) {
235 xonk := getxonk(userid, xid)
236 if xonk != nil {
237 deletehonk(xonk.ID)
238 }
239 _, err := stmtSaveZonker.Exec(userid, xid, "zonk")
240 if err != nil {
241 log.Printf("error eradicating: %s", err)
242 }
243}
244
245func savexonk(x *Honk) {
246 log.Printf("saving xonk: %s", x.XID)
247 go prehandle(x.Honker)
248 go prehandle(x.Oonker)
249 savehonk(x)
250}
251
252type Box struct {
253 In string
254 Out string
255 Shared string
256}
257
258var boxofboxes = make(map[string]*Box)
259var boxlock sync.Mutex
260var boxinglock sync.Mutex
261
262func getboxes(ident string) (*Box, error) {
263 boxlock.Lock()
264 b, ok := boxofboxes[ident]
265 boxlock.Unlock()
266 if ok {
267 return b, nil
268 }
269
270 boxinglock.Lock()
271 defer boxinglock.Unlock()
272
273 boxlock.Lock()
274 b, ok = boxofboxes[ident]
275 boxlock.Unlock()
276 if ok {
277 return b, nil
278 }
279
280 var info string
281 row := stmtGetXonker.QueryRow(ident, "boxes")
282 err := row.Scan(&info)
283 if err != nil {
284 j, err := GetJunk(ident)
285 if err != nil {
286 return nil, err
287 }
288 inbox, _ := j.GetString("inbox")
289 outbox, _ := j.GetString("outbox")
290 sbox, _ := j.FindString([]string{"endpoints", "sharedInbox"})
291 b = &Box{In: inbox, Out: outbox, Shared: sbox}
292 if inbox != "" {
293 m := strings.Join([]string{inbox, outbox, sbox}, " ")
294 _, err = stmtSaveXonker.Exec(ident, m, "boxes")
295 if err != nil {
296 log.Printf("error saving boxes: %s", err)
297 }
298 }
299 } else {
300 m := strings.Split(info, " ")
301 b = &Box{In: m[0], Out: m[1], Shared: m[2]}
302 }
303
304 boxlock.Lock()
305 boxofboxes[ident] = b
306 boxlock.Unlock()
307 return b, nil
308}
309
310func gimmexonks(user *WhatAbout, outbox string) {
311 log.Printf("getting outbox: %s", outbox)
312 j, err := GetJunk(outbox)
313 if err != nil {
314 log.Printf("error getting outbox: %s", err)
315 return
316 }
317 t, _ := j.GetString("type")
318 origin := originate(outbox)
319 if t == "OrderedCollection" {
320 items, _ := j.GetArray("orderedItems")
321 if items == nil {
322 obj, ok := j.GetMap("first")
323 if ok {
324 items, _ = obj.GetArray("orderedItems")
325 } else {
326 page1, _ := j.GetString("first")
327 j, err = GetJunk(page1)
328 if err != nil {
329 log.Printf("error gettings page1: %s", err)
330 return
331 }
332 items, _ = j.GetArray("orderedItems")
333 }
334 }
335 if len(items) > 20 {
336 items = items[0:20]
337 }
338 for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
339 items[i], items[j] = items[j], items[i]
340 }
341 for _, item := range items {
342 obj, ok := item.(junk.Junk)
343 if !ok {
344 continue
345 }
346 xonk := xonkxonk(user, obj, origin)
347 if xonk != nil {
348 savexonk(xonk)
349 }
350 }
351 }
352}
353
354func peeppeep() {
355 user, _ := butwhatabout("htest")
356 honkers := gethonkers(user.ID)
357 for _, f := range honkers {
358 if f.Flavor != "peep" {
359 continue
360 }
361 log.Printf("getting updates: %s", f.XID)
362 box, err := getboxes(f.XID)
363 if err != nil {
364 log.Printf("error getting outbox: %s", err)
365 continue
366 }
367 gimmexonks(user, box.Out)
368 }
369}
370func whosthere(xid string) ([]string, string) {
371 obj, err := GetJunk(xid)
372 if err != nil {
373 log.Printf("error getting remote xonk: %s", err)
374 return nil, ""
375 }
376 convoy, _ := obj.GetString("context")
377 if convoy == "" {
378 convoy, _ = obj.GetString("conversation")
379 }
380 return newphone(nil, obj), convoy
381}
382
383func newphone(a []string, obj junk.Junk) []string {
384 for _, addr := range []string{"to", "cc", "attributedTo"} {
385 who, _ := obj.GetString(addr)
386 if who != "" {
387 a = append(a, who)
388 }
389 whos, _ := obj.GetArray(addr)
390 for _, w := range whos {
391 who, _ := w.(string)
392 if who != "" {
393 a = append(a, who)
394 }
395 }
396 }
397 return a
398}
399
400func extractattrto(obj junk.Junk) string {
401 who, _ := obj.GetString("attributedTo")
402 if who != "" {
403 return who
404 }
405 o, ok := obj.GetMap("attributedTo")
406 if ok {
407 id, ok := o.GetString("id")
408 if ok {
409 return id
410 }
411 }
412 arr, _ := obj.GetArray("attributedTo")
413 for _, a := range arr {
414 o, ok := a.(junk.Junk)
415 if ok {
416 t, _ := o.GetString("type")
417 id, _ := o.GetString("id")
418 if t == "Person" || t == "" {
419 return id
420 }
421 }
422 }
423 return ""
424}
425
426func consumeactivity(user *WhatAbout, j junk.Junk, origin string) {
427 xonk := xonkxonk(user, j, origin)
428 if xonk != nil {
429 savexonk(xonk)
430 }
431}
432
433func xonkxonk(user *WhatAbout, item junk.Junk, origin string) *Honk {
434 depth := 0
435 maxdepth := 10
436 currenttid := ""
437 var xonkxonkfn func(item junk.Junk, origin string) *Honk
438
439 saveoneup := func(xid string) {
440 log.Printf("getting oneup: %s", xid)
441 if depth >= maxdepth {
442 log.Printf("in too deep")
443 return
444 }
445 obj, err := GetJunkHardMode(xid)
446 if err != nil {
447 log.Printf("error getting oneup: %s: %s", xid, err)
448 return
449 }
450 depth++
451 xonk := xonkxonkfn(obj, originate(xid))
452 if xonk != nil {
453 savexonk(xonk)
454 }
455 depth--
456 }
457
458 xonkxonkfn = func(item junk.Junk, origin string) *Honk {
459 // id, _ := item.GetString( "id")
460 what, _ := item.GetString("type")
461 dt, _ := item.GetString("published")
462
463 var err error
464 var xid, rid, url, content, precis, convoy string
465 var replies []string
466 var obj junk.Junk
467 var ok bool
468 isUpdate := false
469 switch what {
470 case "Delete":
471 obj, ok = item.GetMap("object")
472 if ok {
473 xid, _ = obj.GetString("id")
474 } else {
475 xid, _ = item.GetString("object")
476 }
477 if xid == "" {
478 return nil
479 }
480 if originate(xid) != origin {
481 log.Printf("forged delete: %s", xid)
482 return nil
483 }
484 log.Printf("eradicating %s", xid)
485 eradicatexonk(user.ID, xid)
486 return nil
487 case "Tombstone":
488 xid, _ = item.GetString("id")
489 if xid == "" {
490 return nil
491 }
492 if originate(xid) != origin {
493 log.Printf("forged delete: %s", xid)
494 return nil
495 }
496 log.Printf("eradicating %s", xid)
497 eradicatexonk(user.ID, xid)
498 return nil
499 case "Announce":
500 obj, ok = item.GetMap("object")
501 if ok {
502 xid, _ = obj.GetString("id")
503 } else {
504 xid, _ = item.GetString("object")
505 }
506 if !needxonkid(user, xid) {
507 return nil
508 }
509 log.Printf("getting bonk: %s", xid)
510 obj, err = GetJunkHardMode(xid)
511 if err != nil {
512 log.Printf("error getting bonk: %s: %s", xid, err)
513 }
514 origin = originate(xid)
515 what = "bonk"
516 case "Update":
517 isUpdate = true
518 fallthrough
519 case "Create":
520 obj, ok = item.GetMap("object")
521 if !ok {
522 xid, _ = item.GetString("object")
523 log.Printf("getting created honk: %s", xid)
524 obj, err = GetJunkHardMode(xid)
525 if err != nil {
526 log.Printf("error getting creation: %s", err)
527 }
528 }
529 what = "honk"
530 case "Read":
531 xid, ok = item.GetString("object")
532 if ok {
533 if !needxonkid(user, xid) {
534 log.Printf("don't need read obj: %s", xid)
535 return nil
536 }
537 obj, err = GetJunkHardMode(xid)
538 if err != nil {
539 log.Printf("error getting read: %s", err)
540 return nil
541 }
542 return xonkxonkfn(obj, originate(xid))
543 }
544 return nil
545 case "Video":
546 fallthrough
547 case "Question":
548 fallthrough
549 case "Note":
550 fallthrough
551 case "Article":
552 fallthrough
553 case "Page":
554 obj = item
555 what = "honk"
556 default:
557 log.Printf("unknown activity: %s", what)
558 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
559 item.Write(fd)
560 io.WriteString(fd, "\n")
561 fd.Close()
562 return nil
563 }
564
565 var xonk Honk
566 // early init
567 xonk.UserID = user.ID
568 xonk.Honker, _ = item.GetString("actor")
569 if obj != nil {
570 if xonk.Honker == "" {
571 xonk.Honker = extractattrto(obj)
572 }
573 xonk.Oonker = extractattrto(obj)
574 if xonk.Oonker == xonk.Honker {
575 xonk.Oonker = ""
576 }
577 xonk.Audience = newphone(nil, obj)
578 }
579 xonk.Audience = append(xonk.Audience, xonk.Honker)
580 xonk.Audience = oneofakind(xonk.Audience)
581 for _, a := range xonk.Audience {
582 if a == user.URL {
583 xonk.Whofore = 1
584 }
585 }
586
587 if obj != nil {
588 ot, _ := obj.GetString("type")
589 url, _ = obj.GetString("url")
590 dt2, ok := obj.GetString("published")
591 if ok {
592 dt = dt2
593 }
594 xid, _ = obj.GetString("id")
595 precis, _ = obj.GetString("summary")
596 if precis == "" {
597 precis, _ = obj.GetString("name")
598 }
599 content, _ = obj.GetString("content")
600 if !strings.HasPrefix(content, "<p>") {
601 content = "<p>" + content
602 }
603 sens, _ := obj["sensitive"].(bool)
604 if sens && precis == "" {
605 precis = "unspecified horror"
606 }
607 rid, ok = obj.GetString("inReplyTo")
608 if !ok {
609 robj, ok := obj.GetMap("inReplyTo")
610 if ok {
611 rid, _ = robj.GetString("id")
612 }
613 }
614 convoy, _ = obj.GetString("context")
615 if strings.HasSuffix(convoy, "#context") &&
616 originate(convoy) != originate(xid) {
617 // friendica...
618 convoy = ""
619 }
620 if convoy == "" {
621 convoy, _ = obj.GetString("conversation")
622 }
623 if ot == "Question" {
624 if what == "honk" {
625 what = "qonk"
626 }
627 content += "<ul>"
628 ans, _ := obj.GetArray("oneOf")
629 for _, ai := range ans {
630 a, ok := ai.(junk.Junk)
631 if !ok {
632 continue
633 }
634 as, _ := a.GetString("name")
635 content += "<li>" + as
636 }
637 ans, _ = obj.GetArray("anyOf")
638 for _, ai := range ans {
639 a, ok := ai.(junk.Junk)
640 if !ok {
641 continue
642 }
643 as, _ := a.GetString("name")
644 content += "<li>" + as
645 }
646 content += "</ul>"
647 }
648 if what == "honk" && rid != "" {
649 what = "tonk"
650 }
651 atts, _ := obj.GetArray("attachment")
652 for i, atti := range atts {
653 att, ok := atti.(junk.Junk)
654 if !ok {
655 continue
656 }
657 at, _ := att.GetString("type")
658 mt, _ := att.GetString("mediaType")
659 u, _ := att.GetString("url")
660 name, _ := att.GetString("name")
661 desc, _ := att.GetString("summary")
662 if desc == "" {
663 desc = name
664 }
665 localize := false
666 if i > 4 {
667 log.Printf("excessive attachment: %s", at)
668 } else if at == "Document" || at == "Image" {
669 mt = strings.ToLower(mt)
670 log.Printf("attachment: %s %s", mt, u)
671 if mt == "text/plain" || strings.HasPrefix(mt, "image") {
672 localize = true
673 }
674 } else {
675 log.Printf("unknown attachment: %s", at)
676 }
677 if skipMedia(&xonk) {
678 localize = false
679 }
680 donk := savedonk(u, name, desc, mt, localize)
681 if donk != nil {
682 xonk.Donks = append(xonk.Donks, donk)
683 }
684 }
685 tags, _ := obj.GetArray("tag")
686 for _, tagi := range tags {
687 tag, ok := tagi.(junk.Junk)
688 if !ok {
689 continue
690 }
691 tt, _ := tag.GetString("type")
692 name, _ := tag.GetString("name")
693 desc, _ := tag.GetString("summary")
694 if desc == "" {
695 desc = name
696 }
697 if tt == "Emoji" {
698 icon, _ := tag.GetMap("icon")
699 mt, _ := icon.GetString("mediaType")
700 if mt == "" {
701 mt = "image/png"
702 }
703 u, _ := icon.GetString("url")
704 donk := savedonk(u, name, desc, mt, true)
705 if donk != nil {
706 xonk.Donks = append(xonk.Donks, donk)
707 }
708 }
709 if tt == "Hashtag" {
710 if len(name) > 1 && name[0] == '#' {
711 xonk.Onts = append(xonk.Onts, name)
712 } else {
713 log.Printf("bogus hashtag name: %s", name)
714 }
715 }
716 if tt == "Place" {
717 p := new(Place)
718 p.Name = name
719 p.Latitude, _ = tag["latitude"].(float64)
720 p.Longitude, _ = tag["longitude"].(float64)
721 p.Url, _ = tag.GetString("url")
722 xonk.Place = p
723 }
724 }
725 xonk.Onts = oneofakind(xonk.Onts)
726 replyobj, ok := obj.GetMap("replies")
727 if ok {
728 items, _ := replyobj.GetArray("items")
729 for _, repl := range items {
730 s, ok := repl.(string)
731 if ok {
732 replies = append(replies, s)
733 }
734 }
735 }
736
737 }
738 if originate(xid) != origin {
739 log.Printf("original sin: %s <> %s", xid, origin)
740 item.Write(os.Stdout)
741 return nil
742 }
743
744 if currenttid == "" {
745 currenttid = convoy
746 }
747
748 // init xonk
749 xonk.What = what
750 xonk.XID = xid
751 xonk.RID = rid
752 xonk.Date, _ = time.Parse(time.RFC3339, dt)
753 xonk.URL = url
754 xonk.Noise = content
755 xonk.Precis = precis
756 xonk.Format = "html"
757
758 if isUpdate {
759 log.Printf("something has changed! %s", xonk.XID)
760 prev := getxonk(user.ID, xonk.XID)
761 if prev == nil {
762 log.Printf("didn't find old version for update: %s", xonk.XID)
763 return nil
764 }
765 prev.Noise = xonk.Noise
766 prev.Precis = xonk.Precis
767 prev.Date = xonk.Date
768 prev.Donks = xonk.Donks
769 prev.Onts = xonk.Onts
770 prev.Place = xonk.Place
771 updatehonk(prev)
772 return nil
773 }
774
775 if needxonk(user, &xonk) {
776 if rid != "" {
777 if needxonkid(user, rid) {
778 saveoneup(rid)
779 }
780 if convoy == "" {
781 xx := getxonk(user.ID, rid)
782 if xx != nil {
783 convoy = xx.Convoy
784 }
785 }
786 }
787 if convoy == "" {
788 convoy = currenttid
789 }
790 xonk.Convoy = convoy
791 for _, replid := range replies {
792 if needxonkid(user, replid) {
793 log.Printf("missing a reply: %s", replid)
794 }
795 }
796 return &xonk
797 }
798 return nil
799 }
800
801 return xonkxonkfn(item, origin)
802}
803
804func rubadubdub(user *WhatAbout, req junk.Junk) {
805 xid, _ := req.GetString("id")
806 actor, _ := req.GetString("actor")
807 j := junk.New()
808 j["@context"] = itiswhatitis
809 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
810 j["type"] = "Accept"
811 j["actor"] = user.URL
812 j["to"] = actor
813 j["published"] = time.Now().UTC().Format(time.RFC3339)
814 j["object"] = req
815
816 var buf bytes.Buffer
817 j.Write(&buf)
818 msg := buf.Bytes()
819
820 deliverate(0, user.Name, actor, msg)
821}
822
823func itakeitallback(user *WhatAbout, xid string) {
824 j := junk.New()
825 j["@context"] = itiswhatitis
826 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
827 j["type"] = "Undo"
828 j["actor"] = user.URL
829 j["to"] = xid
830 f := junk.New()
831 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
832 f["type"] = "Follow"
833 f["actor"] = user.URL
834 f["to"] = xid
835 f["object"] = xid
836 j["object"] = f
837 j["published"] = time.Now().UTC().Format(time.RFC3339)
838
839 var buf bytes.Buffer
840 j.Write(&buf)
841 msg := buf.Bytes()
842
843 deliverate(0, user.Name, xid, msg)
844}
845
846func subsub(user *WhatAbout, xid string) {
847 j := junk.New()
848 j["@context"] = itiswhatitis
849 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
850 j["type"] = "Follow"
851 j["actor"] = user.URL
852 j["to"] = xid
853 j["object"] = xid
854 j["published"] = time.Now().UTC().Format(time.RFC3339)
855
856 var buf bytes.Buffer
857 j.Write(&buf)
858 msg := buf.Bytes()
859
860 deliverate(0, user.Name, xid, msg)
861}
862
863// returns activity, object
864func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
865 dt := h.Date.Format(time.RFC3339)
866 var jo junk.Junk
867 j := junk.New()
868 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
869 j["actor"] = user.URL
870 j["published"] = dt
871 if h.Public {
872 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
873 } else {
874 j["to"] = h.Audience[0]
875 }
876 if len(h.Audience) > 1 {
877 j["cc"] = h.Audience[1:]
878 }
879
880 switch h.What {
881 case "update":
882 fallthrough
883 case "tonk":
884 fallthrough
885 case "honk":
886 if h.What == "update" {
887 j["type"] = "Update"
888 } else {
889 j["type"] = "Create"
890 }
891
892 jo = junk.New()
893 jo["id"] = h.XID
894 jo["type"] = "Note"
895 jo["published"] = dt
896 jo["url"] = h.XID
897 jo["attributedTo"] = user.URL
898 if h.RID != "" {
899 jo["inReplyTo"] = h.RID
900 }
901 if h.Convoy != "" {
902 jo["context"] = h.Convoy
903 jo["conversation"] = h.Convoy
904 }
905 jo["to"] = h.Audience[0]
906 if len(h.Audience) > 1 {
907 jo["cc"] = h.Audience[1:]
908 }
909 if !h.Public {
910 jo["directMessage"] = true
911 }
912 translate(h)
913 h.Noise = re_memes.ReplaceAllString(h.Noise, "")
914 jo["summary"] = h.Precis
915 jo["content"] = ontologize(mentionize(h.Noise))
916 if strings.HasPrefix(h.Precis, "DZ:") {
917 jo["sensitive"] = true
918 }
919
920 var replies []string
921 for _, reply := range h.Replies {
922 replies = append(replies, reply.XID)
923 }
924 if len(replies) > 0 {
925 jr := junk.New()
926 jr["type"] = "Collection"
927 jr["totalItems"] = len(replies)
928 jr["items"] = replies
929 jo["replies"] = jr
930 }
931
932 var tags []junk.Junk
933 g := bunchofgrapes(h.Noise)
934 for _, m := range g {
935 t := junk.New()
936 t["type"] = "Mention"
937 t["name"] = m.who
938 t["href"] = m.where
939 tags = append(tags, t)
940 }
941 for _, o := range h.Onts {
942 t := junk.New()
943 t["type"] = "Hashtag"
944 o = strings.ToLower(o)
945 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
946 t["name"] = o
947 tags = append(tags, t)
948 }
949 herd := herdofemus(h.Noise)
950 for _, e := range herd {
951 t := junk.New()
952 t["id"] = e.ID
953 t["type"] = "Emoji"
954 t["name"] = e.Name
955 i := junk.New()
956 i["type"] = "Image"
957 i["mediaType"] = "image/png"
958 i["url"] = e.ID
959 t["icon"] = i
960 tags = append(tags, t)
961 }
962 if p := h.Place; p != nil {
963 t := junk.New()
964 t["type"] = "Place"
965 t["name"] = p.Name
966 t["latitude"] = p.Latitude
967 t["longitude"] = p.Longitude
968 t["url"] = p.Url
969 tags = append(tags, t)
970 }
971 if len(tags) > 0 {
972 jo["tag"] = tags
973 }
974 var atts []junk.Junk
975 for _, d := range h.Donks {
976 if re_emus.MatchString(d.Name) {
977 continue
978 }
979 jd := junk.New()
980 jd["mediaType"] = d.Media
981 jd["name"] = d.Name
982 jd["summary"] = d.Desc
983 jd["type"] = "Document"
984 jd["url"] = d.URL
985 atts = append(atts, jd)
986 }
987 if len(atts) > 0 {
988 jo["attachment"] = atts
989 }
990 j["object"] = jo
991 case "bonk":
992 j["type"] = "Announce"
993 if h.Convoy != "" {
994 j["context"] = h.Convoy
995 }
996 j["object"] = h.XID
997 case "unbonk":
998 b := junk.New()
999 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1000 b["type"] = "Announce"
1001 b["actor"] = user.URL
1002 if h.Convoy != "" {
1003 b["context"] = h.Convoy
1004 }
1005 b["object"] = h.XID
1006 j["type"] = "Undo"
1007 j["object"] = b
1008 case "zonk":
1009 j["type"] = "Delete"
1010 j["object"] = h.XID
1011 case "ack":
1012 j["type"] = "Read"
1013 j["object"] = h.XID
1014 case "deack":
1015 b := junk.New()
1016 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1017 b["type"] = "Read"
1018 b["actor"] = user.URL
1019 b["object"] = h.XID
1020 j["type"] = "Undo"
1021 j["object"] = b
1022 }
1023
1024 return j, jo
1025}
1026
1027func honkworldwide(user *WhatAbout, honk *Honk) {
1028 jonk, _ := jonkjonk(user, honk)
1029 jonk["@context"] = itiswhatitis
1030 var buf bytes.Buffer
1031 jonk.Write(&buf)
1032 msg := buf.Bytes()
1033
1034 rcpts := make(map[string]bool)
1035 for _, a := range honk.Audience {
1036 if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1037 continue
1038 }
1039 box, _ := getboxes(a)
1040 if box != nil && honk.Public && box.Shared != "" {
1041 rcpts["%"+box.Shared] = true
1042 } else {
1043 rcpts[a] = true
1044 }
1045 }
1046 if honk.Public {
1047 for _, f := range getdubs(user.ID) {
1048 if f.XID == user.URL {
1049 continue
1050 }
1051 box, _ := getboxes(f.XID)
1052 if box != nil && box.Shared != "" {
1053 rcpts["%"+box.Shared] = true
1054 } else {
1055 rcpts[f.XID] = true
1056 }
1057 }
1058 }
1059 for a := range rcpts {
1060 go deliverate(0, user.Name, a, msg)
1061 }
1062}
1063
1064func asjonker(user *WhatAbout) junk.Junk {
1065 about := obfusbreak(user.About)
1066
1067 j := junk.New()
1068 j["@context"] = itiswhatitis
1069 j["id"] = user.URL
1070 j["type"] = "Person"
1071 j["inbox"] = user.URL + "/inbox"
1072 j["outbox"] = user.URL + "/outbox"
1073 j["followers"] = user.URL + "/followers"
1074 j["following"] = user.URL + "/following"
1075 j["name"] = user.Display
1076 j["preferredUsername"] = user.Name
1077 j["summary"] = about
1078 j["url"] = user.URL
1079 a := junk.New()
1080 a["type"] = "Image"
1081 a["mediaType"] = "image/png"
1082 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1083 j["icon"] = a
1084 k := junk.New()
1085 k["id"] = user.URL + "#key"
1086 k["owner"] = user.URL
1087 k["publicKeyPem"] = user.Key
1088 j["publicKey"] = k
1089
1090 return j
1091}
1092
1093var handfull = make(map[string]string)
1094var handlock sync.Mutex
1095
1096func gofish(name string) string {
1097 if name[0] == '@' {
1098 name = name[1:]
1099 }
1100 m := strings.Split(name, "@")
1101 if len(m) != 2 {
1102 log.Printf("bad fish name: %s", name)
1103 return ""
1104 }
1105 handlock.Lock()
1106 ref, ok := handfull[name]
1107 handlock.Unlock()
1108 if ok {
1109 return ref
1110 }
1111 row := stmtGetXonker.QueryRow(name, "fishname")
1112 var href string
1113 err := row.Scan(&href)
1114 if err == nil {
1115 handlock.Lock()
1116 handfull[name] = href
1117 handlock.Unlock()
1118 return href
1119 }
1120 log.Printf("fishing for %s", name)
1121 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1122 if err != nil {
1123 log.Printf("failed to go fish %s: %s", name, err)
1124 handlock.Lock()
1125 handfull[name] = ""
1126 handlock.Unlock()
1127 return ""
1128 }
1129 links, _ := j.GetArray("links")
1130 for _, li := range links {
1131 l, ok := li.(junk.Junk)
1132 if !ok {
1133 continue
1134 }
1135 href, _ := l.GetString("href")
1136 rel, _ := l.GetString("rel")
1137 t, _ := l.GetString("type")
1138 if rel == "self" && friendorfoe(t) {
1139 _, err := stmtSaveXonker.Exec(name, href, "fishname")
1140 if err != nil {
1141 log.Printf("error saving fishname: %s", err)
1142 }
1143 handlock.Lock()
1144 handfull[name] = href
1145 handlock.Unlock()
1146 return href
1147 }
1148 }
1149 handlock.Lock()
1150 handfull[name] = ""
1151 handlock.Unlock()
1152 return ""
1153}
1154
1155func isactor(t string) bool {
1156 switch t {
1157 case "Person":
1158 case "Organization":
1159 case "Application":
1160 case "Service":
1161 default:
1162 return false
1163 }
1164 return true
1165}
1166
1167func investigate(name string) (*Honker, error) {
1168 if name == "" {
1169 return nil, fmt.Errorf("no name")
1170 }
1171 if name[0] == '@' {
1172 name = gofish(name)
1173 }
1174 if name == "" {
1175 return nil, fmt.Errorf("no name")
1176 }
1177 log.Printf("digging up some info on %s", name)
1178 obj, err := GetJunkFast(name)
1179 if err != nil {
1180 log.Printf("error investigating honker: %s", err)
1181 return nil, err
1182 }
1183 t, _ := obj.GetString("type")
1184 if !isactor(t) {
1185 log.Printf("it's not a person! %s", name)
1186 return nil, err
1187 }
1188 xid, _ := obj.GetString("id")
1189 handle, _ := obj.GetString("preferredUsername")
1190 return &Honker{XID: xid, Handle: handle}, nil
1191}