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