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