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