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