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