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