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 jo["summary"] = html.EscapeString(h.Precis)
1039 jo["content"] = h.Noise
1040 if h.Precis != "" {
1041 jo["sensitive"] = true
1042 }
1043
1044 var replies []string
1045 for _, reply := range h.Replies {
1046 replies = append(replies, reply.XID)
1047 }
1048 if len(replies) > 0 {
1049 jr := junk.New()
1050 jr["type"] = "Collection"
1051 jr["totalItems"] = len(replies)
1052 jr["items"] = replies
1053 jo["replies"] = jr
1054 }
1055
1056 var tags []junk.Junk
1057 for _, m := range mentions {
1058 t := junk.New()
1059 t["type"] = "Mention"
1060 t["name"] = m.Who
1061 t["href"] = m.Where
1062 tags = append(tags, t)
1063 }
1064 for _, o := range h.Onts {
1065 t := junk.New()
1066 t["type"] = "Hashtag"
1067 o = strings.ToLower(o)
1068 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1069 t["name"] = o
1070 tags = append(tags, t)
1071 }
1072 for _, e := range herdofemus(h.Noise) {
1073 t := junk.New()
1074 t["id"] = e.ID
1075 t["type"] = "Emoji"
1076 t["name"] = e.Name
1077 i := junk.New()
1078 i["type"] = "Image"
1079 i["mediaType"] = "image/png"
1080 i["url"] = e.ID
1081 t["icon"] = i
1082 tags = append(tags, t)
1083 }
1084 if len(tags) > 0 {
1085 jo["tag"] = tags
1086 }
1087 if p := h.Place; p != nil {
1088 t := junk.New()
1089 t["type"] = "Place"
1090 if p.Name != "" {
1091 t["name"] = p.Name
1092 }
1093 if p.Latitude != 0 {
1094 t["latitude"] = p.Latitude
1095 }
1096 if p.Longitude != 0 {
1097 t["longitude"] = p.Longitude
1098 }
1099 if p.Url != "" {
1100 t["url"] = p.Url
1101 }
1102 jo["location"] = t
1103 }
1104 if t := h.Time; t != nil {
1105 jo["startTime"] = t.StartTime.Format(time.RFC3339)
1106 if t.Duration != 0 {
1107 jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1108 }
1109 }
1110 var atts []junk.Junk
1111 for _, d := range h.Donks {
1112 if re_emus.MatchString(d.Name) {
1113 continue
1114 }
1115 jd := junk.New()
1116 jd["mediaType"] = d.Media
1117 jd["name"] = d.Name
1118 jd["summary"] = html.EscapeString(d.Desc)
1119 jd["type"] = "Document"
1120 jd["url"] = d.URL
1121 atts = append(atts, jd)
1122 }
1123 if len(atts) > 0 {
1124 jo["attachment"] = atts
1125 }
1126 j["object"] = jo
1127 case "bonk":
1128 j["type"] = "Announce"
1129 if h.Convoy != "" {
1130 j["context"] = h.Convoy
1131 }
1132 j["object"] = h.XID
1133 case "unbonk":
1134 b := junk.New()
1135 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1136 b["type"] = "Announce"
1137 b["actor"] = user.URL
1138 if h.Convoy != "" {
1139 b["context"] = h.Convoy
1140 }
1141 b["object"] = h.XID
1142 j["type"] = "Undo"
1143 j["object"] = b
1144 case "zonk":
1145 j["type"] = "Delete"
1146 j["object"] = h.XID
1147 case "ack":
1148 j["type"] = "Read"
1149 j["object"] = h.XID
1150 if h.Convoy != "" {
1151 j["context"] = h.Convoy
1152 }
1153 case "react":
1154 j["type"] = "EmojiReact"
1155 j["object"] = h.XID
1156 if h.Convoy != "" {
1157 j["context"] = h.Convoy
1158 }
1159 j["content"] = h.Noise
1160 case "deack":
1161 b := junk.New()
1162 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1163 b["type"] = "Read"
1164 b["actor"] = user.URL
1165 b["object"] = h.XID
1166 if h.Convoy != "" {
1167 b["context"] = h.Convoy
1168 }
1169 j["type"] = "Undo"
1170 j["object"] = b
1171 }
1172
1173 return j, jo
1174}
1175
1176var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1177 row := stmtAnyXonk.QueryRow(xid)
1178 honk := scanhonk(row)
1179 if honk == nil || !honk.Public {
1180 return nil, true
1181 }
1182 user, _ := butwhatabout(honk.Username)
1183 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1184 reversehonks(rawhonks)
1185 for _, h := range rawhonks {
1186 if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1187 honk.Replies = append(honk.Replies, h)
1188 }
1189 }
1190 donksforhonks([]*Honk{honk})
1191 _, j := jonkjonk(user, honk)
1192 j["@context"] = itiswhatitis
1193
1194 return j.ToBytes(), true
1195}, Limit: 128})
1196
1197func gimmejonk(xid string) ([]byte, bool) {
1198 var j []byte
1199 ok := oldjonks.Get(xid, &j)
1200 return j, ok
1201}
1202
1203func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1204 rcpts := make(map[string]bool)
1205 for _, a := range addresses {
1206 if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1207 continue
1208 }
1209 if a[0] == '%' {
1210 rcpts[a] = true
1211 continue
1212 }
1213 var box *Box
1214 ok := boxofboxes.Get(a, &box)
1215 if ok && useshared && box.Shared != "" {
1216 rcpts["%"+box.Shared] = true
1217 } else {
1218 rcpts[a] = true
1219 }
1220 }
1221 return rcpts
1222}
1223
1224func honkworldwide(user *WhatAbout, honk *Honk) {
1225 jonk, _ := jonkjonk(user, honk)
1226 jonk["@context"] = itiswhatitis
1227 msg := jonk.ToBytes()
1228
1229 rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1230
1231 if honk.Public {
1232 for _, h := range getdubs(user.ID) {
1233 if h.XID == user.URL {
1234 continue
1235 }
1236 var box *Box
1237 ok := boxofboxes.Get(h.XID, &box)
1238 if ok && box.Shared != "" {
1239 rcpts["%"+box.Shared] = true
1240 } else {
1241 rcpts[h.XID] = true
1242 }
1243 }
1244 for _, f := range getbacktracks(honk.XID) {
1245 rcpts[f] = true
1246 }
1247 }
1248 for a := range rcpts {
1249 go deliverate(0, user.ID, a, msg)
1250 }
1251 if honk.Public && len(honk.Onts) > 0 {
1252 collectiveaction(honk)
1253 }
1254}
1255
1256func collectiveaction(honk *Honk) {
1257 user := getserveruser()
1258 for _, ont := range honk.Onts {
1259 dubs := getnameddubs(serverUID, ont)
1260 if len(dubs) == 0 {
1261 continue
1262 }
1263 j := junk.New()
1264 j["@context"] = itiswhatitis
1265 j["type"] = "Add"
1266 j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1267 j["actor"] = user.URL
1268 j["object"] = honk.XID
1269 j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1270 rcpts := make(map[string]bool)
1271 for _, dub := range dubs {
1272 var box *Box
1273 ok := boxofboxes.Get(dub.XID, &box)
1274 if ok && box.Shared != "" {
1275 rcpts["%"+box.Shared] = true
1276 } else {
1277 rcpts[dub.XID] = true
1278 }
1279 }
1280 msg := j.ToBytes()
1281 for a := range rcpts {
1282 go deliverate(0, user.ID, a, msg)
1283 }
1284 }
1285}
1286
1287func junkuser(user *WhatAbout) junk.Junk {
1288 about := markitzero(user.About)
1289
1290 j := junk.New()
1291 j["@context"] = itiswhatitis
1292 j["id"] = user.URL
1293 j["inbox"] = user.URL + "/inbox"
1294 j["outbox"] = user.URL + "/outbox"
1295 j["name"] = user.Display
1296 j["preferredUsername"] = user.Name
1297 j["summary"] = about
1298 if user.ID > 0 {
1299 j["type"] = "Person"
1300 j["url"] = user.URL
1301 j["followers"] = user.URL + "/followers"
1302 j["following"] = user.URL + "/following"
1303 a := junk.New()
1304 a["type"] = "Image"
1305 a["mediaType"] = "image/png"
1306 if ava := user.Options.Avatar; ava != "" {
1307 a["url"] = ava
1308 } else {
1309 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1310 }
1311 j["icon"] = a
1312 } else {
1313 j["type"] = "Service"
1314 }
1315 k := junk.New()
1316 k["id"] = user.URL + "#key"
1317 k["owner"] = user.URL
1318 k["publicKeyPem"] = user.Key
1319 j["publicKey"] = k
1320
1321 return j
1322}
1323
1324var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1325 user, err := butwhatabout(name)
1326 if err != nil {
1327 return nil, false
1328 }
1329 var buf bytes.Buffer
1330 j := junkuser(user)
1331 j.Write(&buf)
1332 return buf.Bytes(), true
1333}, Duration: 1 * time.Minute})
1334
1335func asjonker(name string) ([]byte, bool) {
1336 var j []byte
1337 ok := oldjonkers.Get(name, &j)
1338 return j, ok
1339}
1340
1341var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1342 m := strings.Split(name, "@")
1343 if len(m) != 2 {
1344 log.Printf("bad fish name: %s", name)
1345 return "", true
1346 }
1347 var href string
1348 row := stmtGetXonker.QueryRow(name, "fishname")
1349 err := row.Scan(&href)
1350 if err == nil {
1351 return href, true
1352 }
1353 log.Printf("fishing for %s", name)
1354 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1355 if err != nil {
1356 log.Printf("failed to go fish %s: %s", name, err)
1357 return "", true
1358 }
1359 links, _ := j.GetArray("links")
1360 for _, li := range links {
1361 l, ok := li.(junk.Junk)
1362 if !ok {
1363 continue
1364 }
1365 href, _ := l.GetString("href")
1366 rel, _ := l.GetString("rel")
1367 t, _ := l.GetString("type")
1368 if rel == "self" && friendorfoe(t) {
1369 when := time.Now().UTC().Format(dbtimeformat)
1370 _, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1371 if err != nil {
1372 log.Printf("error saving fishname: %s", err)
1373 }
1374 return href, true
1375 }
1376 }
1377 return href, true
1378}, Duration: 1 * time.Minute})
1379
1380func gofish(name string) string {
1381 if name[0] == '@' {
1382 name = name[1:]
1383 }
1384 var href string
1385 handfull.Get(name, &href)
1386 return href
1387}
1388
1389func investigate(name string) (*SomeThing, error) {
1390 if name == "" {
1391 return nil, fmt.Errorf("no name")
1392 }
1393 if name[0] == '@' {
1394 name = gofish(name)
1395 }
1396 if name == "" {
1397 return nil, fmt.Errorf("no name")
1398 }
1399 obj, err := GetJunkFast(name)
1400 if err != nil {
1401 return nil, err
1402 }
1403 allinjest(originate(name), obj)
1404 return somethingabout(obj)
1405}
1406
1407func somethingabout(obj junk.Junk) (*SomeThing, error) {
1408 info := new(SomeThing)
1409 t, _ := obj.GetString("type")
1410 switch t {
1411 case "Person":
1412 fallthrough
1413 case "Organization":
1414 fallthrough
1415 case "Application":
1416 fallthrough
1417 case "Service":
1418 info.What = SomeActor
1419 case "OrderedCollection":
1420 fallthrough
1421 case "Collection":
1422 info.What = SomeCollection
1423 default:
1424 return nil, fmt.Errorf("unknown object type")
1425 }
1426 info.XID, _ = obj.GetString("id")
1427 info.Name, _ = obj.GetString("preferredUsername")
1428 if info.Name == "" {
1429 info.Name, _ = obj.GetString("name")
1430 }
1431 info.Owner, _ = obj.GetString("attributedTo")
1432 if info.Owner == "" {
1433 info.Owner = info.XID
1434 }
1435 return info, nil
1436}
1437
1438func allinjest(origin string, obj junk.Junk) {
1439 keyobj, ok := obj.GetMap("publicKey")
1440 if ok {
1441 ingestpubkey(origin, keyobj)
1442 }
1443 ingestboxes(origin, obj)
1444 ingesthandle(origin, obj)
1445}
1446
1447func ingestpubkey(origin string, obj junk.Junk) {
1448 keyobj, ok := obj.GetMap("publicKey")
1449 if ok {
1450 obj = keyobj
1451 }
1452 keyname, ok := obj.GetString("id")
1453 var data string
1454 row := stmtGetXonker.QueryRow(keyname, "pubkey")
1455 err := row.Scan(&data)
1456 if err == nil {
1457 return
1458 }
1459 if !ok || origin != originate(keyname) {
1460 log.Printf("bad key origin %s <> %s", origin, keyname)
1461 return
1462 }
1463 log.Printf("ingesting a needed pubkey: %s", keyname)
1464 owner, ok := obj.GetString("owner")
1465 if !ok {
1466 log.Printf("error finding %s pubkey owner", keyname)
1467 return
1468 }
1469 data, ok = obj.GetString("publicKeyPem")
1470 if !ok {
1471 log.Printf("error finding %s pubkey", keyname)
1472 return
1473 }
1474 if originate(owner) != origin {
1475 log.Printf("bad key owner: %s <> %s", owner, origin)
1476 return
1477 }
1478 _, _, err = httpsig.DecodeKey(data)
1479 if err != nil {
1480 log.Printf("error decoding %s pubkey: %s", keyname, err)
1481 return
1482 }
1483 when := time.Now().UTC().Format(dbtimeformat)
1484 _, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1485 if err != nil {
1486 log.Printf("error saving key: %s", err)
1487 }
1488}
1489
1490func ingestboxes(origin string, obj junk.Junk) {
1491 ident, _ := obj.GetString("id")
1492 if ident == "" {
1493 return
1494 }
1495 if originate(ident) != origin {
1496 return
1497 }
1498 var info string
1499 row := stmtGetXonker.QueryRow(ident, "boxes")
1500 err := row.Scan(&info)
1501 if err == nil {
1502 return
1503 }
1504 log.Printf("ingesting boxes: %s", ident)
1505 inbox, _ := obj.GetString("inbox")
1506 outbox, _ := obj.GetString("outbox")
1507 sbox, _ := obj.GetString("endpoints", "sharedInbox")
1508 if inbox != "" {
1509 when := time.Now().UTC().Format(dbtimeformat)
1510 m := strings.Join([]string{inbox, outbox, sbox}, " ")
1511 _, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1512 if err != nil {
1513 log.Printf("error saving boxes: %s", err)
1514 }
1515 }
1516}
1517
1518func ingesthandle(origin string, obj junk.Junk) {
1519 xid, _ := obj.GetString("id")
1520 if xid == "" {
1521 return
1522 }
1523 if originate(xid) != origin {
1524 return
1525 }
1526 var handle string
1527 row := stmtGetXonker.QueryRow(xid, "handle")
1528 err := row.Scan(&handle)
1529 if err == nil {
1530 return
1531 }
1532 handle, _ = obj.GetString("preferredUsername")
1533 if handle != "" {
1534 when := time.Now().UTC().Format(dbtimeformat)
1535 _, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1536 if err != nil {
1537 log.Printf("error saving handle: %s", err)
1538 }
1539 }
1540}
1541
1542func updateMe(username string) {
1543 var user *WhatAbout
1544 somenamedusers.Get(username, &user)
1545 dt := time.Now().UTC().Format(time.RFC3339)
1546 j := junk.New()
1547 j["@context"] = itiswhatitis
1548 j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1549 j["actor"] = user.URL
1550 j["published"] = dt
1551 j["to"] = []string{thewholeworld, user.URL + "/followers"}
1552 j["type"] = "Update"
1553 j["object"] = junkuser(user)
1554
1555 msg := j.ToBytes()
1556
1557 rcpts := make(map[string]bool)
1558 for _, f := range getdubs(user.ID) {
1559 if f.XID == user.URL {
1560 continue
1561 }
1562 var box *Box
1563 boxofboxes.Get(f.XID, &box)
1564 if box != nil && box.Shared != "" {
1565 rcpts["%"+box.Shared] = true
1566 } else {
1567 rcpts[f.XID] = true
1568 }
1569 }
1570 for a := range rcpts {
1571 go deliverate(0, user.ID, a, msg)
1572 }
1573}