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 "deack":
1156 b := junk.New()
1157 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1158 b["type"] = "Read"
1159 b["actor"] = user.URL
1160 b["object"] = h.XID
1161 if h.Convoy != "" {
1162 b["context"] = h.Convoy
1163 }
1164 j["type"] = "Undo"
1165 j["object"] = b
1166 }
1167
1168 return j, jo
1169}
1170
1171var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1172 row := stmtAnyXonk.QueryRow(xid)
1173 honk := scanhonk(row)
1174 if honk == nil || !honk.Public {
1175 return nil, true
1176 }
1177 user, _ := butwhatabout(honk.Username)
1178 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1179 reversehonks(rawhonks)
1180 for _, h := range rawhonks {
1181 if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1182 honk.Replies = append(honk.Replies, h)
1183 }
1184 }
1185 donksforhonks([]*Honk{honk})
1186 _, j := jonkjonk(user, honk)
1187 j["@context"] = itiswhatitis
1188
1189 return j.ToBytes(), true
1190}, Limit: 128})
1191
1192func gimmejonk(xid string) ([]byte, bool) {
1193 var j []byte
1194 ok := oldjonks.Get(xid, &j)
1195 return j, ok
1196}
1197
1198func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1199 rcpts := make(map[string]bool)
1200 for _, a := range addresses {
1201 if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1202 continue
1203 }
1204 if a[0] == '%' {
1205 rcpts[a] = true
1206 continue
1207 }
1208 var box *Box
1209 ok := boxofboxes.Get(a, &box)
1210 if ok && useshared && box.Shared != "" {
1211 rcpts["%"+box.Shared] = true
1212 } else {
1213 rcpts[a] = true
1214 }
1215 }
1216 return rcpts
1217}
1218
1219func honkworldwide(user *WhatAbout, honk *Honk) {
1220 jonk, _ := jonkjonk(user, honk)
1221 jonk["@context"] = itiswhatitis
1222 msg := jonk.ToBytes()
1223
1224 rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1225
1226 if honk.Public {
1227 for _, h := range getdubs(user.ID) {
1228 if h.XID == user.URL {
1229 continue
1230 }
1231 var box *Box
1232 ok := boxofboxes.Get(h.XID, &box)
1233 if ok && box.Shared != "" {
1234 rcpts["%"+box.Shared] = true
1235 } else {
1236 rcpts[h.XID] = true
1237 }
1238 }
1239 for _, f := range getbacktracks(honk.XID) {
1240 rcpts[f] = true
1241 }
1242 }
1243 for a := range rcpts {
1244 go deliverate(0, user.ID, a, msg)
1245 }
1246 if honk.Public && len(honk.Onts) > 0 {
1247 collectiveaction(honk)
1248 }
1249}
1250
1251func collectiveaction(honk *Honk) {
1252 user := getserveruser()
1253 for _, ont := range honk.Onts {
1254 dubs := getnameddubs(serverUID, ont)
1255 if len(dubs) == 0 {
1256 continue
1257 }
1258 j := junk.New()
1259 j["@context"] = itiswhatitis
1260 j["type"] = "Add"
1261 j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1262 j["actor"] = user.URL
1263 j["object"] = honk.XID
1264 j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1265 rcpts := make(map[string]bool)
1266 for _, dub := range dubs {
1267 var box *Box
1268 ok := boxofboxes.Get(dub.XID, &box)
1269 if ok && box.Shared != "" {
1270 rcpts["%"+box.Shared] = true
1271 } else {
1272 rcpts[dub.XID] = true
1273 }
1274 }
1275 msg := j.ToBytes()
1276 for a := range rcpts {
1277 go deliverate(0, user.ID, a, msg)
1278 }
1279 }
1280}
1281
1282func junkuser(user *WhatAbout) []byte {
1283 about := markitzero(user.About)
1284
1285 j := junk.New()
1286 j["@context"] = itiswhatitis
1287 j["id"] = user.URL
1288 j["inbox"] = user.URL + "/inbox"
1289 j["outbox"] = user.URL + "/outbox"
1290 j["name"] = user.Display
1291 j["preferredUsername"] = user.Name
1292 j["summary"] = about
1293 if user.ID > 0 {
1294 j["type"] = "Person"
1295 j["url"] = user.URL
1296 j["followers"] = user.URL + "/followers"
1297 j["following"] = user.URL + "/following"
1298 a := junk.New()
1299 a["type"] = "Image"
1300 a["mediaType"] = "image/png"
1301 if ava := user.Options.Avatar; ava != "" {
1302 a["url"] = ava
1303 } else {
1304 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1305 }
1306 j["icon"] = a
1307 } else {
1308 j["type"] = "Service"
1309 }
1310 k := junk.New()
1311 k["id"] = user.URL + "#key"
1312 k["owner"] = user.URL
1313 k["publicKeyPem"] = user.Key
1314 j["publicKey"] = k
1315
1316 return j.ToBytes()
1317}
1318
1319var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1320 user, err := butwhatabout(name)
1321 if err != nil {
1322 return nil, false
1323 }
1324 return junkuser(user), true
1325}, Duration: 1 * time.Minute})
1326
1327func asjonker(name string) ([]byte, bool) {
1328 var j []byte
1329 ok := oldjonkers.Get(name, &j)
1330 return j, ok
1331}
1332
1333var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1334 m := strings.Split(name, "@")
1335 if len(m) != 2 {
1336 log.Printf("bad fish name: %s", name)
1337 return "", true
1338 }
1339 var href string
1340 row := stmtGetXonker.QueryRow(name, "fishname")
1341 err := row.Scan(&href)
1342 if err == nil {
1343 return href, true
1344 }
1345 log.Printf("fishing for %s", name)
1346 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1347 if err != nil {
1348 log.Printf("failed to go fish %s: %s", name, err)
1349 return "", true
1350 }
1351 links, _ := j.GetArray("links")
1352 for _, li := range links {
1353 l, ok := li.(junk.Junk)
1354 if !ok {
1355 continue
1356 }
1357 href, _ := l.GetString("href")
1358 rel, _ := l.GetString("rel")
1359 t, _ := l.GetString("type")
1360 if rel == "self" && friendorfoe(t) {
1361 when := time.Now().UTC().Format(dbtimeformat)
1362 _, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1363 if err != nil {
1364 log.Printf("error saving fishname: %s", err)
1365 }
1366 return href, true
1367 }
1368 }
1369 return href, true
1370}})
1371
1372func gofish(name string) string {
1373 if name[0] == '@' {
1374 name = name[1:]
1375 }
1376 var href string
1377 handfull.Get(name, &href)
1378 return href
1379}
1380
1381func investigate(name string) (*SomeThing, error) {
1382 if name == "" {
1383 return nil, fmt.Errorf("no name")
1384 }
1385 if name[0] == '@' {
1386 name = gofish(name)
1387 }
1388 if name == "" {
1389 return nil, fmt.Errorf("no name")
1390 }
1391 obj, err := GetJunkFast(name)
1392 if err != nil {
1393 return nil, err
1394 }
1395 allinjest(originate(name), obj)
1396 return somethingabout(obj)
1397}
1398
1399func somethingabout(obj junk.Junk) (*SomeThing, error) {
1400 info := new(SomeThing)
1401 t, _ := obj.GetString("type")
1402 switch t {
1403 case "Person":
1404 fallthrough
1405 case "Organization":
1406 fallthrough
1407 case "Application":
1408 fallthrough
1409 case "Service":
1410 info.What = SomeActor
1411 case "OrderedCollection":
1412 fallthrough
1413 case "Collection":
1414 info.What = SomeCollection
1415 default:
1416 return nil, fmt.Errorf("unknown object type")
1417 }
1418 info.XID, _ = obj.GetString("id")
1419 info.Name, _ = obj.GetString("preferredUsername")
1420 if info.Name == "" {
1421 info.Name, _ = obj.GetString("name")
1422 }
1423 info.Owner, _ = obj.GetString("attributedTo")
1424 if info.Owner == "" {
1425 info.Owner = info.XID
1426 }
1427 return info, nil
1428}
1429
1430func allinjest(origin string, obj junk.Junk) {
1431 keyobj, ok := obj.GetMap("publicKey")
1432 if ok {
1433 ingestpubkey(origin, keyobj)
1434 }
1435 ingestboxes(origin, obj)
1436 ingesthandle(origin, obj)
1437}
1438
1439func ingestpubkey(origin string, obj junk.Junk) {
1440 keyobj, ok := obj.GetMap("publicKey")
1441 if ok {
1442 obj = keyobj
1443 }
1444 keyname, ok := obj.GetString("id")
1445 var data string
1446 row := stmtGetXonker.QueryRow(keyname, "pubkey")
1447 err := row.Scan(&data)
1448 if err == nil {
1449 return
1450 }
1451 if !ok || origin != originate(keyname) {
1452 log.Printf("bad key origin %s <> %s", origin, keyname)
1453 return
1454 }
1455 log.Printf("ingesting a needed pubkey: %s", keyname)
1456 owner, ok := obj.GetString("owner")
1457 if !ok {
1458 log.Printf("error finding %s pubkey owner", keyname)
1459 return
1460 }
1461 data, ok = obj.GetString("publicKeyPem")
1462 if !ok {
1463 log.Printf("error finding %s pubkey", keyname)
1464 return
1465 }
1466 if originate(owner) != origin {
1467 log.Printf("bad key owner: %s <> %s", owner, origin)
1468 return
1469 }
1470 _, _, err = httpsig.DecodeKey(data)
1471 if err != nil {
1472 log.Printf("error decoding %s pubkey: %s", keyname, err)
1473 return
1474 }
1475 when := time.Now().UTC().Format(dbtimeformat)
1476 _, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1477 if err != nil {
1478 log.Printf("error saving key: %s", err)
1479 }
1480}
1481
1482func ingestboxes(origin string, obj junk.Junk) {
1483 ident, _ := obj.GetString("id")
1484 if ident == "" {
1485 return
1486 }
1487 if originate(ident) != origin {
1488 return
1489 }
1490 var info string
1491 row := stmtGetXonker.QueryRow(ident, "boxes")
1492 err := row.Scan(&info)
1493 if err == nil {
1494 return
1495 }
1496 log.Printf("ingesting boxes: %s", ident)
1497 inbox, _ := obj.GetString("inbox")
1498 outbox, _ := obj.GetString("outbox")
1499 sbox, _ := obj.GetString("endpoints", "sharedInbox")
1500 if inbox != "" {
1501 when := time.Now().UTC().Format(dbtimeformat)
1502 m := strings.Join([]string{inbox, outbox, sbox}, " ")
1503 _, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1504 if err != nil {
1505 log.Printf("error saving boxes: %s", err)
1506 }
1507 }
1508}
1509
1510func ingesthandle(origin string, obj junk.Junk) {
1511 xid, _ := obj.GetString("id")
1512 if xid == "" {
1513 return
1514 }
1515 if originate(xid) != origin {
1516 return
1517 }
1518 var handle string
1519 row := stmtGetXonker.QueryRow(xid, "handle")
1520 err := row.Scan(&handle)
1521 if err == nil {
1522 return
1523 }
1524 handle, _ = obj.GetString("preferredUsername")
1525 if handle != "" {
1526 when := time.Now().UTC().Format(dbtimeformat)
1527 _, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1528 if err != nil {
1529 log.Printf("error saving handle: %s", err)
1530 }
1531 }
1532}