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