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