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