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