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 res, err := stmtSaveFile.Exec(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, _ = res.LastInsertId()
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.Honker, _ = item.GetString("actor")
546 if obj != nil {
547 if xonk.Honker == "" {
548 xonk.Honker = extractattrto(obj)
549 }
550 xonk.Oonker = extractattrto(obj)
551 if xonk.Oonker == xonk.Honker {
552 xonk.Oonker = ""
553 }
554 xonk.Audience = newphone(nil, obj)
555 }
556 xonk.Audience = append(xonk.Audience, xonk.Honker)
557 xonk.Audience = oneofakind(xonk.Audience)
558 for _, a := range xonk.Audience {
559 if a == user.URL {
560 xonk.Whofore = 1
561 }
562 }
563
564 if obj != nil {
565 ot, _ := obj.GetString("type")
566 url, _ = obj.GetString("url")
567 dt2, ok := obj.GetString("published")
568 if ok {
569 dt = dt2
570 }
571 if ot == "Tombstone" {
572 xid, _ = obj.GetString("id")
573 } else {
574 xid, _ = obj.GetString("id")
575 precis, _ = obj.GetString("summary")
576 if precis == "" {
577 precis, _ = obj.GetString("name")
578 }
579 content, _ = obj.GetString("content")
580 if !strings.HasPrefix(content, "<p>") {
581 content = "<p>" + content
582 }
583 sens, _ := obj["sensitive"].(bool)
584 if sens && precis == "" {
585 precis = "unspecified horror"
586 }
587 rid, ok = obj.GetString("inReplyTo")
588 if !ok {
589 robj, ok := obj.GetMap("inReplyTo")
590 if ok {
591 rid, _ = robj.GetString("id")
592 }
593 }
594 convoy, _ = obj.GetString("context")
595 if strings.HasSuffix(convoy, "#context") &&
596 originate(convoy) != originate(xid) {
597 // friendica...
598 convoy = ""
599 }
600 if convoy == "" {
601 convoy, _ = obj.GetString("conversation")
602 }
603 if ot == "Question" {
604 if what == "honk" {
605 what = "qonk"
606 }
607 content += "<ul>"
608 ans, _ := obj.GetArray("oneOf")
609 for _, ai := range ans {
610 a, ok := ai.(junk.Junk)
611 if !ok {
612 continue
613 }
614 as, _ := a.GetString("name")
615 content += "<li>" + as
616 }
617 ans, _ = obj.GetArray("anyOf")
618 for _, ai := range ans {
619 a, ok := ai.(junk.Junk)
620 if !ok {
621 continue
622 }
623 as, _ := a.GetString("name")
624 content += "<li>" + as
625 }
626 content += "</ul>"
627 }
628 if what == "honk" && rid != "" {
629 what = "tonk"
630 }
631 }
632 atts, _ := obj.GetArray("attachment")
633 for i, atti := range atts {
634 att, ok := atti.(junk.Junk)
635 if !ok {
636 continue
637 }
638 at, _ := att.GetString("type")
639 mt, _ := att.GetString("mediaType")
640 u, _ := att.GetString("url")
641 name, _ := att.GetString("name")
642 desc, _ := att.GetString("summary")
643 if desc == "" {
644 desc = name
645 }
646 localize := false
647 if i > 4 {
648 log.Printf("excessive attachment: %s", at)
649 } else if at == "Document" || at == "Image" {
650 mt = strings.ToLower(mt)
651 log.Printf("attachment: %s %s", mt, u)
652 if mt == "text/plain" || strings.HasPrefix(mt, "image") {
653 localize = true
654 }
655 } else {
656 log.Printf("unknown attachment: %s", at)
657 }
658 donk := savedonk(u, name, desc, mt, localize)
659 if donk != nil {
660 xonk.Donks = append(xonk.Donks, donk)
661 }
662 }
663 tags, _ := obj.GetArray("tag")
664 for _, tagi := range tags {
665 tag, ok := tagi.(junk.Junk)
666 if !ok {
667 continue
668 }
669 tt, _ := tag.GetString("type")
670 name, _ := tag.GetString("name")
671 desc, _ := tag.GetString("summary")
672 if desc == "" {
673 desc = name
674 }
675 if tt == "Emoji" {
676 icon, _ := tag.GetMap("icon")
677 mt, _ := icon.GetString("mediaType")
678 if mt == "" {
679 mt = "image/png"
680 }
681 u, _ := icon.GetString("url")
682 donk := savedonk(u, name, desc, mt, true)
683 if donk != nil {
684 xonk.Donks = append(xonk.Donks, donk)
685 }
686 }
687 if tt == "Hashtag" {
688 if len(name) > 1 && name[0] == '#' {
689 xonk.Onts = append(xonk.Onts, name)
690 } else {
691 log.Printf("bogus hashtag name: %s", name)
692 }
693 }
694 if tt == "Place" {
695 p := new(Place)
696 p.Name = name
697 p.Latitude, _ = tag["latitude"].(float64)
698 p.Longitude, _ = tag["longitude"].(float64)
699 log.Printf("place: %v", p)
700 xonk.Place = p
701 }
702 }
703 xonk.Onts = oneofakind(xonk.Onts)
704 }
705 if originate(xid) != origin {
706 log.Printf("original sin: %s <> %s", xid, origin)
707 item.Write(os.Stdout)
708 return nil
709 }
710
711 if currenttid == "" {
712 currenttid = convoy
713 }
714
715 // init xonk
716 xonk.UserID = user.ID
717 xonk.What = what
718 xonk.XID = xid
719 xonk.RID = rid
720 xonk.Date, _ = time.Parse(time.RFC3339, dt)
721 xonk.URL = url
722 xonk.Noise = content
723 xonk.Precis = precis
724 xonk.Format = "html"
725
726 if isUpdate {
727 log.Printf("something has changed! %s", xonk.XID)
728 prev := getxonk(user.ID, xonk.XID)
729 if prev == nil {
730 log.Printf("didn't find old version for update: %s", xonk.XID)
731 return nil
732 }
733 prev.Noise = xonk.Noise
734 prev.Precis = xonk.Precis
735 prev.Date = xonk.Date
736 prev.Donks = xonk.Donks
737 prev.Onts = xonk.Onts
738 updatehonk(prev)
739 return nil
740 }
741
742 if needxonk(user, &xonk) {
743 if rid != "" {
744 if needxonkid(user, rid) {
745 saveoneup(rid)
746 }
747 if convoy == "" {
748 xx := getxonk(user.ID, rid)
749 if xx != nil {
750 convoy = xx.Convoy
751 }
752 }
753 }
754 if convoy == "" {
755 convoy = currenttid
756 }
757 xonk.Convoy = convoy
758 return &xonk
759 }
760 return nil
761 }
762
763 return xonkxonkfn(item, origin)
764}
765
766func rubadubdub(user *WhatAbout, req junk.Junk) {
767 xid, _ := req.GetString("id")
768 actor, _ := req.GetString("actor")
769 j := junk.New()
770 j["@context"] = itiswhatitis
771 j["id"] = user.URL + "/dub/" + url.QueryEscape(xid)
772 j["type"] = "Accept"
773 j["actor"] = user.URL
774 j["to"] = actor
775 j["published"] = time.Now().UTC().Format(time.RFC3339)
776 j["object"] = req
777
778 var buf bytes.Buffer
779 j.Write(&buf)
780 msg := buf.Bytes()
781
782 deliverate(0, user.Name, actor, msg)
783}
784
785func itakeitallback(user *WhatAbout, xid string) {
786 j := junk.New()
787 j["@context"] = itiswhatitis
788 j["id"] = user.URL + "/unsub/" + url.QueryEscape(xid)
789 j["type"] = "Undo"
790 j["actor"] = user.URL
791 j["to"] = xid
792 f := junk.New()
793 f["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
794 f["type"] = "Follow"
795 f["actor"] = user.URL
796 f["to"] = xid
797 f["object"] = xid
798 j["object"] = f
799 j["published"] = time.Now().UTC().Format(time.RFC3339)
800
801 var buf bytes.Buffer
802 j.Write(&buf)
803 msg := buf.Bytes()
804
805 deliverate(0, user.Name, xid, msg)
806}
807
808func subsub(user *WhatAbout, xid string) {
809 j := junk.New()
810 j["@context"] = itiswhatitis
811 j["id"] = user.URL + "/sub/" + url.QueryEscape(xid)
812 j["type"] = "Follow"
813 j["actor"] = user.URL
814 j["to"] = xid
815 j["object"] = xid
816 j["published"] = time.Now().UTC().Format(time.RFC3339)
817
818 var buf bytes.Buffer
819 j.Write(&buf)
820 msg := buf.Bytes()
821
822 deliverate(0, user.Name, xid, msg)
823}
824
825// returns activity, object
826func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
827 dt := h.Date.Format(time.RFC3339)
828 var jo junk.Junk
829 j := junk.New()
830 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
831 j["actor"] = user.URL
832 j["published"] = dt
833 if h.Public {
834 j["to"] = []string{h.Audience[0], user.URL + "/followers"}
835 } else {
836 j["to"] = h.Audience[0]
837 }
838 if len(h.Audience) > 1 {
839 j["cc"] = h.Audience[1:]
840 }
841
842 switch h.What {
843 case "update":
844 fallthrough
845 case "tonk":
846 fallthrough
847 case "honk":
848 if h.What == "update" {
849 j["type"] = "Update"
850 } else {
851 j["type"] = "Create"
852 }
853
854 jo = junk.New()
855 jo["id"] = h.XID
856 jo["type"] = "Note"
857 jo["published"] = dt
858 jo["url"] = h.XID
859 jo["attributedTo"] = user.URL
860 if h.RID != "" {
861 jo["inReplyTo"] = h.RID
862 }
863 if h.Convoy != "" {
864 jo["context"] = h.Convoy
865 jo["conversation"] = h.Convoy
866 }
867 jo["to"] = h.Audience[0]
868 if len(h.Audience) > 1 {
869 jo["cc"] = h.Audience[1:]
870 }
871 if !h.Public {
872 jo["directMessage"] = true
873 }
874 translate(h)
875 h.Noise = re_memes.ReplaceAllString(h.Noise, "")
876 jo["summary"] = h.Precis
877 jo["content"] = ontologize(mentionize(h.Noise))
878 if strings.HasPrefix(h.Precis, "DZ:") {
879 jo["sensitive"] = true
880 }
881
882 var replies []string
883 for _, reply := range h.Replies {
884 replies = append(replies, reply.XID)
885 }
886 if len(replies) > 0 {
887 jr := junk.New()
888 jr["type"] = "Collection"
889 jr["totalItems"] = len(replies)
890 jr["items"] = replies
891 jo["replies"] = jr
892 }
893
894 var tags []junk.Junk
895 g := bunchofgrapes(h.Noise)
896 for _, m := range g {
897 t := junk.New()
898 t["type"] = "Mention"
899 t["name"] = m.who
900 t["href"] = m.where
901 tags = append(tags, t)
902 }
903 for _, o := range h.Onts {
904 t := junk.New()
905 t["type"] = "Hashtag"
906 o = strings.ToLower(o)
907 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
908 t["name"] = o
909 tags = append(tags, t)
910 }
911 herd := herdofemus(h.Noise)
912 for _, e := range herd {
913 t := junk.New()
914 t["id"] = e.ID
915 t["type"] = "Emoji"
916 t["name"] = e.Name
917 i := junk.New()
918 i["type"] = "Image"
919 i["mediaType"] = "image/png"
920 i["url"] = e.ID
921 t["icon"] = i
922 tags = append(tags, t)
923 }
924 if p := h.Place; p != nil {
925 t := junk.New()
926 t["type"] = "Place"
927 t["name"] = p.Name
928 t["latitude"] = p.Latitude
929 t["longitude"] = p.Longitude
930 tags = append(tags, t)
931 }
932 if len(tags) > 0 {
933 jo["tag"] = tags
934 }
935 var atts []junk.Junk
936 for _, d := range h.Donks {
937 if re_emus.MatchString(d.Name) {
938 continue
939 }
940 jd := junk.New()
941 jd["mediaType"] = d.Media
942 jd["name"] = d.Name
943 jd["summary"] = d.Desc
944 jd["type"] = "Document"
945 jd["url"] = d.URL
946 atts = append(atts, jd)
947 }
948 if len(atts) > 0 {
949 jo["attachment"] = atts
950 }
951 j["object"] = jo
952 case "bonk":
953 j["type"] = "Announce"
954 if h.Convoy != "" {
955 j["context"] = h.Convoy
956 }
957 j["object"] = h.XID
958 case "unbonk":
959 b := junk.New()
960 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
961 b["type"] = "Announce"
962 b["actor"] = user.URL
963 if h.Convoy != "" {
964 b["context"] = h.Convoy
965 }
966 b["object"] = h.XID
967 j["type"] = "Undo"
968 j["object"] = b
969 case "zonk":
970 j["type"] = "Delete"
971 j["object"] = h.XID
972 case "ack":
973 j["type"] = "Read"
974 j["object"] = h.XID
975 case "deack":
976 b := junk.New()
977 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
978 b["type"] = "Read"
979 b["actor"] = user.URL
980 b["object"] = h.XID
981 j["type"] = "Undo"
982 j["object"] = b
983 }
984
985 return j, jo
986}
987
988func honkworldwide(user *WhatAbout, honk *Honk) {
989 jonk, _ := jonkjonk(user, honk)
990 jonk["@context"] = itiswhatitis
991 var buf bytes.Buffer
992 jonk.Write(&buf)
993 msg := buf.Bytes()
994
995 rcpts := make(map[string]bool)
996 for _, a := range honk.Audience {
997 if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
998 box, _ := getboxes(a)
999 if box != nil && honk.Public && box.Shared != "" {
1000 rcpts["%"+box.Shared] = true
1001 } else {
1002 rcpts[a] = true
1003 }
1004 }
1005 }
1006 if honk.Public {
1007 for _, f := range getdubs(user.ID) {
1008 box, _ := getboxes(f.XID)
1009 if box != nil && box.Shared != "" {
1010 rcpts["%"+box.Shared] = true
1011 } else {
1012 rcpts[f.XID] = true
1013 }
1014 }
1015 }
1016 for a := range rcpts {
1017 go deliverate(0, user.Name, a, msg)
1018 }
1019}
1020
1021func asjonker(user *WhatAbout) junk.Junk {
1022 about := obfusbreak(user.About)
1023
1024 j := junk.New()
1025 j["@context"] = itiswhatitis
1026 j["id"] = user.URL
1027 j["type"] = "Person"
1028 j["inbox"] = user.URL + "/inbox"
1029 j["outbox"] = user.URL + "/outbox"
1030 j["followers"] = user.URL + "/followers"
1031 j["following"] = user.URL + "/following"
1032 j["name"] = user.Display
1033 j["preferredUsername"] = user.Name
1034 j["summary"] = about
1035 j["url"] = user.URL
1036 a := junk.New()
1037 a["type"] = "Image"
1038 a["mediaType"] = "image/png"
1039 a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
1040 j["icon"] = a
1041 k := junk.New()
1042 k["id"] = user.URL + "#key"
1043 k["owner"] = user.URL
1044 k["publicKeyPem"] = user.Key
1045 j["publicKey"] = k
1046
1047 return j
1048}
1049
1050var handfull = make(map[string]string)
1051var handlock sync.Mutex
1052
1053func gofish(name string) string {
1054 if name[0] == '@' {
1055 name = name[1:]
1056 }
1057 m := strings.Split(name, "@")
1058 if len(m) != 2 {
1059 log.Printf("bad fish name: %s", name)
1060 return ""
1061 }
1062 handlock.Lock()
1063 ref, ok := handfull[name]
1064 handlock.Unlock()
1065 if ok {
1066 return ref
1067 }
1068 row := stmtGetXonker.QueryRow(name, "fishname")
1069 var href string
1070 err := row.Scan(&href)
1071 if err == nil {
1072 handlock.Lock()
1073 handfull[name] = href
1074 handlock.Unlock()
1075 return href
1076 }
1077 log.Printf("fishing for %s", name)
1078 j, err := GetJunkFast(fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1079 if err != nil {
1080 log.Printf("failed to go fish %s: %s", name, err)
1081 handlock.Lock()
1082 handfull[name] = ""
1083 handlock.Unlock()
1084 return ""
1085 }
1086 links, _ := j.GetArray("links")
1087 for _, li := range links {
1088 l, ok := li.(junk.Junk)
1089 if !ok {
1090 continue
1091 }
1092 href, _ := l.GetString("href")
1093 rel, _ := l.GetString("rel")
1094 t, _ := l.GetString("type")
1095 if rel == "self" && friendorfoe(t) {
1096 _, err := stmtSaveXonker.Exec(name, href, "fishname")
1097 if err != nil {
1098 log.Printf("error saving fishname: %s", err)
1099 }
1100 handlock.Lock()
1101 handfull[name] = href
1102 handlock.Unlock()
1103 return href
1104 }
1105 }
1106 handlock.Lock()
1107 handfull[name] = ""
1108 handlock.Unlock()
1109 return ""
1110}
1111
1112func isactor(t string) bool {
1113 switch t {
1114 case "Person":
1115 case "Organization":
1116 case "Application":
1117 case "Service":
1118 default:
1119 return false
1120 }
1121 return true
1122}
1123
1124func investigate(name string) (*Honker, error) {
1125 if name == "" {
1126 return nil, fmt.Errorf("no name")
1127 }
1128 if name[0] == '@' {
1129 name = gofish(name)
1130 }
1131 if name == "" {
1132 return nil, fmt.Errorf("no name")
1133 }
1134 log.Printf("digging up some info on %s", name)
1135 obj, err := GetJunkFast(name)
1136 if err != nil {
1137 log.Printf("error investigating honker: %s", err)
1138 return nil, err
1139 }
1140 t, _ := obj.GetString("type")
1141 if !isactor(t) {
1142 log.Printf("it's not a person! %s", name)
1143 return nil, err
1144 }
1145 xid, _ := obj.GetString("id")
1146 handle, _ := obj.GetString("preferredUsername")
1147 return &Honker{XID: xid, Handle: handle}, nil
1148}