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