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