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