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