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 xonk := xonkxonk(user, obj, origin)
347 if xonk != nil {
348 savexonk(xonk)
349 }
350 }
351 }
352}
353
354func peeppeep() {
355 user, _ := butwhatabout("htest")
356 honkers := gethonkers(user.ID)
357 for _, f := range honkers {
358 if f.Flavor != "peep" {
359 continue
360 }
361 log.Printf("getting updates: %s", f.XID)
362 box, err := getboxes(f.XID)
363 if err != nil {
364 log.Printf("error getting outbox: %s", err)
365 continue
366 }
367 gimmexonks(user, box.Out)
368 }
369}
370func whosthere(xid string) ([]string, string) {
371 obj, err := GetJunk(xid)
372 if err != nil {
373 log.Printf("error getting remote xonk: %s", err)
374 return nil, ""
375 }
376 convoy, _ := obj.GetString("context")
377 if convoy == "" {
378 convoy, _ = obj.GetString("conversation")
379 }
380 return newphone(nil, obj), convoy
381}
382
383func newphone(a []string, obj junk.Junk) []string {
384 for _, addr := range []string{"to", "cc", "attributedTo"} {
385 who, _ := obj.GetString(addr)
386 if who != "" {
387 a = append(a, who)
388 }
389 whos, _ := obj.GetArray(addr)
390 for _, w := range whos {
391 who, _ := w.(string)
392 if who != "" {
393 a = append(a, who)
394 }
395 }
396 }
397 return a
398}
399
400func extractattrto(obj junk.Junk) string {
401 who, _ := obj.GetString("attributedTo")
402 if who != "" {
403 return who
404 }
405 o, ok := obj.GetMap("attributedTo")
406 if ok {
407 id, ok := o.GetString("id")
408 if ok {
409 return id
410 }
411 }
412 arr, _ := obj.GetArray("attributedTo")
413 for _, a := range arr {
414 o, ok := a.(junk.Junk)
415 if ok {
416 t, _ := o.GetString("type")
417 id, _ := o.GetString("id")
418 if t == "Person" || t == "" {
419 return id
420 }
421 }
422 }
423 return ""
424}
425
426func consumeactivity(user *WhatAbout, j junk.Junk, origin string) {
427 xonk := xonkxonk(user, j, origin)
428 if xonk != nil {
429 savexonk(xonk)
430 }
431}
432
433func xonkxonk(user *WhatAbout, item junk.Junk, origin string) *Honk {
434 depth := 0
435 maxdepth := 10
436 currenttid := ""
437 var xonkxonkfn func(item junk.Junk, origin string) *Honk
438
439 saveoneup := func(xid string) {
440 log.Printf("getting oneup: %s", xid)
441 if depth >= maxdepth {
442 log.Printf("in too deep")
443 return
444 }
445 obj, err := GetJunkHardMode(xid)
446 if err != nil {
447 log.Printf("error getting oneup: %s: %s", xid, err)
448 return
449 }
450 depth++
451 xonk := xonkxonkfn(obj, originate(xid))
452 if xonk != nil {
453 savexonk(xonk)
454 }
455 depth--
456 }
457
458 xonkxonkfn = func(item junk.Junk, origin string) *Honk {
459 // id, _ := item.GetString( "id")
460 what, _ := item.GetString("type")
461 dt, _ := item.GetString("published")
462
463 var err error
464 var xid, rid, url, content, precis, convoy string
465 var obj junk.Junk
466 var ok bool
467 isUpdate := false
468 switch what {
469 case "Delete":
470 obj, ok = item.GetMap("object")
471 if ok {
472 xid, _ = obj.GetString("id")
473 } else {
474 xid, _ = item.GetString("object")
475 }
476 if xid == "" {
477 return nil
478 }
479 if originate(xid) != origin {
480 log.Printf("forged delete: %s", xid)
481 return nil
482 }
483 log.Printf("eradicating %s", xid)
484 eradicatexonk(user.ID, xid)
485 return nil
486 case "Tombstone":
487 xid, _ = item.GetString("id")
488 if xid == "" {
489 return nil
490 }
491 if originate(xid) != origin {
492 log.Printf("forged delete: %s", xid)
493 return nil
494 }
495 log.Printf("eradicating %s", xid)
496 eradicatexonk(user.ID, xid)
497 return nil
498 case "Announce":
499 obj, ok = item.GetMap("object")
500 if ok {
501 xid, _ = obj.GetString("id")
502 } else {
503 xid, _ = item.GetString("object")
504 }
505 if !needxonkid(user, xid) {
506 return nil
507 }
508 log.Printf("getting bonk: %s", xid)
509 obj, err = GetJunkHardMode(xid)
510 if err != nil {
511 log.Printf("error getting bonk: %s: %s", xid, err)
512 }
513 origin = originate(xid)
514 what = "bonk"
515 case "Update":
516 isUpdate = true
517 fallthrough
518 case "Create":
519 obj, ok = item.GetMap("object")
520 if !ok {
521 xid, _ = item.GetString("object")
522 log.Printf("getting created honk: %s", xid)
523 obj, err = GetJunkHardMode(xid)
524 if err != nil {
525 log.Printf("error getting creation: %s", err)
526 }
527 }
528 what = "honk"
529 case "Read":
530 xid, ok = item.GetString("object")
531 if ok {
532 if !needxonkid(user, xid) {
533 log.Printf("don't need read obj: %s", xid)
534 return nil
535 }
536 obj, err = GetJunkHardMode(xid)
537 if err != nil {
538 log.Printf("error getting read: %s", err)
539 return nil
540 }
541 return xonkxonkfn(obj, originate(xid))
542 }
543 return nil
544 case "Video":
545 fallthrough
546 case "Question":
547 fallthrough
548 case "Note":
549 fallthrough
550 case "Article":
551 fallthrough
552 case "Page":
553 obj = item
554 what = "honk"
555 default:
556 log.Printf("unknown activity: %s", what)
557 fd, _ := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
558 item.Write(fd)
559 io.WriteString(fd, "\n")
560 fd.Close()
561 return nil
562 }
563
564 var xonk Honk
565 // early init
566 xonk.UserID = user.ID
567 xonk.Honker, _ = item.GetString("actor")
568 if obj != nil {
569 if xonk.Honker == "" {
570 xonk.Honker = extractattrto(obj)
571 }
572 xonk.Oonker = extractattrto(obj)
573 if xonk.Oonker == xonk.Honker {
574 xonk.Oonker = ""
575 }
576 xonk.Audience = newphone(nil, obj)
577 }
578 xonk.Audience = append(xonk.Audience, xonk.Honker)
579 xonk.Audience = oneofakind(xonk.Audience)
580 for _, a := range xonk.Audience {
581 if a == user.URL {
582 xonk.Whofore = 1
583 }
584 }
585
586 if obj != nil {
587 ot, _ := obj.GetString("type")
588 url, _ = obj.GetString("url")
589 dt2, ok := obj.GetString("published")
590 if ok {
591 dt = dt2
592 }
593 xid, _ = obj.GetString("id")
594 precis, _ = obj.GetString("summary")
595 if precis == "" {
596 precis, _ = obj.GetString("name")
597 }
598 content, _ = obj.GetString("content")
599 if !strings.HasPrefix(content, "<p>") {
600 content = "<p>" + content
601 }
602 sens, _ := obj["sensitive"].(bool)
603 if sens && precis == "" {
604 precis = "unspecified horror"
605 }
606 rid, ok = obj.GetString("inReplyTo")
607 if !ok {
608 robj, ok := obj.GetMap("inReplyTo")
609 if ok {
610 rid, _ = robj.GetString("id")
611 }
612 }
613 convoy, _ = obj.GetString("context")
614 if strings.HasSuffix(convoy, "#context") &&
615 originate(convoy) != originate(xid) {
616 // friendica...
617 convoy = ""
618 }
619 if convoy == "" {
620 convoy, _ = obj.GetString("conversation")
621 }
622 if ot == "Question" {
623 if what == "honk" {
624 what = "qonk"
625 }
626 content += "<ul>"
627 ans, _ := obj.GetArray("oneOf")
628 for _, ai := range ans {
629 a, ok := ai.(junk.Junk)
630 if !ok {
631 continue
632 }
633 as, _ := a.GetString("name")
634 content += "<li>" + as
635 }
636 ans, _ = obj.GetArray("anyOf")
637 for _, ai := range ans {
638 a, ok := ai.(junk.Junk)
639 if !ok {
640 continue
641 }
642 as, _ := a.GetString("name")
643 content += "<li>" + as
644 }
645 content += "</ul>"
646 }
647 if what == "honk" && rid != "" {
648 what = "tonk"
649 }
650 atts, _ := obj.GetArray("attachment")
651 for i, atti := range atts {
652 att, ok := atti.(junk.Junk)
653 if !ok {
654 continue
655 }
656 at, _ := att.GetString("type")
657 mt, _ := att.GetString("mediaType")
658 u, _ := att.GetString("url")
659 name, _ := att.GetString("name")
660 desc, _ := att.GetString("summary")
661 if desc == "" {
662 desc = name
663 }
664 localize := false
665 if i > 4 {
666 log.Printf("excessive attachment: %s", at)
667 } else if at == "Document" || at == "Image" {
668 mt = strings.ToLower(mt)
669 log.Printf("attachment: %s %s", mt, u)
670 if mt == "text/plain" || strings.HasPrefix(mt, "image") {
671 localize = true
672 }
673 } else {
674 log.Printf("unknown attachment: %s", at)
675 }
676 if skipMedia(&xonk) {
677 localize = false
678 }
679 donk := savedonk(u, name, desc, mt, localize)
680 if donk != nil {
681 xonk.Donks = append(xonk.Donks, donk)
682 }
683 }
684 tags, _ := obj.GetArray("tag")
685 for _, tagi := range tags {
686 tag, ok := tagi.(junk.Junk)
687 if !ok {
688 continue
689 }
690 tt, _ := tag.GetString("type")
691 name, _ := tag.GetString("name")
692 desc, _ := tag.GetString("summary")
693 if desc == "" {
694 desc = name
695 }
696 if tt == "Emoji" {
697 icon, _ := tag.GetMap("icon")
698 mt, _ := icon.GetString("mediaType")
699 if mt == "" {
700 mt = "image/png"
701 }
702 u, _ := icon.GetString("url")
703 donk := savedonk(u, name, desc, mt, true)
704 if donk != nil {
705 xonk.Donks = append(xonk.Donks, donk)
706 }
707 }
708 if tt == "Hashtag" {
709 if len(name) > 1 && name[0] == '#' {
710 xonk.Onts = append(xonk.Onts, name)
711 } else {
712 log.Printf("bogus hashtag name: %s", name)
713 }
714 }
715 if tt == "Place" {
716 p := new(Place)
717 p.Name = name
718 p.Latitude, _ = tag["latitude"].(float64)
719 p.Longitude, _ = tag["longitude"].(float64)
720 p.Url, _ = tag.GetString("url")
721 xonk.Place = p
722 }
723 }
724 xonk.Onts = oneofakind(xonk.Onts)
725 }
726 if originate(xid) != origin {
727 log.Printf("original sin: %s <> %s", xid, origin)
728 item.Write(os.Stdout)
729 return nil
730 }
731
732 if currenttid == "" {
733 currenttid = convoy
734 }
735
736 // init xonk
737 xonk.What = what
738 xonk.XID = xid
739 xonk.RID = rid
740 xonk.Date, _ = time.Parse(time.RFC3339, dt)
741 xonk.URL = url
742 xonk.Noise = content
743 xonk.Precis = precis
744 xonk.Format = "html"
745
746 if isUpdate {
747 log.Printf("something has changed! %s", xonk.XID)
748 prev := getxonk(user.ID, xonk.XID)
749 if prev == nil {
750 log.Printf("didn't find old version for update: %s", xonk.XID)
751 return nil
752 }
753 prev.Noise = xonk.Noise
754 prev.Precis = xonk.Precis
755 prev.Date = xonk.Date
756 prev.Donks = xonk.Donks
757 prev.Onts = xonk.Onts
758 prev.Place = xonk.Place
759 updatehonk(prev)
760 return nil
761 }
762
763 if needxonk(user, &xonk) {
764 if rid != "" {
765 if needxonkid(user, rid) {
766 saveoneup(rid)
767 }
768 if convoy == "" {
769 xx := getxonk(user.ID, rid)
770 if xx != nil {
771 convoy = xx.Convoy
772 }
773 }
774 }
775 if convoy == "" {
776 convoy = currenttid
777 }
778 xonk.Convoy = convoy
779 return &xonk
780 }
781 return nil
782 }
783
784 return xonkxonkfn(item, origin)
785}
786
787func rubadubdub(user *WhatAbout, req junk.Junk) {
788 xid, _ := req.GetString("id")
789 actor, _ := req.GetString("actor")
790 j := junk.New()
791 j["@context"] = itiswhatitis
792 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
793 j["type"] = "Accept"
794 j["actor"] = user.URL
795 j["to"] = actor
796 j["published"] = time.Now().UTC().Format(time.RFC3339)
797 j["object"] = req
798
799 var buf bytes.Buffer
800 j.Write(&buf)
801 msg := buf.Bytes()
802
803 deliverate(0, user.Name, actor, msg)
804}
805
806func itakeitallback(user *WhatAbout, xid string) {
807 j := junk.New()
808 j["@context"] = itiswhatitis
809 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
810 j["type"] = "Undo"
811 j["actor"] = user.URL
812 j["to"] = xid
813 f := junk.New()
814 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
815 f["type"] = "Follow"
816 f["actor"] = user.URL
817 f["to"] = xid
818 f["object"] = xid
819 j["object"] = f
820 j["published"] = time.Now().UTC().Format(time.RFC3339)
821
822 var buf bytes.Buffer
823 j.Write(&buf)
824 msg := buf.Bytes()
825
826 deliverate(0, user.Name, xid, msg)
827}
828
829func subsub(user *WhatAbout, xid string) {
830 j := junk.New()
831 j["@context"] = itiswhatitis
832 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
833 j["type"] = "Follow"
834 j["actor"] = user.URL
835 j["to"] = xid
836 j["object"] = xid
837 j["published"] = time.Now().UTC().Format(time.RFC3339)
838
839 var buf bytes.Buffer
840 j.Write(&buf)
841 msg := buf.Bytes()
842
843 deliverate(0, user.Name, xid, msg)
844}
845
846// returns activity, object
847func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
848 dt := h.Date.Format(time.RFC3339)
849 var jo junk.Junk
850 j := junk.New()
851 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
852 j["actor"] = user.URL
853 j["published"] = dt
854 if h.Public {
855 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
856 } else {
857 j["to"] = h.Audience[0]
858 }
859 if len(h.Audience) > 1 {
860 j["cc"] = h.Audience[1:]
861 }
862
863 switch h.What {
864 case "update":
865 fallthrough
866 case "tonk":
867 fallthrough
868 case "honk":
869 if h.What == "update" {
870 j["type"] = "Update"
871 } else {
872 j["type"] = "Create"
873 }
874
875 jo = junk.New()
876 jo["id"] = h.XID
877 jo["type"] = "Note"
878 jo["published"] = dt
879 jo["url"] = h.XID
880 jo["attributedTo"] = user.URL
881 if h.RID != "" {
882 jo["inReplyTo"] = h.RID
883 }
884 if h.Convoy != "" {
885 jo["context"] = h.Convoy
886 jo["conversation"] = h.Convoy
887 }
888 jo["to"] = h.Audience[0]
889 if len(h.Audience) > 1 {
890 jo["cc"] = h.Audience[1:]
891 }
892 if !h.Public {
893 jo["directMessage"] = true
894 }
895 translate(h)
896 h.Noise = re_memes.ReplaceAllString(h.Noise, "")
897 jo["summary"] = h.Precis
898 jo["content"] = ontologize(mentionize(h.Noise))
899 if strings.HasPrefix(h.Precis, "DZ:") {
900 jo["sensitive"] = true
901 }
902
903 var replies []string
904 for _, reply := range h.Replies {
905 replies = append(replies, reply.XID)
906 }
907 if len(replies) > 0 {
908 jr := junk.New()
909 jr["type"] = "Collection"
910 jr["totalItems"] = len(replies)
911 jr["items"] = replies
912 jo["replies"] = jr
913 }
914
915 var tags []junk.Junk
916 g := bunchofgrapes(h.Noise)
917 for _, m := range g {
918 t := junk.New()
919 t["type"] = "Mention"
920 t["name"] = m.who
921 t["href"] = m.where
922 tags = append(tags, t)
923 }
924 for _, o := range h.Onts {
925 t := junk.New()
926 t["type"] = "Hashtag"
927 o = strings.ToLower(o)
928 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
929 t["name"] = o
930 tags = append(tags, t)
931 }
932 herd := herdofemus(h.Noise)
933 for _, e := range herd {
934 t := junk.New()
935 t["id"] = e.ID
936 t["type"] = "Emoji"
937 t["name"] = e.Name
938 i := junk.New()
939 i["type"] = "Image"
940 i["mediaType"] = "image/png"
941 i["url"] = e.ID
942 t["icon"] = i
943 tags = append(tags, t)
944 }
945 if p := h.Place; p != nil {
946 t := junk.New()
947 t["type"] = "Place"
948 t["name"] = p.Name
949 t["latitude"] = p.Latitude
950 t["longitude"] = p.Longitude
951 t["url"] = p.Url
952 tags = append(tags, t)
953 }
954 if len(tags) > 0 {
955 jo["tag"] = tags
956 }
957 var atts []junk.Junk
958 for _, d := range h.Donks {
959 if re_emus.MatchString(d.Name) {
960 continue
961 }
962 jd := junk.New()
963 jd["mediaType"] = d.Media
964 jd["name"] = d.Name
965 jd["summary"] = d.Desc
966 jd["type"] = "Document"
967 jd["url"] = d.URL
968 atts = append(atts, jd)
969 }
970 if len(atts) > 0 {
971 jo["attachment"] = atts
972 }
973 j["object"] = jo
974 case "bonk":
975 j["type"] = "Announce"
976 if h.Convoy != "" {
977 j["context"] = h.Convoy
978 }
979 j["object"] = h.XID
980 case "unbonk":
981 b := junk.New()
982 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
983 b["type"] = "Announce"
984 b["actor"] = user.URL
985 if h.Convoy != "" {
986 b["context"] = h.Convoy
987 }
988 b["object"] = h.XID
989 j["type"] = "Undo"
990 j["object"] = b
991 case "zonk":
992 j["type"] = "Delete"
993 j["object"] = h.XID
994 case "ack":
995 j["type"] = "Read"
996 j["object"] = h.XID
997 case "deack":
998 b := junk.New()
999 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1000 b["type"] = "Read"
1001 b["actor"] = user.URL
1002 b["object"] = h.XID
1003 j["type"] = "Undo"
1004 j["object"] = b
1005 }
1006
1007 return j, jo
1008}
1009
1010func honkworldwide(user *WhatAbout, honk *Honk) {
1011 jonk, _ := jonkjonk(user, honk)
1012 jonk["@context"] = itiswhatitis
1013 var buf bytes.Buffer
1014 jonk.Write(&buf)
1015 msg := buf.Bytes()
1016
1017 rcpts := make(map[string]bool)
1018 for _, a := range honk.Audience {
1019 if a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1020 continue
1021 }
1022 box, _ := getboxes(a)
1023 if box != nil && honk.Public && box.Shared != "" {
1024 rcpts["%"+box.Shared] = true
1025 } else {
1026 rcpts[a] = true
1027 }
1028 }
1029 if honk.Public {
1030 for _, f := range getdubs(user.ID) {
1031 if f.XID == user.URL {
1032 continue
1033 }
1034 box, _ := getboxes(f.XID)
1035 if box != nil && box.Shared != "" {
1036 rcpts["%"+box.Shared] = true
1037 } else {
1038 rcpts[f.XID] = true
1039 }
1040 }
1041 }
1042 for a := range rcpts {
1043 go deliverate(0, user.Name, a, msg)
1044 }
1045}
1046
1047func asjonker(user *WhatAbout) junk.Junk {
1048 about := obfusbreak(user.About)
1049
1050 j := junk.New()
1051 j["@context"] = itiswhatitis
1052 j["id"] = user.URL
1053 j["type"] = "Person"
1054 j["inbox"] = user.URL + "/inbox"
1055 j["outbox"] = user.URL + "/outbox"
1056 j["followers"] = user.URL + "/followers"
1057 j["following"] = user.URL + "/following"
1058 j["name"] = user.Display
1059 j["preferredUsername"] = user.Name
1060 j["summary"] = about
1061 j["url"] = user.URL
1062 a := junk.New()
1063 a["type"] = "Image"
1064 a["mediaType"] = "image/png"
1065 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1066 j["icon"] = a
1067 k := junk.New()
1068 k["id"] = user.URL + "#key"
1069 k["owner"] = user.URL
1070 k["publicKeyPem"] = user.Key
1071 j["publicKey"] = k
1072
1073 return j
1074}
1075
1076var handfull = make(map[string]string)
1077var handlock sync.Mutex
1078
1079func gofish(name string) string {
1080 if name[0] == '@' {
1081 name = name[1:]
1082 }
1083 m := strings.Split(name, "@")
1084 if len(m) != 2 {
1085 log.Printf("bad fish name: %s", name)
1086 return ""
1087 }
1088 handlock.Lock()
1089 ref, ok := handfull[name]
1090 handlock.Unlock()
1091 if ok {
1092 return ref
1093 }
1094 row := stmtGetXonker.QueryRow(name, "fishname")
1095 var href string
1096 err := row.Scan(&href)
1097 if err == nil {
1098 handlock.Lock()
1099 handfull[name] = href
1100 handlock.Unlock()
1101 return href
1102 }
1103 log.Printf("fishing for %s", name)
1104 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1105 if err != nil {
1106 log.Printf("failed to go fish %s: %s", name, err)
1107 handlock.Lock()
1108 handfull[name] = ""
1109 handlock.Unlock()
1110 return ""
1111 }
1112 links, _ := j.GetArray("links")
1113 for _, li := range links {
1114 l, ok := li.(junk.Junk)
1115 if !ok {
1116 continue
1117 }
1118 href, _ := l.GetString("href")
1119 rel, _ := l.GetString("rel")
1120 t, _ := l.GetString("type")
1121 if rel == "self" && friendorfoe(t) {
1122 _, err := stmtSaveXonker.Exec(name, href, "fishname")
1123 if err != nil {
1124 log.Printf("error saving fishname: %s", err)
1125 }
1126 handlock.Lock()
1127 handfull[name] = href
1128 handlock.Unlock()
1129 return href
1130 }
1131 }
1132 handlock.Lock()
1133 handfull[name] = ""
1134 handlock.Unlock()
1135 return ""
1136}
1137
1138func isactor(t string) bool {
1139 switch t {
1140 case "Person":
1141 case "Organization":
1142 case "Application":
1143 case "Service":
1144 default:
1145 return false
1146 }
1147 return true
1148}
1149
1150func investigate(name string) (*Honker, error) {
1151 if name == "" {
1152 return nil, fmt.Errorf("no name")
1153 }
1154 if name[0] == '@' {
1155 name = gofish(name)
1156 }
1157 if name == "" {
1158 return nil, fmt.Errorf("no name")
1159 }
1160 log.Printf("digging up some info on %s", name)
1161 obj, err := GetJunkFast(name)
1162 if err != nil {
1163 log.Printf("error investigating honker: %s", err)
1164 return nil, err
1165 }
1166 t, _ := obj.GetString("type")
1167 if !isactor(t) {
1168 log.Printf("it's not a person! %s", name)
1169 return nil, err
1170 }
1171 xid, _ := obj.GetString("id")
1172 handle, _ := obj.GetString("preferredUsername")
1173 return &Honker{XID: xid, Handle: handle}, nil
1174}