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 "fmt"
23 "html"
24 "io"
25 "log"
26 notrand "math/rand"
27 "net/http"
28 "net/url"
29 "os"
30 "regexp"
31 "strings"
32 "sync"
33 "time"
34
35 "humungus.tedunangst.com/r/webs/cache"
36 "humungus.tedunangst.com/r/webs/httpsig"
37 "humungus.tedunangst.com/r/webs/image"
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 = make(map[string][]chan JunkError)
121var decklock sync.Mutex
122
123func GetJunkTimeout(url string, timeout time.Duration) (junk.Junk, error) {
124 decklock.Lock()
125 inflight, ok := flightdeck[url]
126 if ok {
127 log.Printf("awaiting result for %s", url)
128 c := make(chan JunkError)
129 flightdeck[url] = append(inflight, c)
130 decklock.Unlock()
131 je := <-c
132 close(c)
133 return je.Junk, je.Err
134 }
135 flightdeck[url] = inflight
136 decklock.Unlock()
137
138 at := thefakename
139 if strings.Contains(url, ".well-known/webfinger?resource") {
140 at = "application/jrd+json"
141 }
142 j, err := junk.Get(url, junk.GetArgs{
143 Accept: at,
144 Agent: "honksnonk/5.0; " + serverName,
145 Timeout: timeout,
146 })
147
148 decklock.Lock()
149 inflight = flightdeck[url]
150 delete(flightdeck, url)
151 decklock.Unlock()
152 if len(inflight) > 0 {
153 je := JunkError{Junk: j, Err: err}
154 go func() {
155 for _, c := range inflight {
156 log.Printf("returning awaited result for %s", url)
157 c <- je
158 }
159 }()
160 }
161 return j, err
162}
163
164func savedonk(url string, name, desc, media string, localize bool) *Donk {
165 if url == "" {
166 return nil
167 }
168 donk := finddonk(url)
169 if donk != nil {
170 return donk
171 }
172 donk = new(Donk)
173 log.Printf("saving donk: %s", url)
174 xid := xfiltrate()
175 data := []byte{}
176 if localize {
177 resp, err := http.Get(url)
178 if err != nil {
179 log.Printf("error fetching %s: %s", url, err)
180 localize = false
181 goto saveit
182 }
183 defer resp.Body.Close()
184 if resp.StatusCode != 200 {
185 localize = false
186 goto saveit
187 }
188 var buf bytes.Buffer
189 limiter := io.LimitReader(resp.Body, 10*1024*1024)
190 io.Copy(&buf, limiter)
191
192 data = buf.Bytes()
193 if len(data) == 10*1024*1024 {
194 log.Printf("truncation likely")
195 }
196 if strings.HasPrefix(media, "image") {
197 img, err := image.Vacuum(&buf,
198 image.Params{LimitSize: 4200 * 4200, MaxWidth: 2048, MaxHeight: 2048})
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 len(data) > 100000 {
213 log.Printf("not saving large attachment")
214 localize = false
215 data = []byte{}
216 }
217 }
218saveit:
219 fileid, err := savefile(xid, name, desc, url, media, localize, data)
220 if err != nil {
221 log.Printf("error saving file %s: %s", url, err)
222 return nil
223 }
224 donk.FileID = fileid
225 donk.XID = xid
226 return donk
227}
228
229func iszonked(userid int64, xid string) bool {
230 row := stmtFindZonk.QueryRow(userid, xid)
231 var id int64
232 err := row.Scan(&id)
233 if err == nil {
234 return true
235 }
236 if err != sql.ErrNoRows {
237 log.Printf("error querying zonk: %s", err)
238 }
239 return false
240}
241
242func needxonk(user *WhatAbout, x *Honk) bool {
243 if rejectxonk(x) {
244 return false
245 }
246 return needxonkid(user, x.XID)
247}
248func needxonkid(user *WhatAbout, xid string) bool {
249 if strings.HasPrefix(xid, user.URL+"/") {
250 return false
251 }
252 if rejectorigin(user.ID, xid) {
253 return false
254 }
255 if iszonked(user.ID, xid) {
256 log.Printf("already zonked: %s", xid)
257 return false
258 }
259 row := stmtFindXonk.QueryRow(user.ID, xid)
260 var id int64
261 err := row.Scan(&id)
262 if err == nil {
263 return false
264 }
265 if err != sql.ErrNoRows {
266 log.Printf("error querying xonk: %s", err)
267 }
268 return true
269}
270
271func eradicatexonk(userid int64, xid string) {
272 xonk := getxonk(userid, xid)
273 if xonk != nil {
274 deletehonk(xonk.ID)
275 }
276 _, err := stmtSaveZonker.Exec(userid, xid, "zonk")
277 if err != nil {
278 log.Printf("error eradicating: %s", err)
279 }
280}
281
282func savexonk(x *Honk) {
283 log.Printf("saving xonk: %s", x.XID)
284 go prehandle(x.Honker)
285 go prehandle(x.Oonker)
286 savehonk(x)
287}
288
289type Box struct {
290 In string
291 Out string
292 Shared string
293}
294
295var boxofboxes = cache.New(cache.Options{Filler: func(ident string) (*Box, bool) {
296 var info string
297 row := stmtGetXonker.QueryRow(ident, "boxes")
298 err := row.Scan(&info)
299 if err == nil {
300 m := strings.Split(info, " ")
301 b := &Box{In: m[0], Out: m[1], Shared: m[2]}
302 return b, true
303 }
304 j, err := GetJunk(ident)
305 if err != nil {
306 log.Printf("error getting boxes: %s", err)
307 return nil, false
308 }
309 inbox, _ := j.GetString("inbox")
310 outbox, _ := j.GetString("outbox")
311 sbox, _ := j.GetString("endpoints", "sharedInbox")
312 b := &Box{In: inbox, Out: outbox, Shared: sbox}
313 if inbox != "" {
314 m := strings.Join([]string{inbox, outbox, sbox}, " ")
315 _, err = stmtSaveXonker.Exec(ident, m, "boxes")
316 if err != nil {
317 log.Printf("error saving boxes: %s", err)
318 }
319 }
320 return b, true
321}})
322
323func gimmexonks(user *WhatAbout, outbox string) {
324 log.Printf("getting outbox: %s", outbox)
325 j, err := GetJunk(outbox)
326 if err != nil {
327 log.Printf("error getting outbox: %s", err)
328 return
329 }
330 t, _ := j.GetString("type")
331 origin := originate(outbox)
332 if t == "OrderedCollection" {
333 items, _ := j.GetArray("orderedItems")
334 if items == nil {
335 items, _ = j.GetArray("items")
336 }
337 if items == nil {
338 obj, ok := j.GetMap("first")
339 if ok {
340 items, _ = obj.GetArray("orderedItems")
341 } else {
342 page1, ok := j.GetString("first")
343 if ok {
344 j, err = GetJunk(page1)
345 if err != nil {
346 log.Printf("error gettings page1: %s", err)
347 return
348 }
349 items, _ = j.GetArray("orderedItems")
350 }
351 }
352 }
353 if len(items) > 20 {
354 items = items[0:20]
355 }
356 for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
357 items[i], items[j] = items[j], items[i]
358 }
359 for _, item := range items {
360 obj, ok := item.(junk.Junk)
361 if ok {
362 xonksaver(user, obj, origin)
363 continue
364 }
365 xid, ok := item.(string)
366 if ok {
367 if !needxonkid(user, xid) {
368 continue
369 }
370 obj, err = GetJunk(xid)
371 if err != nil {
372 log.Printf("error getting item: %s", err)
373 continue
374 }
375 xonksaver(user, obj, originate(xid))
376 }
377 }
378 }
379}
380
381func whosthere(xid string) ([]string, string) {
382 obj, err := GetJunk(xid)
383 if err != nil {
384 log.Printf("error getting remote xonk: %s", err)
385 return nil, ""
386 }
387 convoy, _ := obj.GetString("context")
388 if convoy == "" {
389 convoy, _ = obj.GetString("conversation")
390 }
391 return newphone(nil, obj), convoy
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, _ := item.GetString("published")
468
469 var err error
470 var xid, rid, url, content, precis, convoy string
471 var replies []string
472 var obj junk.Junk
473 var ok bool
474 isUpdate := false
475 switch what {
476 case "Delete":
477 obj, ok = item.GetMap("object")
478 if ok {
479 xid, _ = obj.GetString("id")
480 } else {
481 xid, _ = item.GetString("object")
482 }
483 if xid == "" {
484 return nil
485 }
486 if originate(xid) != origin {
487 log.Printf("forged delete: %s", xid)
488 return nil
489 }
490 log.Printf("eradicating %s", xid)
491 eradicatexonk(user.ID, xid)
492 return nil
493 case "Tombstone":
494 xid, _ = item.GetString("id")
495 if xid == "" {
496 return nil
497 }
498 if originate(xid) != origin {
499 log.Printf("forged delete: %s", xid)
500 return nil
501 }
502 log.Printf("eradicating %s", xid)
503 eradicatexonk(user.ID, xid)
504 return nil
505 case "Announce":
506 obj, ok = item.GetMap("object")
507 if ok {
508 xid, _ = obj.GetString("id")
509 } else {
510 xid, _ = item.GetString("object")
511 }
512 if !needxonkid(user, xid) {
513 return nil
514 }
515 log.Printf("getting bonk: %s", xid)
516 obj, err = GetJunkHardMode(xid)
517 if err != nil {
518 log.Printf("error getting bonk: %s: %s", xid, err)
519 }
520 origin = originate(xid)
521 what = "bonk"
522 case "Update":
523 isUpdate = true
524 fallthrough
525 case "Create":
526 obj, ok = item.GetMap("object")
527 if !ok {
528 xid, _ = item.GetString("object")
529 log.Printf("getting created honk: %s", xid)
530 obj, err = GetJunkHardMode(xid)
531 if err != nil {
532 log.Printf("error getting creation: %s", err)
533 }
534 }
535 what = "honk"
536 if obj != nil {
537 t, _ := obj.GetString("type")
538 switch t {
539 case "Event":
540 what = "event"
541 }
542 }
543 case "Read":
544 xid, ok = item.GetString("object")
545 if ok {
546 if !needxonkid(user, xid) {
547 log.Printf("don't need read obj: %s", xid)
548 return nil
549 }
550 obj, err = GetJunkHardMode(xid)
551 if err != nil {
552 log.Printf("error getting read: %s", err)
553 return nil
554 }
555 return xonkxonkfn(obj, originate(xid))
556 }
557 return nil
558 case "Add":
559 xid, ok = item.GetString("object")
560 if ok {
561 // check target...
562 if !needxonkid(user, xid) {
563 log.Printf("don't need added obj: %s", xid)
564 return nil
565 }
566 obj, err = GetJunkHardMode(xid)
567 if err != nil {
568 log.Printf("error getting add: %s", err)
569 return nil
570 }
571 return xonkxonkfn(obj, originate(xid))
572 }
573 return nil
574 case "Audio":
575 fallthrough
576 case "Video":
577 fallthrough
578 case "Question":
579 fallthrough
580 case "Note":
581 fallthrough
582 case "Article":
583 fallthrough
584 case "Page":
585 obj = item
586 what = "honk"
587 case "Event":
588 obj = item
589 what = "event"
590 default:
591 log.Printf("unknown activity: %s", what)
592 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
593 item.Write(fd)
594 io.WriteString(fd, "\n")
595 fd.Close()
596 return nil
597 }
598
599 if obj != nil {
600 _, ok := obj.GetString("diaspora:guid")
601 if ok {
602 // friendica does the silliest bonks
603 c, ok := obj.GetString("source", "content")
604 if ok {
605 re_link := regexp.MustCompile(`link='([^']*)'`)
606 m := re_link.FindStringSubmatch(c)
607 if len(m) > 1 {
608 xid := m[1]
609 log.Printf("getting friendica flavored bonk: %s", xid)
610 if !needxonkid(user, xid) {
611 return nil
612 }
613 newobj, err := GetJunkHardMode(xid)
614 if err != nil {
615 log.Printf("error getting bonk: %s: %s", xid, err)
616 } else {
617 obj = newobj
618 origin = originate(xid)
619 what = "bonk"
620 }
621 }
622 }
623 }
624 }
625
626 var xonk Honk
627 // early init
628 xonk.UserID = user.ID
629 xonk.Honker, _ = item.GetString("actor")
630 if xonk.Honker == "" {
631 xonk.Honker, _ = item.GetString("attributedTo")
632 }
633 if obj != nil {
634 if xonk.Honker == "" {
635 xonk.Honker = extractattrto(obj)
636 }
637 xonk.Oonker = extractattrto(obj)
638 if xonk.Oonker == xonk.Honker {
639 xonk.Oonker = ""
640 }
641 xonk.Audience = newphone(nil, obj)
642 }
643 xonk.Audience = append(xonk.Audience, xonk.Honker)
644 xonk.Audience = oneofakind(xonk.Audience)
645
646 var mentions []string
647 if obj != nil {
648 ot, _ := obj.GetString("type")
649 url, _ = obj.GetString("url")
650 dt2, ok := obj.GetString("published")
651 if ok {
652 dt = dt2
653 }
654 xid, _ = obj.GetString("id")
655 precis, _ = obj.GetString("summary")
656 if precis == "" {
657 precis, _ = obj.GetString("name")
658 }
659 content, _ = obj.GetString("content")
660 if !strings.HasPrefix(content, "<p>") {
661 content = "<p>" + content
662 }
663 sens, _ := obj["sensitive"].(bool)
664 if sens && precis == "" {
665 precis = "unspecified horror"
666 }
667 rid, ok = obj.GetString("inReplyTo")
668 if !ok {
669 robj, ok := obj.GetMap("inReplyTo")
670 if ok {
671 rid, _ = robj.GetString("id")
672 }
673 }
674 convoy, _ = obj.GetString("context")
675 if convoy == "" {
676 convoy, _ = obj.GetString("conversation")
677 }
678 if ot == "Question" {
679 if what == "honk" {
680 what = "qonk"
681 }
682 content += "<ul>"
683 ans, _ := obj.GetArray("oneOf")
684 for _, ai := range ans {
685 a, ok := ai.(junk.Junk)
686 if !ok {
687 continue
688 }
689 as, _ := a.GetString("name")
690 content += "<li>" + as
691 }
692 ans, _ = obj.GetArray("anyOf")
693 for _, ai := range ans {
694 a, ok := ai.(junk.Junk)
695 if !ok {
696 continue
697 }
698 as, _ := a.GetString("name")
699 content += "<li>" + as
700 }
701 content += "</ul>"
702 }
703 if what == "honk" && rid != "" {
704 what = "tonk"
705 }
706 atts, _ := obj.GetArray("attachment")
707 for i, atti := range atts {
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" || strings.HasPrefix(mt, "image") {
727 localize = true
728 }
729 } else {
730 log.Printf("unknown attachment: %s", at)
731 }
732 if skipMedia(&xonk) {
733 localize = false
734 }
735 donk := savedonk(u, name, desc, mt, localize)
736 if donk != nil {
737 xonk.Donks = append(xonk.Donks, donk)
738 }
739 }
740 tags, _ := obj.GetArray("tag")
741 for _, tagi := range tags {
742 tag, ok := tagi.(junk.Junk)
743 if !ok {
744 continue
745 }
746 tt, _ := tag.GetString("type")
747 name, _ := tag.GetString("name")
748 desc, _ := tag.GetString("summary")
749 if desc == "" {
750 desc = name
751 }
752 if tt == "Emoji" {
753 icon, _ := tag.GetMap("icon")
754 mt, _ := icon.GetString("mediaType")
755 if mt == "" {
756 mt = "image/png"
757 }
758 u, _ := icon.GetString("url")
759 donk := savedonk(u, name, desc, mt, true)
760 if donk != nil {
761 xonk.Donks = append(xonk.Donks, donk)
762 }
763 }
764 if tt == "Hashtag" {
765 if name == "" || name == "#" {
766 // skip it
767 } else {
768 if name[0] != '#' {
769 name = "#" + name
770 }
771 xonk.Onts = append(xonk.Onts, name)
772 }
773 }
774 if tt == "Place" {
775 p := new(Place)
776 p.Name = name
777 p.Latitude, _ = tag["latitude"].(float64)
778 p.Longitude, _ = tag["longitude"].(float64)
779 p.Url, _ = tag.GetString("url")
780 xonk.Place = p
781 }
782 if tt == "Mention" {
783 m, _ := tag.GetString("href")
784 mentions = append(mentions, m)
785 }
786 }
787 starttime, ok := obj.GetString("startTime")
788 if ok {
789 start, err := time.Parse(time.RFC3339, starttime)
790 if err == nil {
791 t := new(Time)
792 t.StartTime = start
793 endtime, _ := obj.GetString("endTime")
794 t.EndTime, _ = time.Parse(time.RFC3339, endtime)
795 dura, _ := obj.GetString("duration")
796 if strings.HasPrefix(dura, "PT") {
797 dura = strings.ToLower(dura[2:])
798 d, _ := time.ParseDuration(dura)
799 t.Duration = Duration(d)
800 }
801 xonk.Time = t
802 }
803 }
804 loca, ok := obj.GetMap("location")
805 if ok {
806 tt, _ := loca.GetString("type")
807 name, _ := loca.GetString("name")
808 if tt == "Place" {
809 p := new(Place)
810 p.Name = name
811 p.Latitude, _ = loca["latitude"].(float64)
812 p.Longitude, _ = loca["longitude"].(float64)
813 p.Url, _ = loca.GetString("url")
814 xonk.Place = p
815 }
816 }
817
818 xonk.Onts = oneofakind(xonk.Onts)
819 replyobj, ok := obj.GetMap("replies")
820 if ok {
821 items, ok := replyobj.GetArray("items")
822 if !ok {
823 first, ok := replyobj.GetMap("first")
824 if ok {
825 items, _ = first.GetArray("items")
826 }
827 }
828 for _, repl := range items {
829 s, ok := repl.(string)
830 if ok {
831 replies = append(replies, s)
832 }
833 }
834 }
835
836 }
837 if originate(xid) != origin {
838 log.Printf("original sin: %s <> %s", xid, origin)
839 item.Write(os.Stdout)
840 return nil
841 }
842
843 if currenttid == "" {
844 currenttid = convoy
845 }
846
847 if len(content) > 90001 {
848 log.Printf("content too long. truncating")
849 content = content[:90001]
850 }
851
852 // init xonk
853 xonk.What = what
854 xonk.XID = xid
855 xonk.RID = rid
856 xonk.Date, _ = time.Parse(time.RFC3339, dt)
857 xonk.URL = url
858 xonk.Noise = content
859 xonk.Precis = precis
860 xonk.Format = "html"
861 xonk.Convoy = convoy
862 for _, m := range mentions {
863 if m == user.URL {
864 xonk.Whofore = 1
865 }
866 }
867 imaginate(&xonk)
868
869 if isUpdate {
870 log.Printf("something has changed! %s", xonk.XID)
871 prev := getxonk(user.ID, xonk.XID)
872 if prev == nil {
873 log.Printf("didn't find old version for update: %s", xonk.XID)
874 isUpdate = false
875 } else {
876 prev.Noise = xonk.Noise
877 prev.Precis = xonk.Precis
878 prev.Date = xonk.Date
879 prev.Donks = xonk.Donks
880 prev.Onts = xonk.Onts
881 prev.Place = xonk.Place
882 updatehonk(prev)
883 }
884 }
885 if !isUpdate && needxonk(user, &xonk) {
886 if strings.HasSuffix(convoy, "#context") {
887 // friendica...
888 if rid != "" {
889 convoy = ""
890 } else {
891 convoy = url
892 }
893 }
894 if rid != "" {
895 if needxonkid(user, rid) {
896 goingup++
897 saveonemore(rid)
898 goingup--
899 }
900 if convoy == "" {
901 xx := getxonk(user.ID, rid)
902 if xx != nil {
903 convoy = xx.Convoy
904 }
905 }
906 }
907 if convoy == "" {
908 convoy = currenttid
909 }
910 if convoy == "" {
911 convoy = "missing-" + xfiltrate()
912 currenttid = convoy
913 }
914 xonk.Convoy = convoy
915 savexonk(&xonk)
916 }
917 if goingup == 0 {
918 for _, replid := range replies {
919 if needxonkid(user, replid) {
920 log.Printf("missing a reply: %s", replid)
921 saveonemore(replid)
922 }
923 }
924 }
925 return &xonk
926 }
927
928 return xonkxonkfn(item, origin)
929}
930
931func rubadubdub(user *WhatAbout, req junk.Junk) {
932 xid, _ := req.GetString("id")
933 actor, _ := req.GetString("actor")
934 j := junk.New()
935 j["@context"] = itiswhatitis
936 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
937 j["type"] = "Accept"
938 j["actor"] = user.URL
939 j["to"] = actor
940 j["published"] = time.Now().UTC().Format(time.RFC3339)
941 j["object"] = req
942
943 deliverate(0, user.ID, actor, j.ToBytes())
944}
945
946func itakeitallback(user *WhatAbout, xid string) {
947 j := junk.New()
948 j["@context"] = itiswhatitis
949 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
950 j["type"] = "Undo"
951 j["actor"] = user.URL
952 j["to"] = xid
953 f := junk.New()
954 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
955 f["type"] = "Follow"
956 f["actor"] = user.URL
957 f["to"] = xid
958 f["object"] = xid
959 j["object"] = f
960 j["published"] = time.Now().UTC().Format(time.RFC3339)
961
962 deliverate(0, user.ID, xid, j.ToBytes())
963}
964
965func subsub(user *WhatAbout, xid string, owner string) {
966 if xid == "" {
967 log.Printf("can't subscribe to empty")
968 return
969 }
970 j := junk.New()
971 j["@context"] = itiswhatitis
972 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
973 j["type"] = "Follow"
974 j["actor"] = user.URL
975 j["to"] = owner
976 j["object"] = xid
977 j["published"] = time.Now().UTC().Format(time.RFC3339)
978
979 deliverate(0, user.ID, owner, j.ToBytes())
980}
981
982// returns activity, object
983func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
984 dt := h.Date.Format(time.RFC3339)
985 var jo junk.Junk
986 j := junk.New()
987 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
988 j["actor"] = user.URL
989 j["published"] = dt
990 if h.Public {
991 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
992 } else {
993 j["to"] = h.Audience[0]
994 }
995 if len(h.Audience) > 1 {
996 j["cc"] = h.Audience[1:]
997 }
998
999 switch h.What {
1000 case "update":
1001 fallthrough
1002 case "tonk":
1003 fallthrough
1004 case "event":
1005 fallthrough
1006 case "honk":
1007 j["type"] = "Create"
1008 if h.What == "update" {
1009 j["type"] = "Update"
1010 }
1011
1012 jo = junk.New()
1013 jo["id"] = h.XID
1014 jo["type"] = "Note"
1015 if h.What == "event" {
1016 jo["type"] = "Event"
1017 }
1018 jo["published"] = dt
1019 jo["url"] = h.XID
1020 jo["attributedTo"] = user.URL
1021 if h.RID != "" {
1022 jo["inReplyTo"] = h.RID
1023 }
1024 if h.Convoy != "" {
1025 jo["context"] = h.Convoy
1026 jo["conversation"] = h.Convoy
1027 }
1028 jo["to"] = h.Audience[0]
1029 if len(h.Audience) > 1 {
1030 jo["cc"] = h.Audience[1:]
1031 }
1032 if !h.Public {
1033 jo["directMessage"] = true
1034 }
1035 translate(h, true)
1036 h.Noise = re_memes.ReplaceAllString(h.Noise, "")
1037 jo["summary"] = html.EscapeString(h.Precis)
1038 jo["content"] = ontologize(mentionize(h.Noise))
1039 if strings.HasPrefix(h.Precis, "DZ:") {
1040 jo["sensitive"] = true
1041 }
1042
1043 var replies []string
1044 for _, reply := range h.Replies {
1045 replies = append(replies, reply.XID)
1046 }
1047 if len(replies) > 0 {
1048 jr := junk.New()
1049 jr["type"] = "Collection"
1050 jr["totalItems"] = len(replies)
1051 jr["items"] = replies
1052 jo["replies"] = jr
1053 }
1054
1055 var tags []junk.Junk
1056 for _, m := range bunchofgrapes(h.Noise) {
1057 t := junk.New()
1058 t["type"] = "Mention"
1059 t["name"] = m.who
1060 t["href"] = m.where
1061 tags = append(tags, t)
1062 }
1063 for _, o := range h.Onts {
1064 t := junk.New()
1065 t["type"] = "Hashtag"
1066 o = strings.ToLower(o)
1067 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1068 t["name"] = o
1069 tags = append(tags, t)
1070 }
1071 for _, e := range herdofemus(h.Noise) {
1072 t := junk.New()
1073 t["id"] = e.ID
1074 t["type"] = "Emoji"
1075 t["name"] = e.Name
1076 i := junk.New()
1077 i["type"] = "Image"
1078 i["mediaType"] = "image/png"
1079 i["url"] = e.ID
1080 t["icon"] = i
1081 tags = append(tags, t)
1082 }
1083 if p := h.Place; p != nil {
1084 t := junk.New()
1085 t["type"] = "Place"
1086 t["name"] = p.Name
1087 t["latitude"] = p.Latitude
1088 t["longitude"] = p.Longitude
1089 t["url"] = p.Url
1090 if h.What == "event" {
1091 jo["location"] = t
1092 } else {
1093 tags = append(tags, t)
1094 }
1095 }
1096 if len(tags) > 0 {
1097 jo["tag"] = tags
1098 }
1099 if t := h.Time; t != nil {
1100 jo["startTime"] = t.StartTime.Format(time.RFC3339)
1101 if t.Duration != 0 {
1102 jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1103 }
1104 }
1105 var atts []junk.Junk
1106 for _, d := range h.Donks {
1107 if re_emus.MatchString(d.Name) {
1108 continue
1109 }
1110 jd := junk.New()
1111 jd["mediaType"] = d.Media
1112 jd["name"] = d.Name
1113 jd["summary"] = html.EscapeString(d.Desc)
1114 jd["type"] = "Document"
1115 jd["url"] = d.URL
1116 atts = append(atts, jd)
1117 }
1118 if len(atts) > 0 {
1119 jo["attachment"] = atts
1120 }
1121 j["object"] = jo
1122 case "bonk":
1123 j["type"] = "Announce"
1124 if h.Convoy != "" {
1125 j["context"] = h.Convoy
1126 }
1127 j["object"] = h.XID
1128 case "unbonk":
1129 b := junk.New()
1130 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1131 b["type"] = "Announce"
1132 b["actor"] = user.URL
1133 if h.Convoy != "" {
1134 b["context"] = h.Convoy
1135 }
1136 b["object"] = h.XID
1137 j["type"] = "Undo"
1138 j["object"] = b
1139 case "zonk":
1140 j["type"] = "Delete"
1141 j["object"] = h.XID
1142 case "ack":
1143 j["type"] = "Read"
1144 j["object"] = h.XID
1145 case "deack":
1146 b := junk.New()
1147 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1148 b["type"] = "Read"
1149 b["actor"] = user.URL
1150 b["object"] = h.XID
1151 j["type"] = "Undo"
1152 j["object"] = b
1153 }
1154
1155 return j, jo
1156}
1157
1158var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1159 row := stmtAnyXonk.QueryRow(xid)
1160 honk := scanhonk(row)
1161 if honk == nil || !honk.Public {
1162 return nil, true
1163 }
1164 user, _ := butwhatabout(honk.Username)
1165 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1166 reversehonks(rawhonks)
1167 for _, h := range rawhonks {
1168 if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1169 honk.Replies = append(honk.Replies, h)
1170 }
1171 }
1172 donksforhonks([]*Honk{honk})
1173 _, j := jonkjonk(user, honk)
1174 j["@context"] = itiswhatitis
1175
1176 return j.ToBytes(), true
1177}})
1178
1179func gimmejonk(xid string) ([]byte, bool) {
1180 var j []byte
1181 ok := oldjonks.Get(xid, &j)
1182 return j, ok
1183}
1184
1185func honkworldwide(user *WhatAbout, honk *Honk) {
1186 jonk, _ := jonkjonk(user, honk)
1187 jonk["@context"] = itiswhatitis
1188 msg := jonk.ToBytes()
1189
1190 rcpts := make(map[string]bool)
1191 for _, a := range honk.Audience {
1192 if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1193 continue
1194 }
1195 var box *Box
1196 ok := boxofboxes.Get(a, &box)
1197 if ok && honk.Public && box.Shared != "" {
1198 rcpts["%"+box.Shared] = true
1199 } else {
1200 rcpts[a] = true
1201 }
1202 }
1203 if honk.Public {
1204 for _, h := range getdubs(user.ID) {
1205 if h.XID == user.URL {
1206 continue
1207 }
1208 var box *Box
1209 ok := boxofboxes.Get(h.XID, &box)
1210 if ok && box.Shared != "" {
1211 rcpts["%"+box.Shared] = true
1212 } else {
1213 rcpts[h.XID] = true
1214 }
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 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1276 j["icon"] = a
1277 } else {
1278 j["type"] = "Service"
1279 }
1280 k := junk.New()
1281 k["id"] = user.URL + "#key"
1282 k["owner"] = user.URL
1283 k["publicKeyPem"] = user.Key
1284 j["publicKey"] = k
1285
1286 return j.ToBytes()
1287}
1288
1289var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1290 user, err := butwhatabout(name)
1291 if err != nil {
1292 return nil, false
1293 }
1294 return junkuser(user), true
1295}, Duration: 1 * time.Minute})
1296
1297func asjonker(name string) ([]byte, bool) {
1298 var j []byte
1299 ok := oldjonkers.Get(name, &j)
1300 return j, ok
1301}
1302
1303var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1304 m := strings.Split(name, "@")
1305 if len(m) != 2 {
1306 log.Printf("bad fish name: %s", name)
1307 return "", true
1308 }
1309 row := stmtGetXonker.QueryRow(name, "fishname")
1310 var href string
1311 err := row.Scan(&href)
1312 if err == nil {
1313 return href, true
1314 }
1315 log.Printf("fishing for %s", name)
1316 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1317 if err != nil {
1318 log.Printf("failed to go fish %s: %s", name, err)
1319 return "", true
1320 }
1321 links, _ := j.GetArray("links")
1322 for _, li := range links {
1323 l, ok := li.(junk.Junk)
1324 if !ok {
1325 continue
1326 }
1327 href, _ := l.GetString("href")
1328 rel, _ := l.GetString("rel")
1329 t, _ := l.GetString("type")
1330 if rel == "self" && friendorfoe(t) {
1331 _, err := stmtSaveXonker.Exec(name, href, "fishname")
1332 if err != nil {
1333 log.Printf("error saving fishname: %s", err)
1334 }
1335 return href, true
1336 }
1337 }
1338 return href, true
1339}})
1340
1341func gofish(name string) string {
1342 if name[0] == '@' {
1343 name = name[1:]
1344 }
1345 var href string
1346 handfull.Get(name, &href)
1347 return href
1348}
1349
1350func investigate(name string) (*SomeThing, error) {
1351 if name == "" {
1352 return nil, fmt.Errorf("no name")
1353 }
1354 if name[0] == '@' {
1355 name = gofish(name)
1356 }
1357 if name == "" {
1358 return nil, fmt.Errorf("no name")
1359 }
1360 obj, err := GetJunkFast(name)
1361 if err != nil {
1362 return nil, err
1363 }
1364 return somethingabout(obj)
1365}
1366
1367func somethingabout(obj junk.Junk) (*SomeThing, error) {
1368 info := new(SomeThing)
1369 t, _ := obj.GetString("type")
1370 switch t {
1371 case "Person":
1372 fallthrough
1373 case "Organization":
1374 fallthrough
1375 case "Application":
1376 fallthrough
1377 case "Service":
1378 info.What = SomeActor
1379 case "OrderedCollection":
1380 fallthrough
1381 case "Collection":
1382 info.What = SomeCollection
1383 default:
1384 return nil, fmt.Errorf("unknown object type")
1385 }
1386 info.XID, _ = obj.GetString("id")
1387 info.Name, _ = obj.GetString("preferredUsername")
1388 if info.Name == "" {
1389 info.Name, _ = obj.GetString("name")
1390 }
1391 info.Owner, _ = obj.GetString("attributedTo")
1392 if info.Owner == "" {
1393 info.Owner = info.XID
1394 }
1395 return info, nil
1396}