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