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