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 "context"
21 "crypto/tls"
22 "database/sql"
23 "fmt"
24 "html"
25 "io"
26 notrand "math/rand"
27 "net/http"
28 "os"
29 "regexp"
30 "strings"
31 "time"
32
33 "humungus.tedunangst.com/r/webs/cache"
34 "humungus.tedunangst.com/r/webs/gate"
35 "humungus.tedunangst.com/r/webs/httpsig"
36 "humungus.tedunangst.com/r/webs/junk"
37 "humungus.tedunangst.com/r/webs/templates"
38)
39
40var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
41var thefakename = `application/activity+json`
42var falsenames = []string{
43 `application/ld+json`,
44 `application/activity+json`,
45}
46var itiswhatitis = "https://www.w3.org/ns/activitystreams"
47var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
48
49var fastTimeout time.Duration = 5
50var slowTimeout time.Duration = 30
51
52func friendorfoe(ct string) bool {
53 ct = strings.ToLower(ct)
54 for _, at := range falsenames {
55 if strings.HasPrefix(ct, at) {
56 return true
57 }
58 }
59 return false
60}
61
62var honkClient = http.Client{}
63
64func gogglesDoNothing() {
65 honkClient.Transport = &http.Transport{
66 TLSClientConfig: &tls.Config{
67 InsecureSkipVerify: true,
68 },
69 }
70}
71
72func PostJunk(keyname string, key httpsig.PrivateKey, url string, j junk.Junk) error {
73 return PostMsg(keyname, key, url, j.ToBytes())
74}
75
76func PostMsg(keyname string, key httpsig.PrivateKey, url string, msg []byte) error {
77 req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
78 if err != nil {
79 return err
80 }
81 req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
82 req.Header.Set("Content-Type", theonetruename)
83 httpsig.SignRequest(keyname, key, req, msg)
84 ctx, cancel := context.WithTimeout(context.Background(), 2*slowTimeout*time.Second)
85 defer cancel()
86 req = req.WithContext(ctx)
87 resp, err := honkClient.Do(req)
88 if err != nil {
89 return err
90 }
91 resp.Body.Close()
92 switch resp.StatusCode {
93 case 200:
94 case 201:
95 case 202:
96 default:
97 return fmt.Errorf("http post status: %d", resp.StatusCode)
98 }
99 ilog.Printf("successful post: %s %d", url, resp.StatusCode)
100 return nil
101}
102
103func GetJunk(userid int64, url string) (junk.Junk, error) {
104 return GetJunkTimeout(userid, url, slowTimeout*time.Second, nil)
105}
106
107func GetJunkFast(userid int64, url string) (junk.Junk, error) {
108 return GetJunkTimeout(userid, url, fastTimeout*time.Second, nil)
109}
110
111func GetJunkHardMode(userid int64, url string) (junk.Junk, error) {
112 j, err := GetJunk(userid, url)
113 if err != nil {
114 emsg := err.Error()
115 if emsg == "http get status: 502" || strings.Contains(emsg, "timeout") {
116 ilog.Printf("trying again after error: %s", emsg)
117 time.Sleep(time.Duration(60+notrand.Int63n(60)) * time.Second)
118 j, err = GetJunk(userid, url)
119 if err != nil {
120 ilog.Printf("still couldn't get it")
121 } else {
122 ilog.Printf("retry success!")
123 }
124 }
125 }
126 return j, err
127}
128
129var flightdeck = gate.NewSerializer()
130
131func GetJunkTimeout(userid int64, url string, timeout time.Duration, final *string) (junk.Junk, error) {
132 if rejectorigin(userid, url, false) {
133 return nil, fmt.Errorf("rejected origin: %s", url)
134 }
135 if final != nil {
136 *final = url
137 }
138 sign := func(req *http.Request) error {
139 var ki *KeyInfo
140 ok := ziggies.Get(userid, &ki)
141 if ok {
142 httpsig.SignRequest(ki.keyname, ki.seckey, req, nil)
143 }
144 return nil
145 }
146 if develMode {
147 sign = nil
148 }
149 client := honkClient
150 client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
151 if len(via) >= 5 {
152 return fmt.Errorf("stopped after 5 redirects")
153 }
154 if final != nil {
155 *final = req.URL.String()
156 }
157 if sign != nil {
158 sign(req)
159 }
160 return nil
161 }
162 fn := func() (interface{}, error) {
163 at := theonetruename
164 if strings.Contains(url, ".well-known/webfinger?resource") {
165 at = "application/jrd+json"
166 }
167 j, err := junk.Get(url, junk.GetArgs{
168 Accept: at,
169 Agent: "honksnonk/5.0; " + serverName,
170 Timeout: timeout,
171 Client: &client,
172 Fixup: sign,
173 })
174 return j, err
175 }
176
177 ji, err := flightdeck.Call(url, fn)
178 if err != nil {
179 return nil, err
180 }
181 j := ji.(junk.Junk)
182 return j, nil
183}
184
185func fetchsome(url string) ([]byte, error) {
186 req, err := http.NewRequest("GET", url, nil)
187 if err != nil {
188 ilog.Printf("error fetching %s: %s", url, err)
189 return nil, err
190 }
191 req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName)
192 ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
193 defer cancel()
194 req = req.WithContext(ctx)
195 resp, err := honkClient.Do(req)
196 if err != nil {
197 ilog.Printf("error fetching %s: %s", url, err)
198 return nil, err
199 }
200 defer resp.Body.Close()
201 switch resp.StatusCode {
202 case 200:
203 case 201:
204 case 202:
205 default:
206 return nil, fmt.Errorf("http get not 200: %d %s", resp.StatusCode, url)
207 }
208 var buf bytes.Buffer
209 limiter := io.LimitReader(resp.Body, 10*1024*1024)
210 io.Copy(&buf, limiter)
211 return buf.Bytes(), nil
212}
213
214func savedonk(url string, name, desc, media string, localize bool) *Donk {
215 if url == "" {
216 return nil
217 }
218 if donk := finddonk(url); donk != nil {
219 return donk
220 }
221 ilog.Printf("saving donk: %s", url)
222 data := []byte{}
223 if localize {
224 fn := func() (interface{}, error) {
225 return fetchsome(url)
226 }
227 ii, err := flightdeck.Call(url, fn)
228 if err != nil {
229 ilog.Printf("error fetching donk: %s", err)
230 localize = false
231 goto saveit
232 }
233 data = ii.([]byte)
234
235 if len(data) == 10*1024*1024 {
236 ilog.Printf("truncation likely")
237 }
238 if strings.HasPrefix(media, "image") {
239 img, err := shrinkit(data)
240 if err != nil {
241 ilog.Printf("unable to decode image: %s", err)
242 localize = false
243 data = []byte{}
244 goto saveit
245 }
246 data = img.Data
247 media = "image/" + img.Format
248 } else if media == "application/pdf" {
249 if len(data) > 1000000 {
250 ilog.Printf("not saving large pdf")
251 localize = false
252 data = []byte{}
253 }
254 } else if len(data) > 100000 {
255 ilog.Printf("not saving large attachment")
256 localize = false
257 data = []byte{}
258 }
259 }
260saveit:
261 fileid, err := savefile(name, desc, url, media, localize, data)
262 if err != nil {
263 elog.Printf("error saving file %s: %s", url, err)
264 return nil
265 }
266 donk := new(Donk)
267 donk.FileID = fileid
268 return donk
269}
270
271func iszonked(userid int64, xid string) bool {
272 var id int64
273 row := stmtFindZonk.QueryRow(userid, xid)
274 err := row.Scan(&id)
275 if err == nil {
276 return true
277 }
278 if err != sql.ErrNoRows {
279 ilog.Printf("error querying zonk: %s", err)
280 }
281 return false
282}
283
284func needxonk(user *WhatAbout, x *Honk) bool {
285 if rejectxonk(x) {
286 return false
287 }
288 return needxonkid(user, x.XID)
289}
290func needbonkid(user *WhatAbout, xid string) bool {
291 return needxonkidX(user, xid, true)
292}
293func needxonkid(user *WhatAbout, xid string) bool {
294 return needxonkidX(user, xid, false)
295}
296func needxonkidX(user *WhatAbout, xid string, isannounce bool) bool {
297 if !strings.HasPrefix(xid, "https://") {
298 return false
299 }
300 if strings.HasPrefix(xid, user.URL+"/") {
301 return false
302 }
303 if rejectorigin(user.ID, xid, isannounce) {
304 ilog.Printf("rejecting origin: %s", xid)
305 return false
306 }
307 if iszonked(user.ID, xid) {
308 ilog.Printf("already zonked: %s", xid)
309 return false
310 }
311 var id int64
312 row := stmtFindXonk.QueryRow(user.ID, xid)
313 err := row.Scan(&id)
314 if err == nil {
315 return false
316 }
317 if err != sql.ErrNoRows {
318 ilog.Printf("error querying xonk: %s", err)
319 }
320 return true
321}
322
323func eradicatexonk(userid int64, xid string) {
324 xonk := getxonk(userid, xid)
325 if xonk != nil {
326 deletehonk(xonk.ID)
327 _, err := stmtSaveZonker.Exec(userid, xid, "zonk")
328 if err != nil {
329 elog.Printf("error eradicating: %s", err)
330 }
331 }
332}
333
334func savexonk(x *Honk) {
335 ilog.Printf("saving xonk: %s", x.XID)
336 go handles(x.Honker)
337 go handles(x.Oonker)
338 savehonk(x)
339}
340
341type Box struct {
342 In string
343 Out string
344 Shared string
345}
346
347var boxofboxes = cache.New(cache.Options{Filler: func(ident string) (*Box, bool) {
348 var info string
349 row := stmtGetXonker.QueryRow(ident, "boxes")
350 err := row.Scan(&info)
351 if err != nil {
352 dlog.Printf("need to get boxes for %s", ident)
353 var j junk.Junk
354 j, err = GetJunk(readyLuserOne, ident)
355 if err != nil {
356 dlog.Printf("error getting boxes: %s", err)
357 return nil, false
358 }
359 allinjest(originate(ident), j)
360 row = stmtGetXonker.QueryRow(ident, "boxes")
361 err = row.Scan(&info)
362 }
363 if err == nil {
364 m := strings.Split(info, " ")
365 b := &Box{In: m[0], Out: m[1], Shared: m[2]}
366 return b, true
367 }
368 return nil, false
369}})
370
371func gimmexonks(user *WhatAbout, outbox string) {
372 dlog.Printf("getting outbox: %s", outbox)
373 j, err := GetJunk(user.ID, outbox)
374 if err != nil {
375 ilog.Printf("error getting outbox: %s", err)
376 return
377 }
378 t, _ := j.GetString("type")
379 origin := originate(outbox)
380 if t == "OrderedCollection" {
381 items, _ := j.GetArray("orderedItems")
382 if items == nil {
383 items, _ = j.GetArray("items")
384 }
385 if items == nil {
386 obj, ok := j.GetMap("first")
387 if ok {
388 items, _ = obj.GetArray("orderedItems")
389 } else {
390 page1, ok := j.GetString("first")
391 if ok {
392 j, err = GetJunk(user.ID, page1)
393 if err != nil {
394 ilog.Printf("error getting page1: %s", err)
395 return
396 }
397 items, _ = j.GetArray("orderedItems")
398 }
399 }
400 }
401 if len(items) > 20 {
402 items = items[0:20]
403 }
404 for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
405 items[i], items[j] = items[j], items[i]
406 }
407 for _, item := range items {
408 obj, ok := item.(junk.Junk)
409 if ok {
410 xonksaver(user, obj, origin)
411 continue
412 }
413 xid, ok := item.(string)
414 if ok {
415 if !needxonkid(user, xid) {
416 continue
417 }
418 obj, err = GetJunk(user.ID, xid)
419 if err != nil {
420 ilog.Printf("error getting item: %s", err)
421 continue
422 }
423 xonksaver(user, obj, originate(xid))
424 }
425 }
426 }
427}
428
429func newphone(a []string, obj junk.Junk) []string {
430 for _, addr := range []string{"to", "cc", "attributedTo"} {
431 who, _ := obj.GetString(addr)
432 if who != "" {
433 a = append(a, who)
434 }
435 whos, _ := obj.GetArray(addr)
436 for _, w := range whos {
437 who, _ := w.(string)
438 if who != "" {
439 a = append(a, who)
440 }
441 }
442 }
443 return a
444}
445
446func extractattrto(obj junk.Junk) string {
447 arr := oneforall(obj, "attributedTo")
448 for _, a := range arr {
449 s, ok := a.(string)
450 if ok {
451 return s
452 }
453 o, ok := a.(junk.Junk)
454 if ok {
455 t, _ := o.GetString("type")
456 id, _ := o.GetString("id")
457 if t == "Person" || t == "" {
458 return id
459 }
460 }
461 }
462 return ""
463}
464
465func oneforall(obj junk.Junk, key string) []interface{} {
466 if val, ok := obj.GetMap(key); ok {
467 return []interface{}{val}
468 }
469 if str, ok := obj.GetString(key); ok {
470 return []interface{}{str}
471 }
472 arr, _ := obj.GetArray(key)
473 return arr
474}
475
476func firstofmany(obj junk.Junk, key string) string {
477 if val, _ := obj.GetString(key); val != "" {
478 return val
479 }
480 if arr, _ := obj.GetArray(key); len(arr) > 0 {
481 val, ok := arr[0].(string)
482 if ok {
483 return val
484 }
485 }
486 return ""
487}
488
489var re_mast0link = regexp.MustCompile(`https://[[:alnum:].]+/users/[[:alnum:]]+/statuses/[[:digit:]]+`)
490var re_masto1ink = regexp.MustCompile(`https://([[:alnum:].]+)/@([[:alnum:]]+)(@[[:alnum:].]+)?/([[:digit:]]+)`)
491var re_misslink = regexp.MustCompile(`https://[[:alnum:].]+/notes/[[:alnum:]]+`)
492var re_honklink = regexp.MustCompile(`https://[[:alnum:].]+/u/[[:alnum:]]+/h/[[:alnum:]]+`)
493var re_r0malink = regexp.MustCompile(`https://[[:alnum:].]+/objects/[[:alnum:]-]+`)
494var re_roma1ink = regexp.MustCompile(`https://[[:alnum:].]+/notice/[[:alnum:]]+`)
495var re_qtlinks = regexp.MustCompile(`>https://[^\s<]+<`)
496
497func xonksaver(user *WhatAbout, item junk.Junk, origin string) *Honk {
498 depth := 0
499 maxdepth := 10
500 currenttid := ""
501 goingup := 0
502 var xonkxonkfn func(junk.Junk, string, bool, string) *Honk
503
504 qutify := func(user *WhatAbout, qurl, content string) string {
505 if depth >= maxdepth {
506 ilog.Printf("in too deep")
507 return content
508 }
509 // well this is gross
510 malcontent := strings.ReplaceAll(content, `</span><span class="ellipsis">`, "")
511 malcontent = strings.ReplaceAll(malcontent, `</span><span class="invisible">`, "")
512 mlinks := re_qtlinks.FindAllString(malcontent, -1)
513 if qurl != "" {
514 mlinks = append(mlinks, ">"+qurl+"<")
515 }
516 for _, m := range mlinks {
517 tryit := false
518 m = m[1 : len(m)-1]
519 if re_mast0link.MatchString(m) || re_misslink.MatchString(m) ||
520 re_honklink.MatchString(m) || re_r0malink.MatchString(m) ||
521 re_roma1ink.MatchString(m) {
522 tryit = true
523 } else if re_masto1ink.MatchString(m) {
524 tryit = true
525 }
526 if tryit {
527 var prefix string
528 if m == qurl {
529 prefix += fmt.Sprintf("<p><a href=\"%s\">%s</a>", m, m)
530 }
531 var final string
532 if x := getxonk(user.ID, m); x != nil {
533 content = fmt.Sprintf("%s%s<blockquote>%s</blockquote>", content, prefix, x.Noise)
534 } else if j, err := GetJunkTimeout(user.ID, m, fastTimeout*time.Second, &final); err == nil {
535 q, ok := j.GetString("content")
536 if ok {
537 content = fmt.Sprintf("%s%s<blockquote>%s</blockquote>", content, prefix, q)
538 }
539 prevdepth := depth
540 depth = maxdepth
541 xonkxonkfn(j, originate(final), false, "")
542 depth = prevdepth
543 }
544 }
545 }
546 return content
547 }
548
549 saveonemore := func(xid string) {
550 dlog.Printf("getting onemore: %s", xid)
551 if depth >= maxdepth {
552 ilog.Printf("in too deep")
553 return
554 }
555 obj, err := GetJunkHardMode(user.ID, xid)
556 if err != nil {
557 ilog.Printf("error getting onemore: %s: %s", xid, err)
558 return
559 }
560 xonkxonkfn(obj, originate(xid), false, "")
561 }
562
563 xonkxonkfn = func(item junk.Junk, origin string, isUpdate bool, bonker string) *Honk {
564 id, _ := item.GetString("id")
565 what := firstofmany(item, "type")
566 dt, ok := item.GetString("published")
567 if !ok {
568 dt = time.Now().Format(time.RFC3339)
569 }
570 if depth >= maxdepth+5 {
571 ilog.Printf("went too deep in xonkxonk")
572 return nil
573 }
574 depth++
575 defer func() { depth-- }()
576
577 var err error
578 var xid, rid, url, convoy string
579 var replies []string
580 var obj junk.Junk
581 waspage := false
582 preferorig := false
583 switch what {
584 case "Delete":
585 obj, ok = item.GetMap("object")
586 if ok {
587 xid, _ = obj.GetString("id")
588 } else {
589 xid, _ = item.GetString("object")
590 }
591 if xid == "" {
592 return nil
593 }
594 if originate(xid) != origin {
595 ilog.Printf("forged delete: %s", xid)
596 return nil
597 }
598 ilog.Printf("eradicating %s", xid)
599 eradicatexonk(user.ID, xid)
600 return nil
601 case "Remove":
602 xid, _ = item.GetString("object")
603 targ, _ := obj.GetString("target")
604 ilog.Printf("remove %s from %s", obj, targ)
605 return nil
606 case "Tombstone":
607 xid, _ = item.GetString("id")
608 if xid == "" {
609 return nil
610 }
611 if originate(xid) != origin {
612 ilog.Printf("forged delete: %s", xid)
613 return nil
614 }
615 ilog.Printf("eradicating %s", xid)
616 eradicatexonk(user.ID, xid)
617 return nil
618 case "Announce":
619 obj, ok = item.GetMap("object")
620 if ok {
621 // peek ahead some
622 what := firstofmany(obj, "type")
623 if what == "Create" || what == "Update" {
624 if what == "Update" {
625 isUpdate = true
626 }
627 inner, ok := obj.GetMap("object")
628 if ok {
629 obj = inner
630 } else {
631 xid, _ = obj.GetString("object")
632 }
633 }
634 if xid == "" {
635 xid, _ = obj.GetString("id")
636 }
637 } else {
638 xid, _ = item.GetString("object")
639 }
640 if !isUpdate && !needbonkid(user, xid) {
641 return nil
642 }
643 bonker, _ = item.GetString("actor")
644 origin = originate(xid)
645 if ok && originate(id) == origin {
646 dlog.Printf("using object in announce for %s", xid)
647 } else {
648 dlog.Printf("getting bonk: %s", xid)
649 obj, err = GetJunkHardMode(user.ID, xid)
650 if err != nil {
651 ilog.Printf("error getting bonk: %s: %s", xid, err)
652 return nil
653 }
654 }
655 return xonkxonkfn(obj, origin, isUpdate, bonker)
656 case "Update":
657 isUpdate = true
658 fallthrough
659 case "Create":
660 obj, ok = item.GetMap("object")
661 if !ok {
662 xid, _ = item.GetString("object")
663 dlog.Printf("getting created honk: %s", xid)
664 if originate(xid) != origin {
665 ilog.Printf("out of bounds %s not from %s", xid, origin)
666 return nil
667 }
668 obj, err = GetJunkHardMode(user.ID, xid)
669 if err != nil {
670 ilog.Printf("error getting creation: %s", err)
671 }
672 }
673 if obj == nil {
674 ilog.Printf("no object for creation %s", id)
675 return nil
676 }
677 return xonkxonkfn(obj, origin, isUpdate, bonker)
678 case "Read":
679 xid, ok = item.GetString("object")
680 if ok {
681 if !needxonkid(user, xid) {
682 dlog.Printf("don't need read obj: %s", xid)
683 return nil
684 }
685 obj, err = GetJunkHardMode(user.ID, xid)
686 if err != nil {
687 ilog.Printf("error getting read: %s", err)
688 return nil
689 }
690 return xonkxonkfn(obj, originate(xid), false, "")
691 }
692 return nil
693 case "Add":
694 xid, ok = item.GetString("object")
695 if ok {
696 // check target...
697 if !needxonkid(user, xid) {
698 dlog.Printf("don't need added obj: %s", xid)
699 return nil
700 }
701 obj, err = GetJunkHardMode(user.ID, xid)
702 if err != nil {
703 ilog.Printf("error getting add: %s", err)
704 return nil
705 }
706 return xonkxonkfn(obj, originate(xid), false, "")
707 }
708 return nil
709 case "Move":
710 obj = item
711 what = "move"
712 case "Page":
713 waspage = true
714 fallthrough
715 case "Audio":
716 fallthrough
717 case "Image":
718 if what == "Image" {
719 preferorig = true
720 }
721 fallthrough
722 case "Video":
723 fallthrough
724 case "Question":
725 fallthrough
726 case "Note":
727 fallthrough
728 case "Article":
729 obj = item
730 what = "honk"
731 case "Event":
732 obj = item
733 what = "event"
734 case "ChatMessage":
735 bonker = ""
736 obj = item
737 what = "chonk"
738 default:
739 ilog.Printf("unknown activity: %s", what)
740 dumpactivity(item)
741 return nil
742 }
743 if bonker != "" {
744 what = "bonk"
745 }
746
747 if obj != nil {
748 xid, _ = obj.GetString("id")
749 }
750
751 if xid == "" {
752 ilog.Printf("don't know what xid is")
753 item.Write(ilog.Writer())
754 return nil
755 }
756 if originate(xid) != origin {
757 if !develMode && origin != "" {
758 ilog.Printf("original sin: %s not from %s", xid, origin)
759 item.Write(ilog.Writer())
760 return nil
761 }
762 }
763
764 var xonk Honk
765 // early init
766 xonk.XID = xid
767 xonk.UserID = user.ID
768 xonk.Honker, _ = item.GetString("actor")
769 if xonk.Honker == "" {
770 xonk.Honker, _ = item.GetString("attributedTo")
771 }
772 if obj != nil {
773 if xonk.Honker == "" {
774 xonk.Honker = extractattrto(obj)
775 }
776 if bonker != "" {
777 xonk.Honker, xonk.Oonker = bonker, xonk.Honker
778 }
779 if xonk.Oonker == xonk.Honker {
780 xonk.Oonker = ""
781 }
782 xonk.Audience = newphone(nil, obj)
783 }
784 xonk.Audience = append(xonk.Audience, xonk.Honker)
785 xonk.Audience = oneofakind(xonk.Audience)
786 xonk.Public = loudandproud(xonk.Audience)
787
788 var mentions []Mention
789 if obj != nil {
790 ot := firstofmany(obj, "type")
791 url, _ = obj.GetString("url")
792 if dt2, ok := obj.GetString("published"); ok {
793 dt = dt2
794 }
795 content, _ := obj.GetString("content")
796 if !strings.HasPrefix(content, "<p>") {
797 content = "<p>" + content
798 }
799 precis, _ := obj.GetString("summary")
800 if name, ok := obj.GetString("name"); ok {
801 if precis != "" {
802 content = precis + "<p>" + content
803 }
804 precis = html.EscapeString(name)
805 }
806 if sens, _ := obj["sensitive"].(bool); sens && precis == "" {
807 precis = "unspecified horror"
808 }
809 if waspage {
810 content += fmt.Sprintf(`<p><a href="%s">%s</a>`, url, url)
811 url = xid
812 }
813 if user.Options.InlineQuotes {
814 qurl, _ := obj.GetString("quoteUrl")
815 content = qutify(user, qurl, content)
816 }
817 rid, ok = obj.GetString("inReplyTo")
818 if !ok {
819 if robj, ok := obj.GetMap("inReplyTo"); ok {
820 rid, _ = robj.GetString("id")
821 }
822 }
823 convoy, _ = obj.GetString("context")
824 if convoy == "" {
825 convoy, _ = obj.GetString("conversation")
826 }
827 if ot == "Question" {
828 if what == "honk" {
829 what = "qonk"
830 }
831 content += "<ul>"
832 ans, _ := obj.GetArray("oneOf")
833 for _, ai := range ans {
834 a, ok := ai.(junk.Junk)
835 if !ok {
836 continue
837 }
838 as, _ := a.GetString("name")
839 content += "<li>" + as
840 }
841 ans, _ = obj.GetArray("anyOf")
842 for _, ai := range ans {
843 a, ok := ai.(junk.Junk)
844 if !ok {
845 continue
846 }
847 as, _ := a.GetString("name")
848 content += "<li>" + as
849 }
850 content += "</ul>"
851 }
852 if ot == "Move" {
853 targ, _ := obj.GetString("target")
854 content += string(templates.Sprintf(`<p>Moved to <a href="%s">%s</a>`, targ, targ))
855 }
856 if len(content) > 90001 {
857 ilog.Printf("content too long. truncating")
858 content = content[:90001]
859 }
860
861 xonk.Noise = content
862 xonk.Precis = precis
863 if rejectxonk(&xonk) {
864 dlog.Printf("fast reject: %s", xid)
865 return nil
866 }
867
868 numatts := 0
869 procatt := func(att junk.Junk) {
870 at, _ := att.GetString("type")
871 mt, _ := att.GetString("mediaType")
872 if mt == "" {
873 mt = "image"
874 }
875 u, ok := att.GetString("url")
876 if !ok {
877 u, ok = att.GetString("href")
878 }
879 if !ok {
880 if ua, ok := att.GetArray("url"); ok && len(ua) > 0 {
881 u, ok = ua[0].(string)
882 if !ok {
883 if uu, ok := ua[0].(junk.Junk); ok {
884 u, _ = uu.GetString("href")
885 if mt == "" {
886 mt, _ = uu.GetString("mediaType")
887 }
888 }
889 }
890 } else if uu, ok := att.GetMap("url"); ok {
891 u, _ = uu.GetString("href")
892 if mt == "" {
893 mt, _ = uu.GetString("mediaType")
894 }
895 }
896 }
897 name, _ := att.GetString("name")
898 desc, _ := att.GetString("summary")
899 desc = html.UnescapeString(desc)
900 if desc == "" {
901 desc = name
902 }
903 localize := false
904 if at == "Document" || at == "Image" {
905 mt = strings.ToLower(mt)
906 dlog.Printf("attachment: %s %s", mt, u)
907 if mt == "text/plain" || mt == "application/pdf" ||
908 strings.HasPrefix(mt, "image") {
909 if numatts > 4 {
910 ilog.Printf("excessive attachment: %s", at)
911 } else {
912 localize = true
913 }
914 }
915 } else if at == "Link" {
916 if waspage {
917 xonk.Noise += fmt.Sprintf(`<p><a href="%s">%s</a>`, u, u)
918 return
919 }
920 if name == "" {
921 name = u
922 }
923 } else {
924 ilog.Printf("unknown attachment: %s", at)
925 }
926 if skipMedia(&xonk) {
927 localize = false
928 }
929 if preferorig && !localize {
930 return
931 }
932 donk := savedonk(u, name, desc, mt, localize)
933 if donk != nil {
934 xonk.Donks = append(xonk.Donks, donk)
935 }
936 numatts++
937 }
938 if img, ok := obj.GetMap("image"); ok {
939 procatt(img)
940 }
941 if preferorig {
942 atts, _ := obj.GetArray("url")
943 for _, atti := range atts {
944 att, ok := atti.(junk.Junk)
945 if !ok {
946 ilog.Printf("attachment that wasn't map?")
947 continue
948 }
949 procatt(att)
950 }
951 if numatts == 0 {
952 preferorig = false
953 }
954 }
955 if !preferorig {
956 atts := oneforall(obj, "attachment")
957 for _, atti := range atts {
958 att, ok := atti.(junk.Junk)
959 if !ok {
960 ilog.Printf("attachment that wasn't map?")
961 continue
962 }
963 procatt(att)
964 }
965 }
966 proctag := func(tag junk.Junk) {
967 tt, _ := tag.GetString("type")
968 name, _ := tag.GetString("name")
969 desc, _ := tag.GetString("summary")
970 desc = html.UnescapeString(desc)
971 if desc == "" {
972 desc = name
973 }
974 if tt == "Emoji" {
975 icon, _ := tag.GetMap("icon")
976 mt, _ := icon.GetString("mediaType")
977 if mt == "" {
978 mt = "image/png"
979 }
980 u, _ := icon.GetString("url")
981 donk := savedonk(u, name, desc, mt, true)
982 if donk != nil {
983 xonk.Donks = append(xonk.Donks, donk)
984 }
985 }
986 if tt == "Hashtag" {
987 if name == "" || name == "#" {
988 // skip it
989 } else {
990 if name[0] != '#' {
991 name = "#" + name
992 }
993 xonk.Onts = append(xonk.Onts, name)
994 }
995 }
996 if tt == "Place" {
997 p := new(Place)
998 p.Name = name
999 p.Latitude, _ = tag.GetNumber("latitude")
1000 p.Longitude, _ = tag.GetNumber("longitude")
1001 p.Url, _ = tag.GetString("url")
1002 xonk.Place = p
1003 }
1004 if tt == "Mention" {
1005 var m Mention
1006 m.Who, _ = tag.GetString("name")
1007 m.Where, _ = tag.GetString("href")
1008 mentions = append(mentions, m)
1009 }
1010 }
1011 tags := oneforall(obj, "tag")
1012 for _, tagi := range tags {
1013 tag, ok := tagi.(junk.Junk)
1014 if !ok {
1015 continue
1016 }
1017 proctag(tag)
1018 }
1019 if starttime, ok := obj.GetString("startTime"); ok {
1020 if start, err := time.Parse(time.RFC3339, starttime); err == nil {
1021 t := new(Time)
1022 t.StartTime = start
1023 endtime, _ := obj.GetString("endTime")
1024 t.EndTime, _ = time.Parse(time.RFC3339, endtime)
1025 dura, _ := obj.GetString("duration")
1026 if strings.HasPrefix(dura, "PT") {
1027 dura = strings.ToLower(dura[2:])
1028 d, _ := time.ParseDuration(dura)
1029 t.Duration = Duration(d)
1030 }
1031 xonk.Time = t
1032 }
1033 }
1034 if loca, ok := obj.GetMap("location"); ok {
1035 if tt, _ := loca.GetString("type"); tt == "Place" {
1036 p := new(Place)
1037 p.Name, _ = loca.GetString("name")
1038 p.Latitude, _ = loca.GetNumber("latitude")
1039 p.Longitude, _ = loca.GetNumber("longitude")
1040 p.Url, _ = loca.GetString("url")
1041 xonk.Place = p
1042 }
1043 }
1044
1045 xonk.Onts = oneofakind(xonk.Onts)
1046 replyobj, ok := obj.GetMap("replies")
1047 if ok {
1048 items, ok := replyobj.GetArray("items")
1049 if !ok {
1050 first, ok := replyobj.GetMap("first")
1051 if ok {
1052 items, _ = first.GetArray("items")
1053 }
1054 }
1055 for _, repl := range items {
1056 s, ok := repl.(string)
1057 if ok {
1058 replies = append(replies, s)
1059 }
1060 }
1061 }
1062
1063 }
1064
1065 if currenttid == "" {
1066 currenttid = convoy
1067 }
1068
1069 // init xonk
1070 xonk.What = what
1071 xonk.RID = rid
1072 xonk.Date, _ = time.Parse(time.RFC3339, dt)
1073 xonk.URL = url
1074 xonk.Format = "html"
1075 xonk.Convoy = convoy
1076 xonk.Mentions = mentions
1077 for _, m := range mentions {
1078 if m.Where == user.URL {
1079 xonk.Whofore = 1
1080 }
1081 }
1082 imaginate(&xonk)
1083
1084 if what == "chonk" {
1085 target, _ := obj.GetString("to")
1086 if target == user.URL {
1087 target = xonk.Honker
1088 }
1089 ch := Chonk{
1090 UserID: xonk.UserID,
1091 XID: xid,
1092 Who: xonk.Honker,
1093 Target: target,
1094 Date: xonk.Date,
1095 Noise: xonk.Noise,
1096 Format: xonk.Format,
1097 Donks: xonk.Donks,
1098 }
1099 savechonk(&ch)
1100 return nil
1101 }
1102
1103 if isUpdate {
1104 dlog.Printf("something has changed! %s", xonk.XID)
1105 prev := getxonk(user.ID, xonk.XID)
1106 if prev == nil {
1107 ilog.Printf("didn't find old version for update: %s", xonk.XID)
1108 isUpdate = false
1109 } else {
1110 xonk.ID = prev.ID
1111 updatehonk(&xonk)
1112 }
1113 }
1114 if !isUpdate && needxonk(user, &xonk) {
1115 if rid != "" && xonk.Public {
1116 if needxonkid(user, rid) {
1117 goingup++
1118 saveonemore(rid)
1119 goingup--
1120 }
1121 if convoy == "" {
1122 xx := getxonk(user.ID, rid)
1123 if xx != nil {
1124 convoy = xx.Convoy
1125 }
1126 }
1127 }
1128 if convoy == "" {
1129 convoy = currenttid
1130 }
1131 if convoy == "" {
1132 convoy = xonk.XID
1133 currenttid = convoy
1134 }
1135 xonk.Convoy = convoy
1136 savexonk(&xonk)
1137 }
1138 if goingup == 0 {
1139 for _, replid := range replies {
1140 if needxonkid(user, replid) {
1141 dlog.Printf("missing a reply: %s", replid)
1142 saveonemore(replid)
1143 }
1144 }
1145 }
1146 return &xonk
1147 }
1148
1149 return xonkxonkfn(item, origin, false, "")
1150}
1151
1152func dumpactivity(item junk.Junk) {
1153 fd, err := os.OpenFile("savedinbox.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
1154 if err != nil {
1155 elog.Printf("error opening inbox! %s", err)
1156 return
1157 }
1158 defer fd.Close()
1159 item.Write(fd)
1160 io.WriteString(fd, "\n")
1161}
1162
1163func rubadubdub(user *WhatAbout, req junk.Junk) {
1164 actor, _ := req.GetString("actor")
1165 j := junk.New()
1166 j["@context"] = itiswhatitis
1167 j["id"] = user.URL + "/dub/" + xfiltrate()
1168 j["type"] = "Accept"
1169 j["actor"] = user.URL
1170 j["to"] = actor
1171 j["published"] = time.Now().UTC().Format(time.RFC3339)
1172 j["object"] = req
1173
1174 deliverate(user.ID, actor, j.ToBytes())
1175}
1176
1177func itakeitallback(user *WhatAbout, xid string, owner string, folxid string) {
1178 j := junk.New()
1179 j["@context"] = itiswhatitis
1180 j["id"] = user.URL + "/unsub/" + folxid
1181 j["type"] = "Undo"
1182 j["actor"] = user.URL
1183 j["to"] = owner
1184 f := junk.New()
1185 f["id"] = user.URL + "/sub/" + folxid
1186 f["type"] = "Follow"
1187 f["actor"] = user.URL
1188 f["to"] = owner
1189 f["object"] = xid
1190 j["object"] = f
1191 j["published"] = time.Now().UTC().Format(time.RFC3339)
1192
1193 deliverate(user.ID, owner, j.ToBytes())
1194}
1195
1196func subsub(user *WhatAbout, xid string, owner string, folxid string) {
1197 if xid == "" {
1198 ilog.Printf("can't subscribe to empty")
1199 return
1200 }
1201 j := junk.New()
1202 j["@context"] = itiswhatitis
1203 j["id"] = user.URL + "/sub/" + folxid
1204 j["type"] = "Follow"
1205 j["actor"] = user.URL
1206 j["to"] = owner
1207 j["object"] = xid
1208 j["published"] = time.Now().UTC().Format(time.RFC3339)
1209
1210 deliverate(user.ID, owner, j.ToBytes())
1211}
1212
1213func activatedonks(donks []*Donk) []junk.Junk {
1214 var atts []junk.Junk
1215 for _, d := range donks {
1216 if re_emus.MatchString(d.Name) {
1217 continue
1218 }
1219 jd := junk.New()
1220 jd["mediaType"] = d.Media
1221 jd["name"] = d.Name
1222 jd["summary"] = html.EscapeString(d.Desc)
1223 jd["type"] = "Document"
1224 jd["url"] = d.URL
1225 atts = append(atts, jd)
1226 }
1227 return atts
1228}
1229
1230// returns activity, object
1231func jonkjonk(user *WhatAbout, h *Honk) (junk.Junk, junk.Junk) {
1232 dt := h.Date.Format(time.RFC3339)
1233 var jo junk.Junk
1234 j := junk.New()
1235 j["id"] = user.URL + "/" + h.What + "/" + shortxid(h.XID)
1236 j["actor"] = user.URL
1237 j["published"] = dt
1238 j["to"] = h.Audience[0]
1239 if len(h.Audience) > 1 {
1240 j["cc"] = h.Audience[1:]
1241 }
1242
1243 switch h.What {
1244 case "update":
1245 fallthrough
1246 case "event":
1247 fallthrough
1248 case "honk":
1249 j["type"] = "Create"
1250 jo = junk.New()
1251 jo["id"] = h.XID
1252 jo["type"] = "Note"
1253 if h.What == "event" {
1254 jo["type"] = "Event"
1255 }
1256 if h.What == "update" {
1257 j["type"] = "Update"
1258 jo["updated"] = dt
1259 }
1260 jo["published"] = dt
1261 jo["url"] = h.XID
1262 jo["attributedTo"] = user.URL
1263 if h.RID != "" {
1264 jo["inReplyTo"] = h.RID
1265 }
1266 if h.Convoy != "" {
1267 jo["context"] = h.Convoy
1268 jo["conversation"] = h.Convoy
1269 }
1270 jo["to"] = h.Audience[0]
1271 if len(h.Audience) > 1 {
1272 jo["cc"] = h.Audience[1:]
1273 }
1274 if !h.Public {
1275 jo["directMessage"] = true
1276 }
1277 h.Noise = re_retag.ReplaceAllString(h.Noise, "")
1278 translate(h)
1279 redoimages(h)
1280 if h.Precis != "" {
1281 jo["sensitive"] = true
1282 }
1283
1284 var replies []string
1285 for _, reply := range h.Replies {
1286 replies = append(replies, reply.XID)
1287 }
1288 if len(replies) > 0 {
1289 jr := junk.New()
1290 jr["type"] = "Collection"
1291 jr["totalItems"] = len(replies)
1292 jr["items"] = replies
1293 jo["replies"] = jr
1294 }
1295
1296 var tags []junk.Junk
1297 for _, m := range h.Mentions {
1298 t := junk.New()
1299 t["type"] = "Mention"
1300 t["name"] = m.Who
1301 t["href"] = m.Where
1302 tags = append(tags, t)
1303 }
1304 for _, o := range h.Onts {
1305 t := junk.New()
1306 t["type"] = "Hashtag"
1307 o = strings.ToLower(o)
1308 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1309 t["name"] = o
1310 tags = append(tags, t)
1311 }
1312 for _, e := range herdofemus(h.Noise) {
1313 t := junk.New()
1314 t["id"] = e.ID
1315 t["type"] = "Emoji"
1316 t["name"] = e.Name
1317 i := junk.New()
1318 i["type"] = "Image"
1319 i["mediaType"] = e.Type
1320 i["url"] = e.ID
1321 t["icon"] = i
1322 tags = append(tags, t)
1323 }
1324 for _, e := range fixupflags(h) {
1325 t := junk.New()
1326 t["id"] = e.ID
1327 t["type"] = "Emoji"
1328 t["name"] = e.Name
1329 i := junk.New()
1330 i["type"] = "Image"
1331 i["mediaType"] = "image/png"
1332 i["url"] = e.ID
1333 t["icon"] = i
1334 tags = append(tags, t)
1335 }
1336 if len(tags) > 0 {
1337 jo["tag"] = tags
1338 }
1339 if p := h.Place; p != nil {
1340 t := junk.New()
1341 t["type"] = "Place"
1342 if p.Name != "" {
1343 t["name"] = p.Name
1344 }
1345 if p.Latitude != 0 {
1346 t["latitude"] = p.Latitude
1347 }
1348 if p.Longitude != 0 {
1349 t["longitude"] = p.Longitude
1350 }
1351 if p.Url != "" {
1352 t["url"] = p.Url
1353 }
1354 jo["location"] = t
1355 }
1356 if t := h.Time; t != nil {
1357 jo["startTime"] = t.StartTime.Format(time.RFC3339)
1358 if t.Duration != 0 {
1359 jo["duration"] = "PT" + strings.ToUpper(t.Duration.String())
1360 }
1361 }
1362 atts := activatedonks(h.Donks)
1363 if len(atts) > 0 {
1364 jo["attachment"] = atts
1365 }
1366 jo["summary"] = h.Precis
1367 jo["content"] = h.Noise
1368 j["object"] = jo
1369 case "bonk":
1370 j["type"] = "Announce"
1371 if h.Convoy != "" {
1372 j["context"] = h.Convoy
1373 }
1374 j["object"] = h.XID
1375 case "unbonk":
1376 b := junk.New()
1377 b["id"] = user.URL + "/" + "bonk" + "/" + shortxid(h.XID)
1378 b["type"] = "Announce"
1379 b["actor"] = user.URL
1380 if h.Convoy != "" {
1381 b["context"] = h.Convoy
1382 }
1383 b["object"] = h.XID
1384 j["type"] = "Undo"
1385 j["object"] = b
1386 case "zonk":
1387 j["type"] = "Delete"
1388 j["object"] = h.XID
1389 case "ack":
1390 j["type"] = "Read"
1391 j["object"] = h.XID
1392 if h.Convoy != "" {
1393 j["context"] = h.Convoy
1394 }
1395 case "react":
1396 j["type"] = "EmojiReact"
1397 j["object"] = h.XID
1398 if h.Convoy != "" {
1399 j["context"] = h.Convoy
1400 }
1401 j["content"] = h.Noise
1402 case "deack":
1403 b := junk.New()
1404 b["id"] = user.URL + "/" + "ack" + "/" + shortxid(h.XID)
1405 b["type"] = "Read"
1406 b["actor"] = user.URL
1407 b["object"] = h.XID
1408 if h.Convoy != "" {
1409 b["context"] = h.Convoy
1410 }
1411 j["type"] = "Undo"
1412 j["object"] = b
1413 }
1414
1415 return j, jo
1416}
1417
1418var oldjonks = cache.New(cache.Options{Filler: func(xid string) ([]byte, bool) {
1419 row := stmtAnyXonk.QueryRow(xid)
1420 honk := scanhonk(row)
1421 if honk == nil || !honk.Public {
1422 return nil, true
1423 }
1424 user, _ := butwhatabout(honk.Username)
1425 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1426 reversehonks(rawhonks)
1427 for _, h := range rawhonks {
1428 if h.RID == honk.XID && h.Public && (h.Whofore == 2 || h.IsAcked()) {
1429 honk.Replies = append(honk.Replies, h)
1430 }
1431 }
1432 donksforhonks([]*Honk{honk})
1433 _, j := jonkjonk(user, honk)
1434 if j == nil {
1435 elog.Fatalf("what just happened? %v", honk)
1436 }
1437 j["@context"] = itiswhatitis
1438
1439 return j.ToBytes(), true
1440}, Limit: 128})
1441
1442func gimmejonk(xid string) ([]byte, bool) {
1443 var j []byte
1444 ok := oldjonks.Get(xid, &j)
1445 return j, ok
1446}
1447
1448func boxuprcpts(user *WhatAbout, addresses []string, useshared bool) map[string]bool {
1449 rcpts := make(map[string]bool)
1450 for _, a := range addresses {
1451 if a == "" || a == thewholeworld || a == user.URL || strings.HasSuffix(a, "/followers") {
1452 continue
1453 }
1454 if a[0] == '%' {
1455 rcpts[a] = true
1456 continue
1457 }
1458 var box *Box
1459 ok := boxofboxes.Get(a, &box)
1460 if ok && useshared && box.Shared != "" {
1461 rcpts["%"+box.Shared] = true
1462 } else {
1463 rcpts[a] = true
1464 }
1465 }
1466 return rcpts
1467}
1468
1469func chonkifymsg(user *WhatAbout, ch *Chonk) []byte {
1470 dt := ch.Date.Format(time.RFC3339)
1471 aud := []string{ch.Target}
1472
1473 jo := junk.New()
1474 jo["id"] = ch.XID
1475 jo["type"] = "ChatMessage"
1476 jo["published"] = dt
1477 jo["attributedTo"] = user.URL
1478 jo["to"] = aud
1479 jo["content"] = ch.HTML
1480 atts := activatedonks(ch.Donks)
1481 if len(atts) > 0 {
1482 jo["attachment"] = atts
1483 }
1484 var tags []junk.Junk
1485 for _, e := range herdofemus(ch.Noise) {
1486 t := junk.New()
1487 t["id"] = e.ID
1488 t["type"] = "Emoji"
1489 t["name"] = e.Name
1490 i := junk.New()
1491 i["type"] = "Image"
1492 i["mediaType"] = e.Type
1493 i["url"] = e.ID
1494 t["icon"] = i
1495 tags = append(tags, t)
1496 }
1497 if len(tags) > 0 {
1498 jo["tag"] = tags
1499 }
1500
1501 j := junk.New()
1502 j["@context"] = itiswhatitis
1503 j["id"] = user.URL + "/" + "honk" + "/" + shortxid(ch.XID)
1504 j["type"] = "Create"
1505 j["actor"] = user.URL
1506 j["published"] = dt
1507 j["to"] = aud
1508 j["object"] = jo
1509
1510 return j.ToBytes()
1511}
1512
1513func sendchonk(user *WhatAbout, ch *Chonk) {
1514 msg := chonkifymsg(user, ch)
1515
1516 rcpts := make(map[string]bool)
1517 rcpts[ch.Target] = true
1518 for a := range rcpts {
1519 go deliverate(user.ID, a, msg)
1520 }
1521}
1522
1523func honkworldwide(user *WhatAbout, honk *Honk) {
1524 jonk, _ := jonkjonk(user, honk)
1525 jonk["@context"] = itiswhatitis
1526 msg := jonk.ToBytes()
1527
1528 rcpts := boxuprcpts(user, honk.Audience, honk.Public)
1529
1530 if honk.Public {
1531 for _, h := range getdubs(user.ID) {
1532 if h.XID == user.URL {
1533 continue
1534 }
1535 var box *Box
1536 ok := boxofboxes.Get(h.XID, &box)
1537 if ok && box.Shared != "" {
1538 rcpts["%"+box.Shared] = true
1539 } else {
1540 rcpts[h.XID] = true
1541 }
1542 }
1543 for _, f := range getbacktracks(honk.XID) {
1544 if f[0] == '%' {
1545 rcpts[f] = true
1546 } else {
1547 var box *Box
1548 ok := boxofboxes.Get(f, &box)
1549 if ok && box.Shared != "" {
1550 rcpts["%"+box.Shared] = true
1551 } else {
1552 rcpts[f] = true
1553 }
1554 }
1555 }
1556 }
1557 for a := range rcpts {
1558 go deliverate(user.ID, a, msg)
1559 }
1560 if honk.Public && len(honk.Onts) > 0 {
1561 collectiveaction(honk)
1562 }
1563}
1564
1565func collectiveaction(honk *Honk) {
1566 user := getserveruser()
1567 for _, ont := range honk.Onts {
1568 dubs := getnameddubs(readyLuserOne, ont)
1569 if len(dubs) == 0 {
1570 continue
1571 }
1572 j := junk.New()
1573 j["@context"] = itiswhatitis
1574 j["type"] = "Add"
1575 j["id"] = user.URL + "/add/" + shortxid(ont+honk.XID)
1576 j["actor"] = user.URL
1577 j["object"] = honk.XID
1578 j["target"] = fmt.Sprintf("https://%s/o/%s", serverName, ont[1:])
1579 rcpts := make(map[string]bool)
1580 for _, dub := range dubs {
1581 var box *Box
1582 ok := boxofboxes.Get(dub.XID, &box)
1583 if ok && box.Shared != "" {
1584 rcpts["%"+box.Shared] = true
1585 } else {
1586 rcpts[dub.XID] = true
1587 }
1588 }
1589 msg := j.ToBytes()
1590 for a := range rcpts {
1591 go deliverate(user.ID, a, msg)
1592 }
1593 }
1594}
1595
1596func junkuser(user *WhatAbout) junk.Junk {
1597 j := junk.New()
1598 j["@context"] = itiswhatitis
1599 j["id"] = user.URL
1600 j["inbox"] = user.URL + "/inbox"
1601 j["outbox"] = user.URL + "/outbox"
1602 j["name"] = user.Display
1603 j["preferredUsername"] = user.Name
1604 j["summary"] = user.HTAbout
1605 var tags []junk.Junk
1606 for _, o := range user.Onts {
1607 t := junk.New()
1608 t["type"] = "Hashtag"
1609 o = strings.ToLower(o)
1610 t["href"] = fmt.Sprintf("https://%s/o/%s", serverName, o[1:])
1611 t["name"] = o
1612 tags = append(tags, t)
1613 }
1614 if len(tags) > 0 {
1615 j["tag"] = tags
1616 }
1617
1618 if user.ID > 0 {
1619 j["type"] = "Person"
1620 j["url"] = user.URL
1621 j["followers"] = user.URL + "/followers"
1622 j["following"] = user.URL + "/following"
1623 a := junk.New()
1624 a["type"] = "Image"
1625 a["mediaType"] = "image/png"
1626 a["url"] = avatarURL(user)
1627 j["icon"] = a
1628 if ban := user.Options.Banner; ban != "" {
1629 a := junk.New()
1630 a["type"] = "Image"
1631 a["mediaType"] = "image/jpg"
1632 a["url"] = ban
1633 j["image"] = a
1634 }
1635 } else {
1636 j["type"] = "Service"
1637 }
1638 k := junk.New()
1639 k["id"] = user.URL + "#key"
1640 k["owner"] = user.URL
1641 k["publicKeyPem"] = user.Key
1642 j["publicKey"] = k
1643
1644 return j
1645}
1646
1647var oldjonkers = cache.New(cache.Options{Filler: func(name string) ([]byte, bool) {
1648 user, err := butwhatabout(name)
1649 if err != nil {
1650 return nil, false
1651 }
1652 j := junkuser(user)
1653 return j.ToBytes(), true
1654}, Duration: 1 * time.Minute})
1655
1656func asjonker(name string) ([]byte, bool) {
1657 var j []byte
1658 ok := oldjonkers.Get(name, &j)
1659 return j, ok
1660}
1661
1662var handfull = cache.New(cache.Options{Filler: func(name string) (string, bool) {
1663 m := strings.Split(name, "@")
1664 if len(m) != 2 {
1665 dlog.Printf("bad fish name: %s", name)
1666 return "", true
1667 }
1668 var href string
1669 row := stmtGetXonker.QueryRow(name, "fishname")
1670 err := row.Scan(&href)
1671 if err == nil {
1672 return href, true
1673 }
1674 dlog.Printf("fishing for %s", name)
1675 j, err := GetJunkFast(readyLuserOne, fmt.Sprintf("https://%s/.well-known/webfinger?resource=acct:%s", m[1], name))
1676 if err != nil {
1677 ilog.Printf("failed to go fish %s: %s", name, err)
1678 return "", true
1679 }
1680 links, _ := j.GetArray("links")
1681 for _, li := range links {
1682 l, ok := li.(junk.Junk)
1683 if !ok {
1684 continue
1685 }
1686 href, _ := l.GetString("href")
1687 rel, _ := l.GetString("rel")
1688 t, _ := l.GetString("type")
1689 if rel == "self" && friendorfoe(t) {
1690 when := time.Now().UTC().Format(dbtimeformat)
1691 _, err := stmtSaveXonker.Exec(name, href, "fishname", when)
1692 if err != nil {
1693 elog.Printf("error saving fishname: %s", err)
1694 }
1695 return href, true
1696 }
1697 }
1698 return href, true
1699}, Duration: 1 * time.Minute})
1700
1701func gofish(name string) string {
1702 if name[0] == '@' {
1703 name = name[1:]
1704 }
1705 var href string
1706 handfull.Get(name, &href)
1707 return href
1708}
1709
1710func investigate(name string) (*SomeThing, error) {
1711 if name == "" {
1712 return nil, fmt.Errorf("no name")
1713 }
1714 if name[0] == '@' {
1715 name = gofish(name)
1716 }
1717 if name == "" {
1718 return nil, fmt.Errorf("no name")
1719 }
1720 obj, err := GetJunkFast(readyLuserOne, name)
1721 if err != nil {
1722 return nil, err
1723 }
1724 allinjest(originate(name), obj)
1725 return somethingabout(obj)
1726}
1727
1728func somethingabout(obj junk.Junk) (*SomeThing, error) {
1729 info := new(SomeThing)
1730 t, _ := obj.GetString("type")
1731 isowned := false
1732 switch t {
1733 case "Person":
1734 fallthrough
1735 case "Group":
1736 fallthrough
1737 case "Organization":
1738 fallthrough
1739 case "Application":
1740 fallthrough
1741 case "Service":
1742 info.What = SomeActor
1743 case "OrderedCollection":
1744 isowned = true
1745 fallthrough
1746 case "Collection":
1747 info.What = SomeCollection
1748 default:
1749 return nil, fmt.Errorf("unknown object type")
1750 }
1751 info.XID, _ = obj.GetString("id")
1752 info.Name, _ = obj.GetString("preferredUsername")
1753 if info.Name == "" {
1754 info.Name, _ = obj.GetString("name")
1755 }
1756 if isowned {
1757 info.Owner, _ = obj.GetString("attributedTo")
1758 }
1759 if info.Owner == "" {
1760 info.Owner = info.XID
1761 }
1762 return info, nil
1763}
1764
1765func allinjest(origin string, obj junk.Junk) {
1766 keyobj, ok := obj.GetMap("publicKey")
1767 if ok {
1768 ingestpubkey(origin, keyobj)
1769 }
1770 ingestboxes(origin, obj)
1771 ingesthandle(origin, obj)
1772}
1773
1774func ingestpubkey(origin string, obj junk.Junk) {
1775 keyobj, ok := obj.GetMap("publicKey")
1776 if ok {
1777 obj = keyobj
1778 }
1779 keyname, ok := obj.GetString("id")
1780 var data string
1781 row := stmtGetXonker.QueryRow(keyname, "pubkey")
1782 err := row.Scan(&data)
1783 if err == nil {
1784 return
1785 }
1786 if !ok || origin != originate(keyname) {
1787 ilog.Printf("bad key origin %s <> %s", origin, keyname)
1788 return
1789 }
1790 dlog.Printf("ingesting a needed pubkey: %s", keyname)
1791 owner, ok := obj.GetString("owner")
1792 if !ok {
1793 ilog.Printf("error finding %s pubkey owner", keyname)
1794 return
1795 }
1796 data, ok = obj.GetString("publicKeyPem")
1797 if !ok {
1798 ilog.Printf("error finding %s pubkey", keyname)
1799 return
1800 }
1801 if originate(owner) != origin {
1802 ilog.Printf("bad key owner: %s <> %s", owner, origin)
1803 return
1804 }
1805 _, _, err = httpsig.DecodeKey(data)
1806 if err != nil {
1807 ilog.Printf("error decoding %s pubkey: %s", keyname, err)
1808 return
1809 }
1810 when := time.Now().UTC().Format(dbtimeformat)
1811 _, err = stmtSaveXonker.Exec(keyname, data, "pubkey", when)
1812 if err != nil {
1813 elog.Printf("error saving key: %s", err)
1814 }
1815}
1816
1817func ingestboxes(origin string, obj junk.Junk) {
1818 ident, _ := obj.GetString("id")
1819 if ident == "" {
1820 return
1821 }
1822 if originate(ident) != origin {
1823 return
1824 }
1825 var info string
1826 row := stmtGetXonker.QueryRow(ident, "boxes")
1827 err := row.Scan(&info)
1828 if err == nil {
1829 return
1830 }
1831 dlog.Printf("ingesting boxes: %s", ident)
1832 inbox, _ := obj.GetString("inbox")
1833 outbox, _ := obj.GetString("outbox")
1834 sbox, _ := obj.GetString("endpoints", "sharedInbox")
1835 if inbox != "" {
1836 when := time.Now().UTC().Format(dbtimeformat)
1837 m := strings.Join([]string{inbox, outbox, sbox}, " ")
1838 _, err = stmtSaveXonker.Exec(ident, m, "boxes", when)
1839 if err != nil {
1840 elog.Printf("error saving boxes: %s", err)
1841 }
1842 }
1843}
1844
1845func ingesthandle(origin string, obj junk.Junk) {
1846 xid, _ := obj.GetString("id")
1847 if xid == "" {
1848 return
1849 }
1850 if originate(xid) != origin {
1851 return
1852 }
1853 var handle string
1854 row := stmtGetXonker.QueryRow(xid, "handle")
1855 err := row.Scan(&handle)
1856 if err == nil {
1857 return
1858 }
1859 handle, _ = obj.GetString("preferredUsername")
1860 if handle != "" {
1861 when := time.Now().UTC().Format(dbtimeformat)
1862 _, err = stmtSaveXonker.Exec(xid, handle, "handle", when)
1863 if err != nil {
1864 elog.Printf("error saving handle: %s", err)
1865 }
1866 }
1867}
1868
1869func updateMe(username string) {
1870 var user *WhatAbout
1871 somenamedusers.Get(username, &user)
1872 dt := time.Now().UTC().Format(time.RFC3339)
1873 j := junk.New()
1874 j["@context"] = itiswhatitis
1875 j["id"] = fmt.Sprintf("%s/upme/%s/%d", user.URL, user.Name, time.Now().Unix())
1876 j["actor"] = user.URL
1877 j["published"] = dt
1878 j["to"] = thewholeworld
1879 j["type"] = "Update"
1880 j["object"] = junkuser(user)
1881
1882 msg := j.ToBytes()
1883
1884 rcpts := make(map[string]bool)
1885 for _, f := range getdubs(user.ID) {
1886 if f.XID == user.URL {
1887 continue
1888 }
1889 var box *Box
1890 boxofboxes.Get(f.XID, &box)
1891 if box != nil && box.Shared != "" {
1892 rcpts["%"+box.Shared] = true
1893 } else {
1894 rcpts[f.XID] = true
1895 }
1896 }
1897 for a := range rcpts {
1898 go deliverate(user.ID, a, msg)
1899 }
1900}
1901
1902func followme(user *WhatAbout, who string, name string, j junk.Junk) {
1903 folxid, _ := j.GetString("id")
1904
1905 ilog.Printf("updating honker follow: %s %s", who, folxid)
1906
1907 var x string
1908 db := opendatabase()
1909 row := db.QueryRow("select xid from honkers where name = ? and xid = ? and userid = ? and flavor in ('dub', 'undub')", name, who, user.ID)
1910 err := row.Scan(&x)
1911 if err != sql.ErrNoRows {
1912 ilog.Printf("duplicate follow request: %s", who)
1913 _, err = stmtUpdateFlavor.Exec("dub", folxid, user.ID, name, who, "undub")
1914 if err != nil {
1915 elog.Printf("error updating honker: %s", err)
1916 }
1917 } else {
1918 stmtSaveDub.Exec(user.ID, name, who, "dub", folxid)
1919 }
1920 go rubadubdub(user, j)
1921}
1922
1923func unfollowme(user *WhatAbout, who string, name string, j junk.Junk) {
1924 var folxid string
1925 if who == "" {
1926 folxid, _ = j.GetString("object")
1927
1928 db := opendatabase()
1929 row := db.QueryRow("select xid, name from honkers where userid = ? and folxid = ? and flavor in ('dub', 'undub')", user.ID, folxid)
1930 err := row.Scan(&who, &name)
1931 if err != nil {
1932 if err != sql.ErrNoRows {
1933 elog.Printf("error scanning honker: %s", err)
1934 }
1935 return
1936 }
1937 }
1938
1939 ilog.Printf("updating honker undo: %s %s", who, folxid)
1940 _, err := stmtUpdateFlavor.Exec("undub", folxid, user.ID, name, who, "dub")
1941 if err != nil {
1942 elog.Printf("error updating honker: %s", err)
1943 return
1944 }
1945}
1946
1947func followyou(user *WhatAbout, honkerid int64, sync bool) {
1948 var url, owner string
1949 db := opendatabase()
1950 row := db.QueryRow("select xid, owner from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1951 honkerid, user.ID)
1952 err := row.Scan(&url, &owner)
1953 if err != nil {
1954 elog.Printf("can't get honker xid: %s", err)
1955 return
1956 }
1957 folxid := xfiltrate()
1958 ilog.Printf("subscribing to %s", url)
1959 _, err = db.Exec("update honkers set flavor = ?, folxid = ? where honkerid = ?", "presub", folxid, honkerid)
1960 if err != nil {
1961 elog.Printf("error updating honker: %s", err)
1962 return
1963 }
1964 if sync {
1965 subsub(user, url, owner, folxid)
1966 } else {
1967 go subsub(user, url, owner, folxid)
1968 }
1969
1970}
1971func unfollowyou(user *WhatAbout, honkerid int64, sync bool) {
1972 db := opendatabase()
1973 row := db.QueryRow("select xid, owner, folxid, flavor from honkers where honkerid = ? and userid = ? and flavor in ('unsub', 'peep', 'presub', 'sub')",
1974 honkerid, user.ID)
1975 var url, owner, folxid, flavor string
1976 err := row.Scan(&url, &owner, &folxid, &flavor)
1977 if err != nil {
1978 elog.Printf("can't get honker xid: %s", err)
1979 return
1980 }
1981 if flavor == "peep" {
1982 return
1983 }
1984 ilog.Printf("unsubscribing from %s", url)
1985 _, err = db.Exec("update honkers set flavor = ? where honkerid = ?", "unsub", honkerid)
1986 if err != nil {
1987 elog.Printf("error updating honker: %s", err)
1988 return
1989 }
1990 if sync {
1991 itakeitallback(user, url, owner, folxid)
1992 } else {
1993 go itakeitallback(user, url, owner, folxid)
1994 }
1995}
1996
1997func followyou2(user *WhatAbout, j junk.Junk) {
1998 who, _ := j.GetString("actor")
1999
2000 ilog.Printf("updating honker accept: %s", who)
2001 db := opendatabase()
2002 row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
2003 user.ID, who)
2004 var name, folxid string
2005 err := row.Scan(&name, &folxid)
2006 if err != nil {
2007 elog.Printf("can't get honker name: %s", err)
2008 return
2009 }
2010 _, err = stmtUpdateFlavor.Exec("sub", folxid, user.ID, name, who, "presub")
2011 if err != nil {
2012 elog.Printf("error updating honker: %s", err)
2013 return
2014 }
2015}
2016
2017func nofollowyou2(user *WhatAbout, j junk.Junk) {
2018 who, _ := j.GetString("actor")
2019
2020 ilog.Printf("updating honker reject: %s", who)
2021 db := opendatabase()
2022 row := db.QueryRow("select name, folxid from honkers where userid = ? and xid = ? and flavor in ('presub', 'sub')",
2023 user.ID, who)
2024 var name, folxid string
2025 err := row.Scan(&name, &folxid)
2026 if err != nil {
2027 elog.Printf("can't get honker name: %s", err)
2028 return
2029 }
2030 _, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "presub")
2031 _, err = stmtUpdateFlavor.Exec("unsub", folxid, user.ID, name, who, "sub")
2032 if err != nil {
2033 elog.Printf("error updating honker: %s", err)
2034 return
2035 }
2036}