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