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