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 media = "image/" + img.Format
169 } else if len(data) > 100000 {
170 log.Printf("not saving large attachment")
171 localize = false
172 data = []byte{}
173 }
174 }
175saveit:
176 res, err := stmtSaveFile.Exec(xid, name, desc, url, media, localize, data)
177 if err != nil {
178 log.Printf("error saving file %s: %s", url, err)
179 return nil
180 }
181 donk.FileID, _ = res.LastInsertId()
182 return &donk
183}
184
185func iszonked(userid int64, xid string) bool {
186 row := stmtFindZonk.QueryRow(userid, xid)
187 var id int64
188 err := row.Scan(&id)
189 if err == nil {
190 return true
191 }
192 if err != sql.ErrNoRows {
193 log.Printf("err querying zonk: %s", err)
194 }
195 return false
196}
197
198func needxonk(user *WhatAbout, x *Honk) bool {
199 if x.What == "eradicate" {
200 return true
201 }
202 if thoudostbitethythumb(user.ID, x.Audience, x.XID) {
203 log.Printf("not saving thumb biter? %s via %s", x.XID, x.Honker)
204 return false
205 }
206 return needxonkid(user, x.XID)
207}
208func needxonkid(user *WhatAbout, xid string) bool {
209 if strings.HasPrefix(xid, user.URL+"/") {
210 return false
211 }
212 if thoudostbitethythumb(user.ID, nil, xid) {
213 log.Printf("don't need thumb biter? %s", xid)
214 return false
215 }
216 if iszonked(user.ID, xid) {
217 log.Printf("already zonked: %s", xid)
218 return false
219 }
220 row := stmtFindXonk.QueryRow(user.ID, xid)
221 var id int64
222 err := row.Scan(&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.XID, x.Honker)
235 xonk := getxonk(x.UserID, x.XID)
236 if xonk != nil {
237 _, err := stmtZonkDonks.Exec(xonk.ID)
238 if err != nil {
239 log.Printf("error eradicating: %s", err)
240 }
241 _, err = stmtZonkIt.Exec(xonk.ID)
242 if err != nil {
243 log.Printf("error eradicating: %s", err)
244 }
245 }
246 _, err := stmtSaveZonker.Exec(x.UserID, x.XID, "zonk")
247 if err != nil {
248 log.Printf("error eradicating: %s", err)
249 }
250 return
251 }
252 log.Printf("saving xonk: %s", x.XID)
253 go prehandle(x.Honker)
254 go prehandle(x.Oonker)
255 savehonk(x)
256}
257
258type Box struct {
259 In string
260 Out string
261 Shared string
262}
263
264var boxofboxes = make(map[string]*Box)
265var boxlock sync.Mutex
266var boxinglock sync.Mutex
267
268func getboxes(ident string) (*Box, error) {
269 boxlock.Lock()
270 b, ok := boxofboxes[ident]
271 boxlock.Unlock()
272 if ok {
273 return b, nil
274 }
275
276 boxinglock.Lock()
277 defer boxinglock.Unlock()
278
279 boxlock.Lock()
280 b, ok = boxofboxes[ident]
281 boxlock.Unlock()
282 if ok {
283 return b, nil
284 }
285
286 var info string
287 row := stmtGetXonker.QueryRow(ident, "boxes")
288 err := row.Scan(&info)
289 if err != nil {
290 j, err := GetJunk(ident)
291 if err != nil {
292 return nil, err
293 }
294 inbox, _ := j.GetString("inbox")
295 outbox, _ := j.GetString("outbox")
296 sbox, _ := j.FindString([]string{"endpoints", "sharedInbox"})
297 b = &Box{In: inbox, Out: outbox, Shared: sbox}
298 if inbox != "" {
299 m := strings.Join([]string{inbox, outbox, sbox}, " ")
300 _, err = stmtSaveXonker.Exec(ident, m, "boxes")
301 if err != nil {
302 log.Printf("error saving boxes: %s", err)
303 }
304 }
305 } else {
306 m := strings.Split(info, " ")
307 b = &Box{In: m[0], Out: m[1], Shared: m[2]}
308 }
309
310 boxlock.Lock()
311 boxofboxes[ident] = b
312 boxlock.Unlock()
313 return b, nil
314}
315
316func gimmexonks(user *WhatAbout, outbox string) {
317 log.Printf("getting outbox: %s", outbox)
318 j, err := GetJunk(outbox)
319 if err != nil {
320 log.Printf("error getting outbox: %s", err)
321 return
322 }
323 t, _ := j.GetString("type")
324 origin := originate(outbox)
325 if t == "OrderedCollection" {
326 items, _ := j.GetArray("orderedItems")
327 if items == nil {
328 obj, ok := j.GetMap("first")
329 if ok {
330 items, _ = obj.GetArray("orderedItems")
331 } else {
332 page1, _ := j.GetString("first")
333 j, err = GetJunk(page1)
334 if err != nil {
335 log.Printf("error gettings page1: %s", err)
336 return
337 }
338 items, _ = j.GetArray("orderedItems")
339 }
340 }
341 if len(items) > 20 {
342 items = items[0:20]
343 }
344 for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
345 items[i], items[j] = items[j], items[i]
346 }
347 for _, item := range items {
348 obj, ok := item.(junk.Junk)
349 if !ok {
350 continue
351 }
352 xonk := xonkxonk(user, obj, origin)
353 if xonk != nil {
354 savexonk(xonk)
355 }
356 }
357 }
358}
359
360func peeppeep() {
361 user, _ := butwhatabout("htest")
362 honkers := gethonkers(user.ID)
363 for _, f := range honkers {
364 if f.Flavor != "peep" {
365 continue
366 }
367 log.Printf("getting updates: %s", f.XID)
368 box, err := getboxes(f.XID)
369 if err != nil {
370 log.Printf("error getting outbox: %s", err)
371 continue
372 }
373 gimmexonks(user, box.Out)
374 }
375}
376func whosthere(xid string) ([]string, string) {
377 obj, err := GetJunk(xid)
378 if err != nil {
379 log.Printf("error getting remote xonk: %s", err)
380 return nil, ""
381 }
382 convoy, _ := obj.GetString("context")
383 if convoy == "" {
384 convoy, _ = obj.GetString("conversation")
385 }
386 return newphone(nil, obj), convoy
387}
388
389func newphone(a []string, obj junk.Junk) []string {
390 for _, addr := range []string{"to", "cc", "attributedTo"} {
391 who, _ := obj.GetString(addr)
392 if who != "" {
393 a = append(a, who)
394 }
395 whos, _ := obj.GetArray(addr)
396 for _, w := range whos {
397 who, _ := w.(string)
398 if who != "" {
399 a = append(a, who)
400 }
401 }
402 }
403 return a
404}
405
406func extractattrto(obj junk.Junk) string {
407 who, _ := obj.GetString("attributedTo")
408 if who != "" {
409 return who
410 }
411 o, ok := obj.GetMap("attributedTo")
412 if ok {
413 id, ok := o.GetString("id")
414 if ok {
415 return id
416 }
417 }
418 arr, _ := obj.GetArray("attributedTo")
419 for _, a := range arr {
420 o, ok := a.(junk.Junk)
421 if ok {
422 t, _ := o.GetString("type")
423 id, _ := o.GetString("id")
424 if t == "Person" || t == "" {
425 return id
426 }
427 }
428 }
429 return ""
430}
431
432func consumeactivity(user *WhatAbout, j junk.Junk, origin string) {
433 xonk := xonkxonk(user, j, origin)
434 if xonk != nil {
435 savexonk(xonk)
436 }
437}
438
439func xonkxonk(user *WhatAbout, item junk.Junk, origin string) *Honk {
440 depth := 0
441 maxdepth := 10
442 currenttid := ""
443 var xonkxonkfn func(item junk.Junk, origin string) *Honk
444
445 saveoneup := func(xid string) {
446 log.Printf("getting oneup: %s", xid)
447 if depth >= maxdepth {
448 log.Printf("in too deep")
449 return
450 }
451 obj, err := GetJunkHardMode(xid)
452 if err != nil {
453 log.Printf("error getting oneup: %s: %s", xid, err)
454 return
455 }
456 depth++
457 xonk := xonkxonkfn(obj, originate(xid))
458 if xonk != nil {
459 savexonk(xonk)
460 }
461 depth--
462 }
463
464 xonkxonkfn = func(item junk.Junk, origin string) *Honk {
465 // id, _ := item.GetString( "id")
466 what, _ := item.GetString("type")
467 dt, _ := item.GetString("published")
468
469 var audience []string
470 var err error
471 var xid, rid, url, content, precis, convoy, oonker string
472 var obj junk.Junk
473 var ok bool
474 switch what {
475 case "Announce":
476 obj, ok = item.GetMap("object")
477 if ok {
478 xid, _ = obj.GetString("id")
479 } else {
480 xid, _ = item.GetString("object")
481 }
482 if !needxonkid(user, xid) {
483 return nil
484 }
485 log.Printf("getting bonk: %s", xid)
486 obj, err = GetJunkHardMode(xid)
487 if err != nil {
488 log.Printf("error getting bonk: %s: %s", xid, err)
489 }
490 origin = originate(xid)
491 what = "bonk"
492 case "Create":
493 obj, ok = item.GetMap("object")
494 if !ok {
495 xid, _ = obj.GetString("object")
496 log.Printf("getting created honk: %s", xid)
497 obj, err = GetJunkHardMode(xid)
498 if err != nil {
499 log.Printf("error getting creation: %s", err)
500 }
501 }
502 what = "honk"
503 case "Delete":
504 obj, _ = item.GetMap("object")
505 xid, _ = item.GetString("object")
506 what = "eradicate"
507 case "Read":
508 xid, ok = item.GetString("object")
509 if ok {
510 if !needxonkid(user, xid) {
511 log.Printf("don't need read obj: %s", xid)
512 return nil
513 }
514 obj, err = GetJunkHardMode(xid)
515 if err != nil {
516 log.Printf("error getting read: %s", err)
517 return nil
518 }
519 return xonkxonkfn(obj, originate(xid))
520 }
521 return nil
522 case "Video":
523 fallthrough
524 case "Question":
525 fallthrough
526 case "Note":
527 fallthrough
528 case "Article":
529 fallthrough
530 case "Page":
531 obj = item
532 what = "honk"
533 default:
534 log.Printf("unknown activity: %s", what)
535 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
536 item.Write(fd)
537 io.WriteString(fd, "\n")
538 fd.Close()
539 return nil
540 }
541
542 var xonk Honk
543 who, _ := item.GetString("actor")
544 if obj != nil {
545 if who == "" {
546 who = extractattrto(obj)
547 }
548 oonker = extractattrto(obj)
549 ot, _ := obj.GetString("type")
550 url, _ = obj.GetString("url")
551 if ot == "Tombstone" {
552 xid, _ = obj.GetString("id")
553 } else {
554 audience = newphone(audience, obj)
555 xid, _ = obj.GetString("id")
556 precis, _ = obj.GetString("summary")
557 if precis == "" {
558 precis, _ = obj.GetString("name")
559 }
560 content, _ = obj.GetString("content")
561 if !strings.HasPrefix(content, "<p>") {
562 content = "<p>" + content
563 }
564 sens, _ := obj["sensitive"].(bool)
565 if sens && precis == "" {
566 precis = "unspecified horror"
567 }
568 rid, ok = obj.GetString("inReplyTo")
569 if !ok {
570 robj, ok := obj.GetMap("inReplyTo")
571 if ok {
572 rid, _ = robj.GetString("id")
573 }
574 }
575 convoy, _ = obj.GetString("context")
576 if convoy == "" {
577 convoy, _ = obj.GetString("conversation")
578 }
579 if ot == "Question" {
580 if what == "honk" {
581 what = "qonk"
582 }
583 content += "<ul>"
584 ans, _ := obj.GetArray("oneOf")
585 for _, ai := range ans {
586 a, ok := ai.(junk.Junk)
587 if !ok {
588 continue
589 }
590 as, _ := a.GetString("name")
591 content += "<li>" + as
592 }
593 ans, _ = obj.GetArray("anyOf")
594 for _, ai := range ans {
595 a, ok := ai.(junk.Junk)
596 if !ok {
597 continue
598 }
599 as, _ := a.GetString("name")
600 content += "<li>" + as
601 }
602 content += "</ul>"
603 }
604 if what == "honk" && rid != "" {
605 what = "tonk"
606 }
607 }
608 atts, _ := obj.GetArray("attachment")
609 for i, atti := range atts {
610 att, ok := atti.(junk.Junk)
611 if !ok {
612 continue
613 }
614 at, _ := att.GetString("type")
615 mt, _ := att.GetString("mediaType")
616 u, _ := att.GetString("url")
617 name, _ := att.GetString("name")
618 desc, _ := att.GetString("summary")
619 log.Printf("att: %s %s %s", name, desc, u)
620 if desc == "" {
621 desc = name
622 }
623 localize := false
624 if i > 4 {
625 log.Printf("excessive attachment: %s", at)
626 } else if at == "Document" || at == "Image" {
627 mt = strings.ToLower(mt)
628 log.Printf("attachment: %s %s", mt, u)
629 if mt == "text/plain" || strings.HasPrefix(mt, "image") {
630 localize = true
631 }
632 } else {
633 log.Printf("unknown attachment: %s", at)
634 }
635 log.Printf("saving a donk: %s is %s", name, desc)
636 donk := savedonk(u, name, desc, mt, localize)
637 if donk != nil {
638 xonk.Donks = append(xonk.Donks, donk)
639 }
640 }
641 tags, _ := obj.GetArray("tag")
642 for _, tagi := range tags {
643 tag, ok := tagi.(junk.Junk)
644 if !ok {
645 continue
646 }
647 tt, _ := tag.GetString("type")
648 name, _ := tag.GetString("name")
649 desc, _ := tag.GetString("summary")
650 if desc == "" {
651 desc = name
652 }
653 if tt == "Emoji" {
654 icon, _ := tag.GetMap("icon")
655 mt, _ := icon.GetString("mediaType")
656 if mt == "" {
657 mt = "image/png"
658 }
659 u, _ := icon.GetString("url")
660 donk := savedonk(u, name, desc, mt, true)
661 if donk != nil {
662 xonk.Donks = append(xonk.Donks, donk)
663 }
664 }
665 if tt == "Hashtag" {
666 xonk.Onts = append(xonk.Onts, name)
667 }
668 }
669 xonk.Onts = oneofakind(xonk.Onts)
670 }
671 if originate(xid) != origin {
672 log.Printf("original sin: %s <> %s", xid, origin)
673 item.Write(os.Stdout)
674 return nil
675 }
676 audience = append(audience, who)
677
678 audience = oneofakind(audience)
679
680 if currenttid == "" {
681 currenttid = convoy
682 }
683
684 if oonker == who {
685 oonker = ""
686 }
687 // init xonk
688 xonk.UserID = user.ID
689 xonk.What = what
690 xonk.Honker = who
691 xonk.XID = xid
692 xonk.RID = rid
693 xonk.Date, _ = time.Parse(time.RFC3339, dt)
694 xonk.URL = url
695 xonk.Noise = content
696 xonk.Precis = precis
697 xonk.Audience = audience
698 xonk.Oonker = oonker
699 xonk.Format = "html"
700 for _, a := range audience {
701 if a == user.URL {
702 xonk.Whofore = 1
703 }
704 }
705
706 if needxonk(user, &xonk) {
707 if rid != "" {
708 if needxonkid(user, rid) {
709 saveoneup(rid)
710 }
711 }
712 if convoy == "" {
713 convoy = currenttid
714 }
715 xonk.Convoy = convoy
716 return &xonk
717 }
718 return nil
719 }
720
721 return xonkxonkfn(item, origin)
722}
723
724func rubadubdub(user *WhatAbout, req junk.Junk) {
725 xid, _ := req.GetString("id")
726 actor, _ := req.GetString("actor")
727 j := junk.New()
728 j["@context"] = itiswhatitis
729 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
730 j["type"] = "Accept"
731 j["actor"] = user.URL
732 j["to"] = actor
733 j["published"] = time.Now().UTC().Format(time.RFC3339)
734 j["object"] = req
735
736 var buf bytes.Buffer
737 j.Write(&buf)
738 msg := buf.Bytes()
739
740 deliverate(0, user.Name, actor, msg)
741}
742
743func itakeitallback(user *WhatAbout, xid string) {
744 j := junk.New()
745 j["@context"] = itiswhatitis
746 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
747 j["type"] = "Undo"
748 j["actor"] = user.URL
749 j["to"] = xid
750 f := junk.New()
751 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
752 f["type"] = "Follow"
753 f["actor"] = user.URL
754 f["to"] = xid
755 f["object"] = xid
756 j["object"] = f
757 j["published"] = time.Now().UTC().Format(time.RFC3339)
758
759 var buf bytes.Buffer
760 j.Write(&buf)
761 msg := buf.Bytes()
762
763 deliverate(0, user.Name, xid, msg)
764}
765
766func subsub(user *WhatAbout, xid string) {
767 j := junk.New()
768 j["@context"] = itiswhatitis
769 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
770 j["type"] = "Follow"
771 j["actor"] = user.URL
772 j["to"] = xid
773 j["object"] = xid
774 j["published"] = time.Now().UTC().Format(time.RFC3339)
775
776 var buf bytes.Buffer
777 j.Write(&buf)
778 msg := buf.Bytes()
779
780 deliverate(0, user.Name, xid, msg)
781}
782
783func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
784 dt := h.Date.Format(time.RFC3339)
785 var jo junk.Junk
786 j := junk.New()
787 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
788 j["actor"] = user.URL
789 j["published"] = dt
790 if h.Public {
791 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
792 } else {
793 j["to"] = h.Audience[0]
794 }
795 if len(h.Audience) > 1 {
796 j["cc"] = h.Audience[1:]
797 }
798
799 switch h.What {
800 case "tonk":
801 fallthrough
802 case "honk":
803 j["type"] = "Create"
804
805 jo = junk.New()
806 jo["id"] = h.XID
807 jo["type"] = "Note"
808 jo["published"] = dt
809 jo["url"] = h.XID
810 jo["attributedTo"] = user.URL
811 if h.RID != "" {
812 jo["inReplyTo"] = h.RID
813 }
814 if h.Convoy != "" {
815 jo["context"] = h.Convoy
816 jo["conversation"] = h.Convoy
817 }
818 jo["to"] = h.Audience[0]
819 if len(h.Audience) > 1 {
820 jo["cc"] = h.Audience[1:]
821 }
822 if !h.Public {
823 jo["directMessage"] = true
824 }
825 jo["summary"] = h.Precis
826 jo["content"] = ontologize(mentionize(h.Noise))
827 if strings.HasPrefix(h.Precis, "DZ:") {
828 jo["sensitive"] = true
829 }
830
831 var replies []string
832 for _, reply := range h.Replies {
833 replies = append(replies, reply.XID)
834 }
835 if len(replies) > 0 {
836 jr := junk.New()
837 jr["type"] = "Collection"
838 jr["totalItems"] = len(replies)
839 jr["items"] = replies
840 jo["replies"] = jr
841 }
842
843 var tags []junk.Junk
844 g := bunchofgrapes(h.Noise)
845 for _, m := range g {
846 t := junk.New()
847 t["type"] = "Mention"
848 t["name"] = m.who
849 t["href"] = m.where
850 tags = append(tags, t)
851 }
852 for _, o := range h.Onts {
853 t := junk.New()
854 t["type"] = "Hashtag"
855 o = strings.ToLower(o)
856 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
857 t["name"] = o
858 tags = append(tags, t)
859 }
860 herd := herdofemus(h.Noise)
861 for _, e := range herd {
862 t := junk.New()
863 t["id"] = e.ID
864 t["type"] = "Emoji"
865 t["name"] = e.Name
866 i := junk.New()
867 i["type"] = "Image"
868 i["mediaType"] = "image/png"
869 i["url"] = e.ID
870 t["icon"] = i
871 tags = append(tags, t)
872 }
873 if len(tags) > 0 {
874 jo["tag"] = tags
875 }
876 var atts []junk.Junk
877 for _, d := range h.Donks {
878 if re_emus.MatchString(d.Name) {
879 continue
880 }
881 jd := junk.New()
882 jd["mediaType"] = d.Media
883 jd["name"] = d.Name
884 jd["summary"] = d.Desc
885 jd["type"] = "Document"
886 jd["url"] = d.URL
887 atts = append(atts, jd)
888 }
889 if len(atts) > 0 {
890 jo["attachment"] = atts
891 }
892 j["object"] = jo
893 case "bonk":
894 j["type"] = "Announce"
895 if h.Convoy != "" {
896 j["context"] = h.Convoy
897 }
898 j["object"] = h.XID
899 case "unbonk":
900 b := junk.New()
901 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
902 b["type"] = "Announce"
903 if h.Convoy != "" {
904 b["context"] = h.Convoy
905 }
906 b["object"] = h.XID
907 j["type"] = "Undo"
908 j["object"] = b
909 case "zonk":
910 j["type"] = "Delete"
911 j["object"] = h.XID
912 case "ack":
913 j["type"] = "Read"
914 j["object"] = h.XID
915 case "deack":
916 j["type"] = "Ignore"
917 j["object"] = h.XID
918 }
919
920 return j, jo
921}
922
923func honkworldwide(user *WhatAbout, honk *Honk) {
924 jonk, _ := jonkjonk(user, honk)
925 jonk["@context"] = itiswhatitis
926 var buf bytes.Buffer
927 jonk.Write(&buf)
928 msg := buf.Bytes()
929
930 rcpts := make(map[string]bool)
931 for _, a := range honk.Audience {
932 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
933 box, _ := getboxes(a)
934 if box != nil && honk.Public && box.Shared != "" {
935 rcpts["%"+box.Shared] = true
936 } else {
937 rcpts[a] = true
938 }
939 }
940 }
941 if honk.Public {
942 for _, f := range getdubs(user.ID) {
943 box, _ := getboxes(f.XID)
944 if box != nil && box.Shared != "" {
945 rcpts["%"+box.Shared] = true
946 } else {
947 rcpts[f.XID] = true
948 }
949 }
950 }
951 for a := range rcpts {
952 go deliverate(0, user.Name, a, msg)
953 }
954}
955
956func asjonker(user *WhatAbout) junk.Junk {
957 about := obfusbreak(user.About)
958
959 j := junk.New()
960 j["@context"] = itiswhatitis
961 j["id"] = user.URL
962 j["type"] = "Person"
963 j["inbox"] = user.URL + "/inbox"
964 j["outbox"] = user.URL + "/outbox"
965 j["followers"] = user.URL + "/followers"
966 j["following"] = user.URL + "/following"
967 j["name"] = user.Display
968 j["preferredUsername"] = user.Name
969 j["summary"] = about
970 j["url"] = user.URL
971 a := junk.New()
972 a["type"] = "Image"
973 a["mediaType"] = "image/png"
974 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
975 j["icon"] = a
976 k := junk.New()
977 k["id"] = user.URL + "#key"
978 k["owner"] = user.URL
979 k["publicKeyPem"] = user.Key
980 j["publicKey"] = k
981
982 return j
983}
984
985var handfull = make(map[string]string)
986var handlock sync.Mutex
987
988func gofish(name string) string {
989 if name[0] == '@' {
990 name = name[1:]
991 }
992 m := strings.Split(name, "@")
993 if len(m) != 2 {
994 log.Printf("bad fish name: %s", name)
995 return ""
996 }
997 handlock.Lock()
998 ref, ok := handfull[name]
999 handlock.Unlock()
1000 if ok {
1001 return ref
1002 }
1003 row := stmtGetXonker.QueryRow(name, "fishname")
1004 var href string
1005 err := row.Scan(&href)
1006 if err == nil {
1007 handlock.Lock()
1008 handfull[name] = href
1009 handlock.Unlock()
1010 return href
1011 }
1012 log.Printf("fishing for %s", name)
1013 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1014 if err != nil {
1015 log.Printf("failed to go fish %s: %s", name, err)
1016 handlock.Lock()
1017 handfull[name] = ""
1018 handlock.Unlock()
1019 return ""
1020 }
1021 links, _ := j.GetArray("links")
1022 for _, li := range links {
1023 l, ok := li.(junk.Junk)
1024 if !ok {
1025 continue
1026 }
1027 href, _ := l.GetString("href")
1028 rel, _ := l.GetString("rel")
1029 t, _ := l.GetString("type")
1030 if rel == "self" && friendorfoe(t) {
1031 _, err := stmtSaveXonker.Exec(name, href, "fishname")
1032 if err != nil {
1033 log.Printf("error saving fishname: %s", err)
1034 }
1035 handlock.Lock()
1036 handfull[name] = href
1037 handlock.Unlock()
1038 return href
1039 }
1040 }
1041 handlock.Lock()
1042 handfull[name] = ""
1043 handlock.Unlock()
1044 return ""
1045}
1046
1047func isactor(t string) bool {
1048 switch t {
1049 case "Person":
1050 case "Organization":
1051 case "Application":
1052 case "Service":
1053 default:
1054 return false
1055 }
1056 return true
1057}
1058
1059func investigate(name string) (*Honker, error) {
1060 if name == "" {
1061 return nil, fmt.Errorf("no name")
1062 }
1063 if name[0] == '@' {
1064 name = gofish(name)
1065 }
1066 if name == "" {
1067 return nil, fmt.Errorf("no name")
1068 }
1069 log.Printf("digging up some info on %s", name)
1070 obj, err := GetJunkFast(name)
1071 if err != nil {
1072 log.Printf("error investigating honker: %s", err)
1073 return nil, err
1074 }
1075 t, _ := obj.GetString("type")
1076 if !isactor(t) {
1077 log.Printf("it's not a person! %s", name)
1078 return nil, err
1079 }
1080 xid, _ := obj.GetString("id")
1081 handle, _ := obj.GetString("preferredUsername")
1082 return &Honker{XID: xid, Handle: handle}, nil
1083}