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