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