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