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