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