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