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