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