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 xonksaver(user, obj, origin)
347 }
348 }
349}
350
351func peeppeep() {
352 user, _ := butwhatabout("htest")
353 honkers := gethonkers(user.ID)
354 for _, f := range honkers {
355 if f.Flavor != "peep" {
356 continue
357 }
358 log.Printf("getting updates: %s", f.XID)
359 box, err := getboxes(f.XID)
360 if err != nil {
361 log.Printf("error getting outbox: %s", err)
362 continue
363 }
364 gimmexonks(user, box.Out)
365 }
366}
367func whosthere(xid string) ([]string, string) {
368 obj, err := GetJunk(xid)
369 if err != nil {
370 log.Printf("error getting remote xonk: %s", err)
371 return nil, ""
372 }
373 convoy, _ := obj.GetString("context")
374 if convoy == "" {
375 convoy, _ = obj.GetString("conversation")
376 }
377 return newphone(nil, obj), convoy
378}
379
380func newphone(a []string, obj junk.Junk) []string {
381 for _, addr := range []string{"to", "cc", "attributedTo"} {
382 who, _ := obj.GetString(addr)
383 if who != "" {
384 a = append(a, who)
385 }
386 whos, _ := obj.GetArray(addr)
387 for _, w := range whos {
388 who, _ := w.(string)
389 if who != "" {
390 a = append(a, who)
391 }
392 }
393 }
394 return a
395}
396
397func extractattrto(obj junk.Junk) string {
398 who, _ := obj.GetString("attributedTo")
399 if who != "" {
400 return who
401 }
402 o, ok := obj.GetMap("attributedTo")
403 if ok {
404 id, ok := o.GetString("id")
405 if ok {
406 return id
407 }
408 }
409 arr, _ := obj.GetArray("attributedTo")
410 for _, a := range arr {
411 o, ok := a.(junk.Junk)
412 if ok {
413 t, _ := o.GetString("type")
414 id, _ := o.GetString("id")
415 if t == "Person" || t == "" {
416 return id
417 }
418 }
419 }
420 return ""
421}
422
423func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
424 depth := 0
425 maxdepth := 10
426 currenttid := ""
427 var xonkxonkfn func(item junk.Junk, origin string) *Honk
428
429 saveonemore := func(xid string) {
430 log.Printf("getting onemore: %s", xid)
431 if depth >= maxdepth {
432 log.Printf("in too deep")
433 return
434 }
435 obj, err := GetJunkHardMode(xid)
436 if err != nil {
437 log.Printf("error getting onemore: %s: %s", xid, err)
438 return
439 }
440 depth++
441 xonkxonkfn(obj, originate(xid))
442 depth--
443 }
444
445 xonkxonkfn = func(item junk.Junk, origin string) *Honk {
446 // id, _ := item.GetString( "id")
447 what, _ := item.GetString("type")
448 dt, _ := item.GetString("published")
449
450 var err error
451 var xid, rid, url, content, precis, convoy string
452 var replies []string
453 var obj junk.Junk
454 var ok bool
455 isUpdate := false
456 switch what {
457 case "Delete":
458 obj, ok = item.GetMap("object")
459 if ok {
460 xid, _ = obj.GetString("id")
461 } else {
462 xid, _ = item.GetString("object")
463 }
464 if xid == "" {
465 return nil
466 }
467 if originate(xid) != origin {
468 log.Printf("forged delete: %s", xid)
469 return nil
470 }
471 log.Printf("eradicating %s", xid)
472 eradicatexonk(user.ID, xid)
473 return nil
474 case "Tombstone":
475 xid, _ = item.GetString("id")
476 if xid == "" {
477 return nil
478 }
479 if originate(xid) != origin {
480 log.Printf("forged delete: %s", xid)
481 return nil
482 }
483 log.Printf("eradicating %s", xid)
484 eradicatexonk(user.ID, xid)
485 return nil
486 case "Announce":
487 obj, ok = item.GetMap("object")
488 if ok {
489 xid, _ = obj.GetString("id")
490 } else {
491 xid, _ = item.GetString("object")
492 }
493 if !needxonkid(user, xid) {
494 return nil
495 }
496 log.Printf("getting bonk: %s", xid)
497 obj, err = GetJunkHardMode(xid)
498 if err != nil {
499 log.Printf("error getting bonk: %s: %s", xid, err)
500 }
501 origin = originate(xid)
502 what = "bonk"
503 case "Update":
504 isUpdate = true
505 fallthrough
506 case "Create":
507 obj, ok = item.GetMap("object")
508 if !ok {
509 xid, _ = item.GetString("object")
510 log.Printf("getting created honk: %s", xid)
511 obj, err = GetJunkHardMode(xid)
512 if err != nil {
513 log.Printf("error getting creation: %s", err)
514 }
515 }
516 what = "honk"
517 case "Read":
518 xid, ok = item.GetString("object")
519 if ok {
520 if !needxonkid(user, xid) {
521 log.Printf("don't need read obj: %s", xid)
522 return nil
523 }
524 obj, err = GetJunkHardMode(xid)
525 if err != nil {
526 log.Printf("error getting read: %s", err)
527 return nil
528 }
529 return xonkxonkfn(obj, originate(xid))
530 }
531 return nil
532 case "Video":
533 fallthrough
534 case "Question":
535 fallthrough
536 case "Note":
537 fallthrough
538 case "Article":
539 fallthrough
540 case "Page":
541 obj = item
542 what = "honk"
543 default:
544 log.Printf("unknown activity: %s", what)
545 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
546 item.Write(fd)
547 io.WriteString(fd, "\n")
548 fd.Close()
549 return nil
550 }
551
552 var xonk Honk
553 // early init
554 xonk.UserID = user.ID
555 xonk.Honker, _ = item.GetString("actor")
556 if obj != nil {
557 if xonk.Honker == "" {
558 xonk.Honker = extractattrto(obj)
559 }
560 xonk.Oonker = extractattrto(obj)
561 if xonk.Oonker == xonk.Honker {
562 xonk.Oonker = ""
563 }
564 xonk.Audience = newphone(nil, obj)
565 }
566 xonk.Audience = append(xonk.Audience, xonk.Honker)
567 xonk.Audience = oneofakind(xonk.Audience)
568 for _, a := range xonk.Audience {
569 if a == user.URL {
570 xonk.Whofore = 1
571 }
572 }
573
574 if obj != nil {
575 ot, _ := obj.GetString("type")
576 url, _ = obj.GetString("url")
577 dt2, ok := obj.GetString("published")
578 if ok {
579 dt = dt2
580 }
581 xid, _ = obj.GetString("id")
582 precis, _ = obj.GetString("summary")
583 if precis == "" {
584 precis, _ = obj.GetString("name")
585 }
586 content, _ = obj.GetString("content")
587 if !strings.HasPrefix(content, "<p>") {
588 content = "<p>" + content
589 }
590 sens, _ := obj["sensitive"].(bool)
591 if sens && precis == "" {
592 precis = "unspecified horror"
593 }
594 rid, ok = obj.GetString("inReplyTo")
595 if !ok {
596 robj, ok := obj.GetMap("inReplyTo")
597 if ok {
598 rid, _ = robj.GetString("id")
599 }
600 }
601 convoy, _ = obj.GetString("context")
602 if strings.HasSuffix(convoy, "#context") &&
603 originate(convoy) != originate(xid) {
604 // friendica...
605 convoy = ""
606 }
607 if convoy == "" {
608 convoy, _ = obj.GetString("conversation")
609 }
610 if ot == "Question" {
611 if what == "honk" {
612 what = "qonk"
613 }
614 content += "<ul>"
615 ans, _ := obj.GetArray("oneOf")
616 for _, ai := range ans {
617 a, ok := ai.(junk.Junk)
618 if !ok {
619 continue
620 }
621 as, _ := a.GetString("name")
622 content += "<li>" + as
623 }
624 ans, _ = obj.GetArray("anyOf")
625 for _, ai := range ans {
626 a, ok := ai.(junk.Junk)
627 if !ok {
628 continue
629 }
630 as, _ := a.GetString("name")
631 content += "<li>" + as
632 }
633 content += "</ul>"
634 }
635 if what == "honk" && rid != "" {
636 what = "tonk"
637 }
638 atts, _ := obj.GetArray("attachment")
639 for i, atti := range atts {
640 att, ok := atti.(junk.Junk)
641 if !ok {
642 continue
643 }
644 at, _ := att.GetString("type")
645 mt, _ := att.GetString("mediaType")
646 u, _ := att.GetString("url")
647 name, _ := att.GetString("name")
648 desc, _ := att.GetString("summary")
649 if desc == "" {
650 desc = name
651 }
652 localize := false
653 if i > 4 {
654 log.Printf("excessive attachment: %s", at)
655 } else if at == "Document" || at == "Image" {
656 mt = strings.ToLower(mt)
657 log.Printf("attachment: %s %s", mt, u)
658 if mt == "text/plain" || strings.HasPrefix(mt, "image") {
659 localize = true
660 }
661 } else {
662 log.Printf("unknown attachment: %s", at)
663 }
664 if skipMedia(&xonk) {
665 localize = false
666 }
667 donk := savedonk(u, name, desc, mt, localize)
668 if donk != nil {
669 xonk.Donks = append(xonk.Donks, donk)
670 }
671 }
672 tags, _ := obj.GetArray("tag")
673 for _, tagi := range tags {
674 tag, ok := tagi.(junk.Junk)
675 if !ok {
676 continue
677 }
678 tt, _ := tag.GetString("type")
679 name, _ := tag.GetString("name")
680 desc, _ := tag.GetString("summary")
681 if desc == "" {
682 desc = name
683 }
684 if tt == "Emoji" {
685 icon, _ := tag.GetMap("icon")
686 mt, _ := icon.GetString("mediaType")
687 if mt == "" {
688 mt = "image/png"
689 }
690 u, _ := icon.GetString("url")
691 donk := savedonk(u, name, desc, mt, true)
692 if donk != nil {
693 xonk.Donks = append(xonk.Donks, donk)
694 }
695 }
696 if tt == "Hashtag" {
697 if len(name) > 1 && name[0] == '#' {
698 xonk.Onts = append(xonk.Onts, name)
699 } else {
700 log.Printf("bogus hashtag name: %s", name)
701 }
702 }
703 if tt == "Place" {
704 p := new(Place)
705 p.Name = name
706 p.Latitude, _ = tag["latitude"].(float64)
707 p.Longitude, _ = tag["longitude"].(float64)
708 p.Url, _ = tag.GetString("url")
709 xonk.Place = p
710 }
711 }
712 xonk.Onts = oneofakind(xonk.Onts)
713 replyobj, ok := obj.GetMap("replies")
714 if ok {
715 items, _ := replyobj.GetArray("items")
716 for _, repl := range items {
717 s, ok := repl.(string)
718 if ok {
719 replies = append(replies, s)
720 }
721 }
722 }
723
724 }
725 if originate(xid) != origin {
726 log.Printf("original sin: %s <> %s", xid, origin)
727 item.Write(os.Stdout)
728 return nil
729 }
730
731 if currenttid == "" {
732 currenttid = convoy
733 }
734
735 // init xonk
736 xonk.What = what
737 xonk.XID = xid
738 xonk.RID = rid
739 xonk.Date, _ = time.Parse(time.RFC3339, dt)
740 xonk.URL = url
741 xonk.Noise = content
742 xonk.Precis = precis
743 xonk.Format = "html"
744 xonk.Convoy = convoy
745
746 if isUpdate {
747 log.Printf("something has changed! %s", xonk.XID)
748 prev := getxonk(user.ID, xonk.XID)
749 if prev == nil {
750 log.Printf("didn't find old version for update: %s", xonk.XID)
751 return nil
752 }
753 prev.Noise = xonk.Noise
754 prev.Precis = xonk.Precis
755 prev.Date = xonk.Date
756 prev.Donks = xonk.Donks
757 prev.Onts = xonk.Onts
758 prev.Place = xonk.Place
759 updatehonk(prev)
760 } else if needxonk(user, &xonk) {
761 if rid != "" {
762 if needxonkid(user, rid) {
763 saveonemore(rid)
764 }
765 if convoy == "" {
766 xx := getxonk(user.ID, rid)
767 if xx != nil {
768 convoy = xx.Convoy
769 }
770 }
771 }
772 if convoy == "" {
773 convoy = currenttid
774 }
775 savexonk(&xonk)
776 }
777 for _, replid := range replies {
778 if needxonkid(user, replid) {
779 log.Printf("missing a reply: %s", replid)
780 saveonemore(replid)
781 }
782 }
783 return &xonk
784 }
785
786 return xonkxonkfn(item, origin)
787}
788
789func rubadubdub(user *WhatAbout, req junk.Junk) {
790 xid, _ := req.GetString("id")
791 actor, _ := req.GetString("actor")
792 j := junk.New()
793 j["@context"] = itiswhatitis
794 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
795 j["type"] = "Accept"
796 j["actor"] = user.URL
797 j["to"] = actor
798 j["published"] = time.Now().UTC().Format(time.RFC3339)
799 j["object"] = req
800
801 var buf bytes.Buffer
802 j.Write(&buf)
803 msg := buf.Bytes()
804
805 deliverate(0, user.Name, actor, msg)
806}
807
808func itakeitallback(user *WhatAbout, xid string) {
809 j := junk.New()
810 j["@context"] = itiswhatitis
811 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
812 j["type"] = "Undo"
813 j["actor"] = user.URL
814 j["to"] = xid
815 f := junk.New()
816 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
817 f["type"] = "Follow"
818 f["actor"] = user.URL
819 f["to"] = xid
820 f["object"] = xid
821 j["object"] = f
822 j["published"] = time.Now().UTC().Format(time.RFC3339)
823
824 var buf bytes.Buffer
825 j.Write(&buf)
826 msg := buf.Bytes()
827
828 deliverate(0, user.Name, xid, msg)
829}
830
831func subsub(user *WhatAbout, xid string) {
832 j := junk.New()
833 j["@context"] = itiswhatitis
834 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
835 j["type"] = "Follow"
836 j["actor"] = user.URL
837 j["to"] = xid
838 j["object"] = xid
839 j["published"] = time.Now().UTC().Format(time.RFC3339)
840
841 var buf bytes.Buffer
842 j.Write(&buf)
843 msg := buf.Bytes()
844
845 deliverate(0, user.Name, xid, msg)
846}
847
848// returns activity, object
849func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
850 dt := h.Date.Format(time.RFC3339)
851 var jo junk.Junk
852 j := junk.New()
853 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
854 j["actor"] = user.URL
855 j["published"] = dt
856 if h.Public {
857 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
858 } else {
859 j["to"] = h.Audience[0]
860 }
861 if len(h.Audience) > 1 {
862 j["cc"] = h.Audience[1:]
863 }
864
865 switch h.What {
866 case "update":
867 fallthrough
868 case "tonk":
869 fallthrough
870 case "honk":
871 if h.What == "update" {
872 j["type"] = "Update"
873 } else {
874 j["type"] = "Create"
875 }
876
877 jo = junk.New()
878 jo["id"] = h.XID
879 jo["type"] = "Note"
880 jo["published"] = dt
881 jo["url"] = h.XID
882 jo["attributedTo"] = user.URL
883 if h.RID != "" {
884 jo["inReplyTo"] = h.RID
885 }
886 if h.Convoy != "" {
887 jo["context"] = h.Convoy
888 jo["conversation"] = h.Convoy
889 }
890 jo["to"] = h.Audience[0]
891 if len(h.Audience) > 1 {
892 jo["cc"] = h.Audience[1:]
893 }
894 if !h.Public {
895 jo["directMessage"] = true
896 }
897 translate(h)
898 h.Noise = re_memes.ReplaceAllString(h.Noise, "")
899 jo["summary"] = h.Precis
900 jo["content"] = ontologize(mentionize(h.Noise))
901 if strings.HasPrefix(h.Precis, "DZ:") {
902 jo["sensitive"] = true
903 }
904
905 var replies []string
906 for _, reply := range h.Replies {
907 replies = append(replies, reply.XID)
908 }
909 if len(replies) > 0 {
910 jr := junk.New()
911 jr["type"] = "Collection"
912 jr["totalItems"] = len(replies)
913 jr["items"] = replies
914 jo["replies"] = jr
915 }
916
917 var tags []junk.Junk
918 g := bunchofgrapes(h.Noise)
919 for _, m := range g {
920 t := junk.New()
921 t["type"] = "Mention"
922 t["name"] = m.who
923 t["href"] = m.where
924 tags = append(tags, t)
925 }
926 for _, o := range h.Onts {
927 t := junk.New()
928 t["type"] = "Hashtag"
929 o = strings.ToLower(o)
930 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
931 t["name"] = o
932 tags = append(tags, t)
933 }
934 herd := herdofemus(h.Noise)
935 for _, e := range herd {
936 t := junk.New()
937 t["id"] = e.ID
938 t["type"] = "Emoji"
939 t["name"] = e.Name
940 i := junk.New()
941 i["type"] = "Image"
942 i["mediaType"] = "image/png"
943 i["url"] = e.ID
944 t["icon"] = i
945 tags = append(tags, t)
946 }
947 if p := h.Place; p != nil {
948 t := junk.New()
949 t["type"] = "Place"
950 t["name"] = p.Name
951 t["latitude"] = p.Latitude
952 t["longitude"] = p.Longitude
953 t["url"] = p.Url
954 tags = append(tags, t)
955 }
956 if len(tags) > 0 {
957 jo["tag"] = tags
958 }
959 var atts []junk.Junk
960 for _, d := range h.Donks {
961 if re_emus.MatchString(d.Name) {
962 continue
963 }
964 jd := junk.New()
965 jd["mediaType"] = d.Media
966 jd["name"] = d.Name
967 jd["summary"] = d.Desc
968 jd["type"] = "Document"
969 jd["url"] = d.URL
970 atts = append(atts, jd)
971 }
972 if len(atts) > 0 {
973 jo["attachment"] = atts
974 }
975 j["object"] = jo
976 case "bonk":
977 j["type"] = "Announce"
978 if h.Convoy != "" {
979 j["context"] = h.Convoy
980 }
981 j["object"] = h.XID
982 case "unbonk":
983 b := junk.New()
984 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
985 b["type"] = "Announce"
986 b["actor"] = user.URL
987 if h.Convoy != "" {
988 b["context"] = h.Convoy
989 }
990 b["object"] = h.XID
991 j["type"] = "Undo"
992 j["object"] = b
993 case "zonk":
994 j["type"] = "Delete"
995 j["object"] = h.XID
996 case "ack":
997 j["type"] = "Read"
998 j["object"] = h.XID
999 case "deack":
1000 b := junk.New()
1001 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1002 b["type"] = "Read"
1003 b["actor"] = user.URL
1004 b["object"] = h.XID
1005 j["type"] = "Undo"
1006 j["object"] = b
1007 }
1008
1009 return j, jo
1010}
1011
1012func honkworldwide(user *WhatAbout, honk *Honk) {
1013 jonk, _ := jonkjonk(user, honk)
1014 jonk["@context"] = itiswhatitis
1015 var buf bytes.Buffer
1016 jonk.Write(&buf)
1017 msg := buf.Bytes()
1018
1019 rcpts := make(map[string]bool)
1020 for _, a := range honk.Audience {
1021 if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1022 continue
1023 }
1024 box, _ := getboxes(a)
1025 if box != nil && honk.Public && box.Shared != "" {
1026 rcpts["%"+box.Shared] = true
1027 } else {
1028 rcpts[a] = true
1029 }
1030 }
1031 if honk.Public {
1032 for _, f := range getdubs(user.ID) {
1033 if f.XID == user.URL {
1034 continue
1035 }
1036 box, _ := getboxes(f.XID)
1037 if box != nil && box.Shared != "" {
1038 rcpts["%"+box.Shared] = true
1039 } else {
1040 rcpts[f.XID] = true
1041 }
1042 }
1043 }
1044 for a := range rcpts {
1045 go deliverate(0, user.Name, a, msg)
1046 }
1047}
1048
1049func asjonker(user *WhatAbout) junk.Junk {
1050 about := obfusbreak(user.About)
1051
1052 j := junk.New()
1053 j["@context"] = itiswhatitis
1054 j["id"] = user.URL
1055 j["type"] = "Person"
1056 j["inbox"] = user.URL + "/inbox"
1057 j["outbox"] = user.URL + "/outbox"
1058 j["followers"] = user.URL + "/followers"
1059 j["following"] = user.URL + "/following"
1060 j["name"] = user.Display
1061 j["preferredUsername"] = user.Name
1062 j["summary"] = about
1063 j["url"] = user.URL
1064 a := junk.New()
1065 a["type"] = "Image"
1066 a["mediaType"] = "image/png"
1067 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1068 j["icon"] = a
1069 k := junk.New()
1070 k["id"] = user.URL + "#key"
1071 k["owner"] = user.URL
1072 k["publicKeyPem"] = user.Key
1073 j["publicKey"] = k
1074
1075 return j
1076}
1077
1078var handfull = make(map[string]string)
1079var handlock sync.Mutex
1080
1081func gofish(name string) string {
1082 if name[0] == '@' {
1083 name = name[1:]
1084 }
1085 m := strings.Split(name, "@")
1086 if len(m) != 2 {
1087 log.Printf("bad fish name: %s", name)
1088 return ""
1089 }
1090 handlock.Lock()
1091 ref, ok := handfull[name]
1092 handlock.Unlock()
1093 if ok {
1094 return ref
1095 }
1096 row := stmtGetXonker.QueryRow(name, "fishname")
1097 var href string
1098 err := row.Scan(&href)
1099 if err == nil {
1100 handlock.Lock()
1101 handfull[name] = href
1102 handlock.Unlock()
1103 return href
1104 }
1105 log.Printf("fishing for %s", name)
1106 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1107 if err != nil {
1108 log.Printf("failed to go fish %s: %s", name, err)
1109 handlock.Lock()
1110 handfull[name] = ""
1111 handlock.Unlock()
1112 return ""
1113 }
1114 links, _ := j.GetArray("links")
1115 for _, li := range links {
1116 l, ok := li.(junk.Junk)
1117 if !ok {
1118 continue
1119 }
1120 href, _ := l.GetString("href")
1121 rel, _ := l.GetString("rel")
1122 t, _ := l.GetString("type")
1123 if rel == "self" && friendorfoe(t) {
1124 _, err := stmtSaveXonker.Exec(name, href, "fishname")
1125 if err != nil {
1126 log.Printf("error saving fishname: %s", err)
1127 }
1128 handlock.Lock()
1129 handfull[name] = href
1130 handlock.Unlock()
1131 return href
1132 }
1133 }
1134 handlock.Lock()
1135 handfull[name] = ""
1136 handlock.Unlock()
1137 return ""
1138}
1139
1140func isactor(t string) bool {
1141 switch t {
1142 case "Person":
1143 case "Organization":
1144 case "Application":
1145 case "Service":
1146 default:
1147 return false
1148 }
1149 return true
1150}
1151
1152func investigate(name string) (*Honker, error) {
1153 if name == "" {
1154 return nil, fmt.Errorf("no name")
1155 }
1156 if name[0] == '@' {
1157 name = gofish(name)
1158 }
1159 if name == "" {
1160 return nil, fmt.Errorf("no name")
1161 }
1162 log.Printf("digging up some info on %s", name)
1163 obj, err := GetJunkFast(name)
1164 if err != nil {
1165 log.Printf("error investigating honker: %s", err)
1166 return nil, err
1167 }
1168 t, _ := obj.GetString("type")
1169 if !isactor(t) {
1170 log.Printf("it's not a person! %s", name)
1171 return nil, err
1172 }
1173 xid, _ := obj.GetString("id")
1174 handle, _ := obj.GetString("preferredUsername")
1175 return &Honker{XID: xid, Handle: handle}, nil
1176}