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