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