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 if xid == "" {
631 log.Printf("don't know what xid is")
632 item.Write(os.Stdout)
633 return nil
634 }
635 if originate(xid) != origin {
636 log.Printf("original sin: %s <> %s", xid, origin)
637 item.Write(os.Stdout)
638 return nil
639 }
640
641 var xonk Honk
642 // early init
643 xonk.XID = xid
644 xonk.UserID = user.ID
645 xonk.Honker, _ = item.GetString("actor")
646 if xonk.Honker == "" {
647 xonk.Honker, _ = item.GetString("attributedTo")
648 }
649 if obj != nil {
650 if xonk.Honker == "" {
651 xonk.Honker = extractattrto(obj)
652 }
653 xonk.Oonker = extractattrto(obj)
654 if xonk.Oonker == xonk.Honker {
655 xonk.Oonker = ""
656 }
657 xonk.Audience = newphone(nil, obj)
658 }
659 xonk.Audience = append(xonk.Audience, xonk.Honker)
660 xonk.Audience = oneofakind(xonk.Audience)
661
662 var mentions []Mention
663 if obj != nil {
664 ot, _ := obj.GetString("type")
665 url, _ = obj.GetString("url")
666 if dt2, ok := obj.GetString("published"); ok {
667 dt = dt2
668 }
669 content, _ = obj.GetString("content")
670 if !strings.HasPrefix(content, "<p>") {
671 content = "<p>" + content
672 }
673 precis, _ = obj.GetString("summary")
674 if name, ok := obj.GetString("name"); ok {
675 if precis != "" {
676 content = precis + "<p>" + content
677 }
678 precis = html.EscapeString(name)
679 }
680 if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
681 precis = "unspecified horror"
682 }
683 rid, ok = obj.GetString("inReplyTo")
684 if !ok {
685 if robj, ok := obj.GetMap("inReplyTo"); ok {
686 rid, _ = robj.GetString("id")
687 }
688 }
689 convoy, _ = obj.GetString("context")
690 if convoy == "" {
691 convoy, _ = obj.GetString("conversation")
692 }
693 if ot == "Question" {
694 if what == "honk" {
695 what = "qonk"
696 }
697 content += "<ul>"
698 ans, _ := obj.GetArray("oneOf")
699 for _, ai := range ans {
700 a, ok := ai.(junk.Junk)
701 if !ok {
702 continue
703 }
704 as, _ := a.GetString("name")
705 content += "<li>" + as
706 }
707 ans, _ = obj.GetArray("anyOf")
708 for _, ai := range ans {
709 a, ok := ai.(junk.Junk)
710 if !ok {
711 continue
712 }
713 as, _ := a.GetString("name")
714 content += "<li>" + as
715 }
716 content += "</ul>"
717 }
718 if ot == "Move" {
719 targ, _ := obj.GetString("target")
720 content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
721 }
722 if what == "honk" && rid != "" {
723 what = "tonk"
724 }
725 atts, _ := obj.GetArray("attachment")
726 for i, atti := range atts {
727 if rejectxonk(&xonk) {
728 log.Printf("skipping rejected attachment: %s", xid)
729 continue
730 }
731 att, ok := atti.(junk.Junk)
732 if !ok {
733 continue
734 }
735 at, _ := att.GetString("type")
736 mt, _ := att.GetString("mediaType")
737 u, _ := att.GetString("url")
738 name, _ := att.GetString("name")
739 desc, _ := att.GetString("summary")
740 if desc == "" {
741 desc = name
742 }
743 localize := false
744 if i > 4 {
745 log.Printf("excessive attachment: %s", at)
746 } else if at == "Document" || at == "Image" {
747 mt = strings.ToLower(mt)
748 log.Printf("attachment: %s %s", mt, u)
749 if mt == "text/plain" || mt == "application/pdf" ||
750 strings.HasPrefix(mt, "image") {
751 localize = true
752 }
753 } else {
754 log.Printf("unknown attachment: %s", at)
755 }
756 if skipMedia(&xonk) {
757 localize = false
758 }
759 donk := savedonk(u, name, desc, mt, localize)
760 if donk != nil {
761 xonk.Donks = append(xonk.Donks, donk)
762 }
763 }
764 tags, _ := obj.GetArray("tag")
765 for _, tagi := range tags {
766 if rejectxonk(&xonk) {
767 log.Printf("skipping rejected attachment: %s", xid)
768 continue
769 }
770 tag, ok := tagi.(junk.Junk)
771 if !ok {
772 continue
773 }
774 tt, _ := tag.GetString("type")
775 name, _ := tag.GetString("name")
776 desc, _ := tag.GetString("summary")
777 if desc == "" {
778 desc = name
779 }
780 if tt == "Emoji" {
781 icon, _ := tag.GetMap("icon")
782 mt, _ := icon.GetString("mediaType")
783 if mt == "" {
784 mt = "image/png"
785 }
786 u, _ := icon.GetString("url")
787 donk := savedonk(u, name, desc, mt, true)
788 if donk != nil {
789 xonk.Donks = append(xonk.Donks, donk)
790 }
791 }
792 if tt == "Hashtag" {
793 if name == "" || name == "#" {
794 // skip it
795 } else {
796 if name[0] != '#' {
797 name = "#" + name
798 }
799 xonk.Onts = append(xonk.Onts, name)
800 }
801 }
802 if tt == "Place" {
803 p := new(Place)
804 p.Name = name
805 p.Latitude, _ = tag["latitude"].(float64)
806 p.Longitude, _ = tag["longitude"].(float64)
807 p.Url, _ = tag.GetString("url")
808 xonk.Place = p
809 }
810 if tt == "Mention" {
811 var m Mention
812 m.Who, _ = tag.GetString("name")
813 m.Where, _ = tag.GetString("href")
814 mentions = append(mentions, m)
815 }
816 }
817 if starttime, ok := obj.GetString("startTime"); ok {
818 if start, err := time.Parse(time.RFC3339, starttime); err == nil {
819 t := new(Time)
820 t.StartTime = start
821 endtime, _ := obj.GetString("endTime")
822 t.EndTime, _ = time.Parse(time.RFC3339, endtime)
823 dura, _ := obj.GetString("duration")
824 if strings.HasPrefix(dura, "PT") {
825 dura = strings.ToLower(dura[2:])
826 d, _ := time.ParseDuration(dura)
827 t.Duration = Duration(d)
828 }
829 xonk.Time = t
830 }
831 }
832 if loca, ok := obj.GetMap("location"); ok {
833 if tt, _ := loca.GetString("type"); tt == "Place" {
834 p := new(Place)
835 p.Name, _ = loca.GetString("name")
836 p.Latitude, _ = loca["latitude"].(float64)
837 p.Longitude, _ = loca["longitude"].(float64)
838 p.Url, _ = loca.GetString("url")
839 xonk.Place = p
840 }
841 }
842
843 xonk.Onts = oneofakind(xonk.Onts)
844 replyobj, ok := obj.GetMap("replies")
845 if ok {
846 items, ok := replyobj.GetArray("items")
847 if !ok {
848 first, ok := replyobj.GetMap("first")
849 if ok {
850 items, _ = first.GetArray("items")
851 }
852 }
853 for _, repl := range items {
854 s, ok := repl.(string)
855 if ok {
856 replies = append(replies, s)
857 }
858 }
859 }
860
861 }
862
863 if currenttid == "" {
864 currenttid = convoy
865 }
866
867 if len(content) > 90001 {
868 log.Printf("content too long. truncating")
869 content = content[:90001]
870 }
871
872 // init xonk
873 xonk.What = what
874 xonk.RID = rid
875 xonk.Date, _ = time.Parse(time.RFC3339, dt)
876 xonk.URL = url
877 xonk.Noise = content
878 xonk.Precis = precis
879 xonk.Format = "html"
880 xonk.Convoy = convoy
881 xonk.Mentions = mentions
882 for _, m := range mentions {
883 if m.Where == user.URL {
884 xonk.Whofore = 1
885 }
886 }
887 imaginate(&xonk)
888
889 if isUpdate {
890 log.Printf("something has changed! %s", xonk.XID)
891 prev := getxonk(user.ID, xonk.XID)
892 if prev == nil {
893 log.Printf("didn't find old version for update: %s", xonk.XID)
894 isUpdate = false
895 } else {
896 xonk.ID = prev.ID
897 updatehonk(&xonk)
898 }
899 }
900 if !isUpdate && needxonk(user, &xonk) {
901 if strings.HasSuffix(convoy, "#context") {
902 // friendica...
903 if rid != "" {
904 convoy = ""
905 } else {
906 convoy = url
907 }
908 }
909 if rid != "" {
910 if needxonkid(user, rid) {
911 goingup++
912 saveonemore(rid)
913 goingup--
914 }
915 if convoy == "" {
916 xx := getxonk(user.ID, rid)
917 if xx != nil {
918 convoy = xx.Convoy
919 }
920 }
921 }
922 if convoy == "" {
923 convoy = currenttid
924 }
925 if convoy == "" {
926 convoy = "data:,missing-" + xfiltrate()
927 currenttid = convoy
928 }
929 xonk.Convoy = convoy
930 savexonk(&xonk)
931 }
932 if goingup == 0 {
933 for _, replid := range replies {
934 if needxonkid(user, replid) {
935 log.Printf("missing a reply: %s", replid)
936 saveonemore(replid)
937 }
938 }
939 }
940 return &xonk
941 }
942
943 return xonkxonkfn(item, origin)
944}
945
946func rubadubdub(user *WhatAbout, req junk.Junk) {
947 xid, _ := req.GetString("id")
948 actor, _ := req.GetString("actor")
949 j := junk.New()
950 j["@context"] = itiswhatitis
951 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
952 j["type"] = "Accept"
953 j["actor"] = user.URL
954 j["to"] = actor
955 j["published"] = time.Now().UTC().Format(time.RFC3339)
956 j["object"] = req
957
958 deliverate(0, user.ID, actor, j.ToBytes())
959}
960
961func itakeitallback(user *WhatAbout, xid string) {
962 j := junk.New()
963 j["@context"] = itiswhatitis
964 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
965 j["type"] = "Undo"
966 j["actor"] = user.URL
967 j["to"] = xid
968 f := junk.New()
969 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
970 f["type"] = "Follow"
971 f["actor"] = user.URL
972 f["to"] = xid
973 f["object"] = xid
974 j["object"] = f
975 j["published"] = time.Now().UTC().Format(time.RFC3339)
976
977 deliverate(0, user.ID, xid, j.ToBytes())
978}
979
980func subsub(user *WhatAbout, xid string, owner string) {
981 if xid == "" {
982 log.Printf("can't subscribe to empty")
983 return
984 }
985 j := junk.New()
986 j["@context"] = itiswhatitis
987 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
988 j["type"] = "Follow"
989 j["actor"] = user.URL
990 j["to"] = owner
991 j["object"] = xid
992 j["published"] = time.Now().UTC().Format(time.RFC3339)
993
994 deliverate(0, user.ID, owner, j.ToBytes())
995}
996
997// returns activity, object
998func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
999 dt := h.Date.Format(time.RFC3339)
1000 var jo junk.Junk
1001 j := junk.New()
1002 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1003 j["actor"] = user.URL
1004 j["published"] = dt
1005 if h.Public {
1006 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
1007 } else {
1008 j["to"] = h.Audience[0]
1009 }
1010 if len(h.Audience) > 1 {
1011 j["cc"] = h.Audience[1:]
1012 }
1013
1014 switch h.What {
1015 case "update":
1016 fallthrough
1017 case "tonk":
1018 fallthrough
1019 case "event":
1020 fallthrough
1021 case "honk":
1022 j["type"] = "Create"
1023 if h.What == "update" {
1024 j["type"] = "Update"
1025 }
1026
1027 jo = junk.New()
1028 jo["id"] = h.XID
1029 jo["type"] = "Note"
1030 if h.What == "event" {
1031 jo["type"] = "Event"
1032 }
1033 jo["published"] = dt
1034 jo["url"] = h.XID
1035 jo["attributedTo"] = user.URL
1036 if h.RID != "" {
1037 jo["inReplyTo"] = h.RID
1038 }
1039 if h.Convoy != "" {
1040 jo["context"] = h.Convoy
1041 jo["conversation"] = h.Convoy
1042 }
1043 jo["to"] = h.Audience[0]
1044 if len(h.Audience) > 1 {
1045 jo["cc"] = h.Audience[1:]
1046 }
1047 if !h.Public {
1048 jo["directMessage"] = true
1049 }
1050 mentions := bunchofgrapes(h.Noise)
1051 translate(h)
1052 redoimages(h)
1053 jo["summary"] = html.EscapeString(h.Precis)
1054 jo["content"] = h.Noise
1055 if h.Precis != "" {
1056 jo["sensitive"] = true
1057 }
1058
1059 var replies []string
1060 for _, reply := range h.Replies {
1061 replies = append(replies, reply.XID)
1062 }
1063 if len(replies) > 0 {
1064 jr := junk.New()
1065 jr["type"] = "Collection"
1066 jr["totalItems"] = len(replies)
1067 jr["items"] = replies
1068 jo["replies"] = jr
1069 }
1070
1071 var tags []junk.Junk
1072 for _, m := range mentions {
1073 t := junk.New()
1074 t["type"] = "Mention"
1075 t["name"] = m.Who
1076 t["href"] = m.Where
1077 tags = append(tags, t)
1078 }
1079 for _, o := range h.Onts {
1080 t := junk.New()
1081 t["type"] = "Hashtag"
1082 o = strings.ToLower(o)
1083 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1084 t["name"] = o
1085 tags = append(tags, t)
1086 }
1087 for _, e := range herdofemus(h.Noise) {
1088 t := junk.New()
1089 t["id"] = e.ID
1090 t["type"] = "Emoji"
1091 t["name"] = e.Name
1092 i := junk.New()
1093 i["type"] = "Image"
1094 i["mediaType"] = "image/png"
1095 i["url"] = e.ID
1096 t["icon"] = i
1097 tags = append(tags, t)
1098 }
1099 if len(tags) > 0 {
1100 jo["tag"] = tags
1101 }
1102 if p := h.Place; p != nil {
1103 t := junk.New()
1104 t["type"] = "Place"
1105 if p.Name != "" {
1106 t["name"] = p.Name
1107 }
1108 if p.Latitude != 0 {
1109 t["latitude"] = p.Latitude
1110 }
1111 if p.Longitude != 0 {
1112 t["longitude"] = p.Longitude
1113 }
1114 if p.Url != "" {
1115 t["url"] = p.Url
1116 }
1117 jo["location"] = t
1118 }
1119 if t := h.Time; t != nil {
1120 jo["startTime"] = t.StartTime.Format(time.RFC3339)
1121 if t.Duration != 0 {
1122 jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1123 }
1124 }
1125 var atts []junk.Junk
1126 for _, d := range h.Donks {
1127 if re_emus.MatchString(d.Name) {
1128 continue
1129 }
1130 jd := junk.New()
1131 jd["mediaType"] = d.Media
1132 jd["name"] = d.Name
1133 jd["summary"] = html.EscapeString(d.Desc)
1134 jd["type"] = "Document"
1135 jd["url"] = d.URL
1136 atts = append(atts, jd)
1137 }
1138 if len(atts) > 0 {
1139 jo["attachment"] = atts
1140 }
1141 j["object"] = jo
1142 case "bonk":
1143 j["type"] = "Announce"
1144 if h.Convoy != "" {
1145 j["context"] = h.Convoy
1146 }
1147 j["object"] = h.XID
1148 case "unbonk":
1149 b := junk.New()
1150 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1151 b["type"] = "Announce"
1152 b["actor"] = user.URL
1153 if h.Convoy != "" {
1154 b["context"] = h.Convoy
1155 }
1156 b["object"] = h.XID
1157 j["type"] = "Undo"
1158 j["object"] = b
1159 case "zonk":
1160 j["type"] = "Delete"
1161 j["object"] = h.XID
1162 case "ack":
1163 j["type"] = "Read"
1164 j["object"] = h.XID
1165 if h.Convoy != "" {
1166 j["context"] = h.Convoy
1167 }
1168 case "react":
1169 j["type"] = "EmojiReaction"
1170 j["object"] = h.XID
1171 if h.Convoy != "" {
1172 j["context"] = h.Convoy
1173 }
1174 j["content"] = user.Options.Reaction
1175 case "deack":
1176 b := junk.New()
1177 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1178 b["type"] = "Read"
1179 b["actor"] = user.URL
1180 b["object"] = h.XID
1181 if h.Convoy != "" {
1182 b["context"] = h.Convoy
1183 }
1184 j["type"] = "Undo"
1185 j["object"] = b
1186 }
1187
1188 return j, jo
1189}
1190
1191var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1192 row := stmtAnyXonk.QueryRow(xid)
1193 honk := scanhonk(row)
1194 if honk == nil || !honk.Public {
1195 return nil, true
1196 }
1197 user, _ := butwhatabout(honk.Username)
1198 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1199 reversehonks(rawhonks)
1200 for _, h := range rawhonks {
1201 if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1202 honk.Replies = append(honk.Replies, h)
1203 }
1204 }
1205 donksforhonks([]*Honk{honk})
1206 _, j := jonkjonk(user, honk)
1207 j["@context"] = itiswhatitis
1208
1209 return j.ToBytes(), true
1210}, Limit: 128})
1211
1212func gimmejonk(xid string) ([]byte, bool) {
1213 var j []byte
1214 ok := oldjonks.Get(xid, &j)
1215 return j, ok
1216}
1217
1218func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1219 rcpts := make(map[string]bool)
1220 for _, a := range addresses {
1221 if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1222 continue
1223 }
1224 if a[0] == '%' {
1225 rcpts[a] = true
1226 continue
1227 }
1228 var box *Box
1229 ok := boxofboxes.Get(a, &box)
1230 if ok && useshared && box.Shared != "" {
1231 rcpts["%"+box.Shared] = true
1232 } else {
1233 rcpts[a] = true
1234 }
1235 }
1236 return rcpts
1237}
1238
1239func honkworldwide(user *WhatAbout, honk *Honk) {
1240 jonk, _ := jonkjonk(user, honk)
1241 jonk["@context"] = itiswhatitis
1242 msg := jonk.ToBytes()
1243
1244 rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1245
1246 if honk.Public {
1247 for _, h := range getdubs(user.ID) {
1248 if h.XID == user.URL {
1249 continue
1250 }
1251 var box *Box
1252 ok := boxofboxes.Get(h.XID, &box)
1253 if ok && box.Shared != "" {
1254 rcpts["%"+box.Shared] = true
1255 } else {
1256 rcpts[h.XID] = true
1257 }
1258 }
1259 for _, f := range getbacktracks(honk.XID) {
1260 rcpts[f] = true
1261 }
1262 }
1263 for a := range rcpts {
1264 go deliverate(0, user.ID, a, msg)
1265 }
1266 if honk.Public && len(honk.Onts) > 0 {
1267 collectiveaction(honk)
1268 }
1269}
1270
1271func collectiveaction(honk *Honk) {
1272 user := getserveruser()
1273 for _, ont := range honk.Onts {
1274 dubs := getnameddubs(serverUID, ont)
1275 if len(dubs) == 0 {
1276 continue
1277 }
1278 j := junk.New()
1279 j["@context"] = itiswhatitis
1280 j["type"] = "Add"
1281 j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1282 j["actor"] = user.URL
1283 j["object"] = honk.XID
1284 j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1285 rcpts := make(map[string]bool)
1286 for _, dub := range dubs {
1287 var box *Box
1288 ok := boxofboxes.Get(dub.XID, &box)
1289 if ok && box.Shared != "" {
1290 rcpts["%"+box.Shared] = true
1291 } else {
1292 rcpts[dub.XID] = true
1293 }
1294 }
1295 msg := j.ToBytes()
1296 for a := range rcpts {
1297 go deliverate(0, user.ID, a, msg)
1298 }
1299 }
1300}
1301
1302func junkuser(user *WhatAbout) []byte {
1303 about := markitzero(user.About)
1304
1305 j := junk.New()
1306 j["@context"] = itiswhatitis
1307 j["id"] = user.URL
1308 j["inbox"] = user.URL + "/inbox"
1309 j["outbox"] = user.URL + "/outbox"
1310 j["name"] = user.Display
1311 j["preferredUsername"] = user.Name
1312 j["summary"] = about
1313 if user.ID > 0 {
1314 j["type"] = "Person"
1315 j["url"] = user.URL
1316 j["followers"] = user.URL + "/followers"
1317 j["following"] = user.URL + "/following"
1318 a := junk.New()
1319 a["type"] = "Image"
1320 a["mediaType"] = "image/png"
1321 if ava := user.Options.Avatar; ava != "" {
1322 a["url"] = ava
1323 } else {
1324 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1325 }
1326 j["icon"] = a
1327 } else {
1328 j["type"] = "Service"
1329 }
1330 k := junk.New()
1331 k["id"] = user.URL + "#key"
1332 k["owner"] = user.URL
1333 k["publicKeyPem"] = user.Key
1334 j["publicKey"] = k
1335
1336 return j.ToBytes()
1337}
1338
1339var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1340 user, err := butwhatabout(name)
1341 if err != nil {
1342 return nil, false
1343 }
1344 return junkuser(user), true
1345}, Duration: 1 * time.Minute})
1346
1347func asjonker(name string) ([]byte, bool) {
1348 var j []byte
1349 ok := oldjonkers.Get(name, &j)
1350 return j, ok
1351}
1352
1353var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1354 m := strings.Split(name, "@")
1355 if len(m) != 2 {
1356 log.Printf("bad fish name: %s", name)
1357 return "", true
1358 }
1359 var href string
1360 row := stmtGetXonker.QueryRow(name, "fishname")
1361 err := row.Scan(&href)
1362 if err == nil {
1363 return href, true
1364 }
1365 log.Printf("fishing for %s", name)
1366 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1367 if err != nil {
1368 log.Printf("failed to go fish %s: %s", name, err)
1369 return "", true
1370 }
1371 links, _ := j.GetArray("links")
1372 for _, li := range links {
1373 l, ok := li.(junk.Junk)
1374 if !ok {
1375 continue
1376 }
1377 href, _ := l.GetString("href")
1378 rel, _ := l.GetString("rel")
1379 t, _ := l.GetString("type")
1380 if rel == "self" && friendorfoe(t) {
1381 when := time.Now().UTC().Format(dbtimeformat)
1382 _, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1383 if err != nil {
1384 log.Printf("error saving fishname: %s", err)
1385 }
1386 return href, true
1387 }
1388 }
1389 return href, true
1390}})
1391
1392func gofish(name string) string {
1393 if name[0] == '@' {
1394 name = name[1:]
1395 }
1396 var href string
1397 handfull.Get(name, &href)
1398 return href
1399}
1400
1401func investigate(name string) (*SomeThing, error) {
1402 if name == "" {
1403 return nil, fmt.Errorf("no name")
1404 }
1405 if name[0] == '@' {
1406 name = gofish(name)
1407 }
1408 if name == "" {
1409 return nil, fmt.Errorf("no name")
1410 }
1411 obj, err := GetJunkFast(name)
1412 if err != nil {
1413 return nil, err
1414 }
1415 allinjest(originate(name), obj)
1416 return somethingabout(obj)
1417}
1418
1419func somethingabout(obj junk.Junk) (*SomeThing, error) {
1420 info := new(SomeThing)
1421 t, _ := obj.GetString("type")
1422 switch t {
1423 case "Person":
1424 fallthrough
1425 case "Organization":
1426 fallthrough
1427 case "Application":
1428 fallthrough
1429 case "Service":
1430 info.What = SomeActor
1431 case "OrderedCollection":
1432 fallthrough
1433 case "Collection":
1434 info.What = SomeCollection
1435 default:
1436 return nil, fmt.Errorf("unknown object type")
1437 }
1438 info.XID, _ = obj.GetString("id")
1439 info.Name, _ = obj.GetString("preferredUsername")
1440 if info.Name == "" {
1441 info.Name, _ = obj.GetString("name")
1442 }
1443 info.Owner, _ = obj.GetString("attributedTo")
1444 if info.Owner == "" {
1445 info.Owner = info.XID
1446 }
1447 return info, nil
1448}
1449
1450func allinjest(origin string, obj junk.Junk) {
1451 keyobj, ok := obj.GetMap("publicKey")
1452 if ok {
1453 ingestpubkey(origin, keyobj)
1454 }
1455 ingestboxes(origin, obj)
1456 ingesthandle(origin, obj)
1457}
1458
1459func ingestpubkey(origin string, obj junk.Junk) {
1460 keyobj, ok := obj.GetMap("publicKey")
1461 if ok {
1462 obj = keyobj
1463 }
1464 keyname, ok := obj.GetString("id")
1465 var data string
1466 row := stmtGetXonker.QueryRow(keyname, "pubkey")
1467 err := row.Scan(&data)
1468 if err == nil {
1469 return
1470 }
1471 if !ok || origin != originate(keyname) {
1472 log.Printf("bad key origin %s <> %s", origin, keyname)
1473 return
1474 }
1475 log.Printf("ingesting a needed pubkey: %s", keyname)
1476 owner, ok := obj.GetString("owner")
1477 if !ok {
1478 log.Printf("error finding %s pubkey owner", keyname)
1479 return
1480 }
1481 data, ok = obj.GetString("publicKeyPem")
1482 if !ok {
1483 log.Printf("error finding %s pubkey", keyname)
1484 return
1485 }
1486 if originate(owner) != origin {
1487 log.Printf("bad key owner: %s <> %s", owner, origin)
1488 return
1489 }
1490 _, _, err = httpsig.DecodeKey(data)
1491 if err != nil {
1492 log.Printf("error decoding %s pubkey: %s", keyname, err)
1493 return
1494 }
1495 when := time.Now().UTC().Format(dbtimeformat)
1496 _, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1497 if err != nil {
1498 log.Printf("error saving key: %s", err)
1499 }
1500}
1501
1502func ingestboxes(origin string, obj junk.Junk) {
1503 ident, _ := obj.GetString("id")
1504 if ident == "" {
1505 return
1506 }
1507 if originate(ident) != origin {
1508 return
1509 }
1510 var info string
1511 row := stmtGetXonker.QueryRow(ident, "boxes")
1512 err := row.Scan(&info)
1513 if err == nil {
1514 return
1515 }
1516 log.Printf("ingesting boxes: %s", ident)
1517 inbox, _ := obj.GetString("inbox")
1518 outbox, _ := obj.GetString("outbox")
1519 sbox, _ := obj.GetString("endpoints", "sharedInbox")
1520 if inbox != "" {
1521 when := time.Now().UTC().Format(dbtimeformat)
1522 m := strings.Join([]string{inbox, outbox, sbox}, " ")
1523 _, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1524 if err != nil {
1525 log.Printf("error saving boxes: %s", err)
1526 }
1527 }
1528}
1529
1530func ingesthandle(origin string, obj junk.Junk) {
1531 xid, _ := obj.GetString("id")
1532 if xid == "" {
1533 return
1534 }
1535 if originate(xid) != origin {
1536 return
1537 }
1538 var handle string
1539 row := stmtGetXonker.QueryRow(xid, "handle")
1540 err := row.Scan(&handle)
1541 if err == nil {
1542 return
1543 }
1544 handle, _ = obj.GetString("preferredUsername")
1545 if handle != "" {
1546 when := time.Now().UTC().Format(dbtimeformat)
1547 _, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1548 if err != nil {
1549 log.Printf("error saving handle: %s", err)
1550 }
1551 }
1552}