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