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