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