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