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