all repos — honk @ 3de7c947b5afce00bf72cee2ec99e7041800b511

my fork of honk

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	"compress/gzip"
 21	"crypto/rsa"
 22	"database/sql"
 23	"encoding/json"
 24	"fmt"
 25	"io"
 26	"log"
 27	"net/http"
 28	"net/url"
 29	"os"
 30	"strconv"
 31	"strings"
 32	"sync"
 33	"time"
 34)
 35
 36func NewJunk() map[string]interface{} {
 37	return make(map[string]interface{})
 38}
 39
 40func WriteJunk(w io.Writer, j map[string]interface{}) error {
 41	e := json.NewEncoder(w)
 42	e.SetEscapeHTML(false)
 43	e.SetIndent("", "  ")
 44	err := e.Encode(j)
 45	return err
 46}
 47
 48func ReadJunk(r io.Reader) (map[string]interface{}, error) {
 49	decoder := json.NewDecoder(r)
 50	var j map[string]interface{}
 51	err := decoder.Decode(&j)
 52	if err != nil {
 53		return nil, err
 54	}
 55	return j, nil
 56}
 57
 58var theonetruename = `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`
 59var falsenames = []string{
 60	`application/ld+json`,
 61	`application/activity+json`,
 62}
 63var itiswhatitis = "https://www.w3.org/ns/activitystreams"
 64var thewholeworld = "https://www.w3.org/ns/activitystreams#Public"
 65
 66func friendorfoe(ct string) bool {
 67	ct = strings.ToLower(ct)
 68	for _, at := range falsenames {
 69		if strings.HasPrefix(ct, at) {
 70			return true
 71		}
 72	}
 73	return false
 74}
 75
 76func PostJunk(keyname string, key *rsa.PrivateKey, url string, j map[string]interface{}) error {
 77	var buf bytes.Buffer
 78	WriteJunk(&buf, j)
 79	return PostMsg(keyname, key, url, buf.Bytes())
 80}
 81
 82func PostMsg(keyname string, key *rsa.PrivateKey, url string, msg []byte) error {
 83	client := http.DefaultClient
 84	req, err := http.NewRequest("POST", url, bytes.NewReader(msg))
 85	if err != nil {
 86		return err
 87	}
 88	req.Header.Set("Content-Type", theonetruename)
 89	zig(keyname, key, req, msg)
 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	log.Printf("successful post: %s %d", url, resp.StatusCode)
103	return nil
104}
105
106type gzCloser struct {
107	r     *gzip.Reader
108	under io.ReadCloser
109}
110
111func (gz *gzCloser) Read(p []byte) (int, error) {
112	return gz.r.Read(p)
113}
114
115func (gz *gzCloser) Close() error {
116	defer gz.under.Close()
117	return gz.r.Close()
118}
119
120func GetJunk(url string) (map[string]interface{}, error) {
121	client := http.DefaultClient
122	req, err := http.NewRequest("GET", url, nil)
123	if err != nil {
124		return nil, err
125	}
126	at := theonetruename
127	if strings.Contains(url, ".well-known/webfinger?resource") {
128		at = "application/jrd+json"
129	}
130	req.Header.Set("Accept", at)
131	req.Header.Set("Accept-Encoding", "gzip")
132	resp, err := client.Do(req)
133	if err != nil {
134		return nil, err
135	}
136	if resp.StatusCode != 200 {
137		resp.Body.Close()
138		return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
139	}
140	if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
141		gz, err := gzip.NewReader(resp.Body)
142		if err != nil {
143			resp.Body.Close()
144			return nil, err
145		}
146		resp.Body = &gzCloser{r: gz, under: resp.Body}
147	}
148	defer resp.Body.Close()
149	j, err := ReadJunk(resp.Body)
150	return j, err
151}
152
153func jsonfindinterface(ii interface{}, keys []string) interface{} {
154	for _, key := range keys {
155		idx, err := strconv.Atoi(key)
156		if err == nil {
157			m := ii.([]interface{})
158			if idx >= len(m) {
159				return nil
160			}
161			ii = m[idx]
162		} else {
163			m := ii.(map[string]interface{})
164			ii = m[key]
165			if ii == nil {
166				return nil
167			}
168		}
169	}
170	return ii
171}
172func jsonfindstring(j interface{}, keys []string) (string, bool) {
173	s, ok := jsonfindinterface(j, keys).(string)
174	return s, ok
175}
176func jsonfindarray(j interface{}, keys []string) ([]interface{}, bool) {
177	a, ok := jsonfindinterface(j, keys).([]interface{})
178	return a, ok
179}
180func jsonfindmap(j interface{}, keys []string) (map[string]interface{}, bool) {
181	m, ok := jsonfindinterface(j, keys).(map[string]interface{})
182	return m, ok
183}
184func jsongetstring(j interface{}, key string) (string, bool) {
185	return jsonfindstring(j, []string{key})
186}
187func jsongetarray(j interface{}, key string) ([]interface{}, bool) {
188	return jsonfindarray(j, []string{key})
189}
190func jsongetmap(j interface{}, key string) (map[string]interface{}, bool) {
191	return jsonfindmap(j, []string{key})
192}
193
194func savedonk(url string, name, media string) *Donk {
195	var donk Donk
196	row := stmtFindFile.QueryRow(url)
197	err := row.Scan(&donk.FileID)
198	if err == nil {
199		return &donk
200	}
201	log.Printf("saving donk: %s", url)
202	if err != nil && err != sql.ErrNoRows {
203		log.Printf("error querying: %s", err)
204	}
205	resp, err := http.Get(url)
206	if err != nil {
207		log.Printf("error fetching %s: %s", url, err)
208		return nil
209	}
210	defer resp.Body.Close()
211	if resp.StatusCode != 200 {
212		return nil
213	}
214	var buf bytes.Buffer
215	io.Copy(&buf, resp.Body)
216
217	xid := xfiltrate()
218
219	res, err := stmtSaveFile.Exec(xid, name, url, media, buf.Bytes())
220	if err != nil {
221		log.Printf("error saving file %s: %s", url, err)
222		return nil
223	}
224	donk.FileID, _ = res.LastInsertId()
225	return &donk
226}
227
228func needxonk(user *WhatAbout, x *Honk) bool {
229	if strings.HasPrefix(x.XID, user.URL+"/h/") {
230		return false
231	}
232	if x.What == "eradicate" {
233		return true
234	}
235	row := stmtFindXonk.QueryRow(user.ID, x.XID)
236	err := row.Scan(&x.ID)
237	if err == nil {
238		return false
239	}
240	if err != sql.ErrNoRows {
241		log.Printf("err querying xonk: %s", err)
242	}
243	return true
244}
245
246func savexonk(x *Honk) {
247	if x.What == "eradicate" {
248		log.Printf("eradicating %s by %s", x.RID, x.Honker)
249		_, err := stmtDeleteHonk.Exec(x.RID, x.Honker)
250		if err != nil {
251			log.Printf("error eradicating: %s", err)
252		}
253		return
254	}
255	dt := x.Date.UTC().Format(dbtimeformat)
256	aud := strings.Join(x.Audience, " ")
257	res, err := stmtSaveHonk.Exec(x.UserID, x.What, x.Honker, x.XID, x.RID, dt, x.URL, aud, x.Noise, x.Convoy)
258	if err != nil {
259		log.Printf("err saving xonk: %s", err)
260		return
261	}
262	x.ID, _ = res.LastInsertId()
263	for _, d := range x.Donks {
264		_, err = stmtSaveDonk.Exec(x.ID, d.FileID)
265		if err != nil {
266			log.Printf("err saving donk: %s", err)
267			return
268		}
269	}
270}
271
272type Box struct {
273	In     string
274	Out    string
275	Shared string
276}
277
278var boxofboxes = make(map[string]*Box)
279var boxlock sync.Mutex
280var boxinglock sync.Mutex
281
282func getboxes(ident string) (*Box, error) {
283	boxlock.Lock()
284	b, ok := boxofboxes[ident]
285	boxlock.Unlock()
286	if ok {
287		return b, nil
288	}
289
290	boxinglock.Lock()
291	defer boxinglock.Unlock()
292
293	boxlock.Lock()
294	b, ok = boxofboxes[ident]
295	boxlock.Unlock()
296	if ok {
297		return b, nil
298	}
299
300	j, err := GetJunk(ident)
301	if err != nil {
302		return nil, err
303	}
304	inbox, _ := jsongetstring(j, "inbox")
305	outbox, _ := jsongetstring(j, "outbox")
306	sbox, _ := jsonfindstring(j, []string{"endpoints", "sharedInbox"})
307	b = &Box{In: inbox, Out: outbox, Shared: sbox}
308	boxlock.Lock()
309	boxofboxes[ident] = b
310	boxlock.Unlock()
311	return b, nil
312}
313
314func peeppeep() {
315	user, _ := butwhatabout("htest")
316	honkers := gethonkers(user.ID)
317	for _, f := range honkers {
318		if f.Flavor != "peep" {
319			continue
320		}
321		log.Printf("getting updates: %s", f.XID)
322		box, err := getboxes(f.XID)
323		if err != nil {
324			log.Printf("error getting outbox: %s", err)
325			continue
326		}
327		log.Printf("getting outbox")
328		j, err := GetJunk(box.Out)
329		if err != nil {
330			log.Printf("err: %s", err)
331			continue
332		}
333		t, _ := jsongetstring(j, "type")
334		if t == "OrderedCollection" {
335			items, _ := jsongetarray(j, "orderedItems")
336			if items == nil {
337				page1, _ := jsongetstring(j, "first")
338				j, err = GetJunk(page1)
339				if err != nil {
340					log.Printf("err: %s", err)
341					continue
342				}
343				items, _ = jsongetarray(j, "orderedItems")
344			}
345
346			for _, item := range items {
347				xonk := xonkxonk(item)
348				if xonk != nil && needxonk(user, xonk) {
349					xonk.UserID = user.ID
350					savexonk(xonk)
351				}
352			}
353		}
354	}
355}
356
357func whosthere(xid string) ([]string, string) {
358	obj, err := GetJunk(xid)
359	if err != nil {
360		log.Printf("error getting remote xonk: %s", err)
361		return nil, ""
362	}
363	convoy, _ := jsongetstring(obj, "context")
364	if convoy == "" {
365		convoy, _ = jsongetstring(obj, "conversation")
366	}
367	return newphone(nil, obj), convoy
368}
369
370func newphone(a []string, obj map[string]interface{}) []string {
371	for _, addr := range []string{"to", "cc", "attributedTo"} {
372		who, _ := jsongetstring(obj, addr)
373		if who != "" {
374			a = append(a, who)
375		}
376		whos, _ := jsongetarray(obj, addr)
377		for _, w := range whos {
378			who, _ := w.(string)
379			if who != "" {
380				a = append(a, who)
381			}
382		}
383	}
384	return a
385}
386
387func xonkxonk(item interface{}) *Honk {
388	// id, _ := jsongetstring(item, "id")
389	what, _ := jsongetstring(item, "type")
390	dt, _ := jsongetstring(item, "published")
391
392	var audience []string
393	var err error
394	var xid, rid, url, content, convoy string
395	var obj map[string]interface{}
396	switch what {
397	case "Announce":
398		xid, _ = jsongetstring(item, "object")
399		log.Printf("getting bonk: %s", xid)
400		obj, err = GetJunk(xid)
401		if err != nil {
402			log.Printf("error regetting: %s", err)
403		}
404		what = "bonk"
405	case "Create":
406		obj, _ = jsongetmap(item, "object")
407		what = "honk"
408	case "Delete":
409		obj, _ = jsongetmap(item, "object")
410		rid, _ = jsongetstring(item, "object")
411		what = "eradicate"
412	default:
413		log.Printf("unknown activity: %s", what)
414		return nil
415	}
416	who, _ := jsongetstring(item, "actor")
417
418	var xonk Honk
419	if obj != nil {
420		ot, _ := jsongetstring(obj, "type")
421		url, _ = jsongetstring(obj, "url")
422		if ot == "Note" || ot == "Article" {
423			audience = newphone(audience, obj)
424			xid, _ = jsongetstring(obj, "id")
425			content, _ = jsongetstring(obj, "content")
426			summary, _ := jsongetstring(obj, "summary")
427			if summary != "" {
428				content = "<p>summary: " + summary + content
429			}
430			rid, _ = jsongetstring(obj, "inReplyTo")
431			convoy, _ = jsongetstring(obj, "context")
432			if convoy == "" {
433				convoy, _ = jsongetstring(obj, "conversation")
434			}
435			if what == "honk" && rid != "" {
436				what = "tonk"
437			}
438		}
439		if ot == "Tombstone" {
440			rid, _ = jsongetstring(obj, "id")
441		}
442		atts, _ := jsongetarray(obj, "attachment")
443		for _, att := range atts {
444			at, _ := jsongetstring(att, "type")
445			mt, _ := jsongetstring(att, "mediaType")
446			u, _ := jsongetstring(att, "url")
447			name, _ := jsongetstring(att, "name")
448			if at == "Document" {
449				mt = strings.ToLower(mt)
450				log.Printf("attachment: %s %s", mt, u)
451				if mt == "image/jpeg" || mt == "image/png" ||
452					mt == "image/gif" || mt == "text/plain" {
453					donk := savedonk(u, name, mt)
454					if donk != nil {
455						xonk.Donks = append(xonk.Donks, donk)
456					}
457				}
458			}
459		}
460		tags, _ := jsongetarray(obj, "tag")
461		for _, tag := range tags {
462			tt, _ := jsongetstring(tag, "type")
463			name, _ := jsongetstring(tag, "name")
464			if tt == "Emoji" {
465				icon, _ := jsongetmap(tag, "icon")
466				mt, _ := jsongetstring(icon, "mediaType")
467				u, _ := jsongetstring(icon, "url")
468				donk := savedonk(u, name, mt)
469				if donk != nil {
470					xonk.Donks = append(xonk.Donks, donk)
471				}
472			}
473		}
474	}
475	audience = append(audience, who)
476
477	audience = oneofakind(audience)
478
479	xonk.What = what
480	xonk.Honker = who
481	xonk.XID = xid
482	xonk.RID = rid
483	xonk.Date, _ = time.Parse(time.RFC3339, dt)
484	xonk.URL = url
485	xonk.Noise = content
486	xonk.Audience = audience
487	xonk.Convoy = convoy
488
489	return &xonk
490}
491
492func rubadubdub(user *WhatAbout, req map[string]interface{}) {
493	xid, _ := jsongetstring(req, "id")
494	reqactor, _ := jsongetstring(req, "actor")
495	j := NewJunk()
496	j["@context"] = itiswhatitis
497	j["id"] = user.URL + "/dub/" + xid
498	j["type"] = "Accept"
499	j["actor"] = user.URL
500	j["to"] = reqactor
501	j["published"] = time.Now().UTC().Format(time.RFC3339)
502	j["object"] = req
503
504	WriteJunk(os.Stdout, j)
505
506	actor, _ := jsongetstring(req, "actor")
507	box, err := getboxes(actor)
508	if err != nil {
509		log.Printf("can't get dub box: %s", err)
510		return
511	}
512	keyname, key := ziggy(user.Name)
513	err = PostJunk(keyname, key, box.In, j)
514	if err != nil {
515		log.Printf("can't rub a dub: %s", err)
516		return
517	}
518	stmtSaveDub.Exec(user.ID, actor, actor, "dub")
519}
520
521func subsub(user *WhatAbout, xid string) {
522	j := NewJunk()
523	j["@context"] = itiswhatitis
524	j["id"] = user.URL + "/sub/" + xid
525	j["type"] = "Follow"
526	j["actor"] = user.URL
527	j["to"] = xid
528	j["object"] = xid
529	j["published"] = time.Now().UTC().Format(time.RFC3339)
530
531	box, err := getboxes(xid)
532	if err != nil {
533		log.Printf("can't send follow: %s", err)
534		return
535	}
536	WriteJunk(os.Stdout, j)
537	keyname, key := ziggy(user.Name)
538	err = PostJunk(keyname, key, box.In, j)
539	if err != nil {
540		log.Printf("failed to subsub: %s", err)
541	}
542}
543
544func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
545	dt := h.Date.Format(time.RFC3339)
546	var jo map[string]interface{}
547	j := NewJunk()
548	j["id"] = user.URL + "/" + h.What + "/" + h.XID
549	j["actor"] = user.URL
550	j["published"] = dt
551	j["to"] = h.Audience[0]
552	if len(h.Audience) > 1 {
553		j["cc"] = h.Audience[1:]
554	}
555
556	switch h.What {
557	case "zonk":
558		fallthrough
559	case "tonk":
560		fallthrough
561	case "honk":
562		j["type"] = "Create"
563		if h.What == "zonk" {
564			j["type"] = "Delete"
565		}
566
567		jo = NewJunk()
568		jo["id"] = user.URL + "/h/" + h.XID
569		jo["type"] = "Note"
570		if h.What == "zonk" {
571			jo["type"] = "Tombstone"
572		}
573		jo["published"] = dt
574		jo["url"] = user.URL + "/h/" + h.XID
575		jo["attributedTo"] = user.URL
576		if h.RID != "" {
577			jo["inReplyTo"] = h.RID
578		}
579		if h.Convoy != "" {
580			jo["context"] = h.Convoy
581			jo["conversation"] = h.Convoy
582		}
583		jo["to"] = h.Audience[0]
584		if len(h.Audience) > 1 {
585			jo["cc"] = h.Audience[1:]
586		}
587		jo["content"] = h.Noise
588		jo["summary"] = nil
589		var tags []interface{}
590		g := bunchofgrapes(h.Noise)
591		for _, m := range g {
592			t := NewJunk()
593			t["type"] = "Mention"
594			t["name"] = m.who
595			t["href"] = m.where
596			tags = append(tags, t)
597		}
598		herd := herdofemus(h.Noise)
599		for _, e := range herd {
600			t := NewJunk()
601			t["id"] = e.ID
602			t["type"] = "Emoji"
603			t["name"] = e.Name
604			i := NewJunk()
605			i["type"] = "Image"
606			i["mediaType"] = "image/png"
607			i["url"] = e.ID
608			t["icon"] = i
609			tags = append(tags, t)
610		}
611		if len(tags) > 0 {
612			jo["tag"] = tags
613		}
614		var atts []interface{}
615		for _, d := range h.Donks {
616			if re_emus.MatchString(d.Name) {
617				continue
618			}
619			jd := NewJunk()
620			jd["mediaType"] = d.Media
621			jd["name"] = d.Name
622			jd["type"] = "Document"
623			jd["url"] = d.URL
624			atts = append(atts, jd)
625		}
626		if len(atts) > 0 {
627			jo["attachment"] = atts
628		}
629		j["object"] = jo
630	case "bonk":
631		j["type"] = "Announce"
632		j["object"] = h.XID
633	}
634
635	return j, jo
636}
637
638func honkworldwide(user *WhatAbout, honk *Honk) {
639	jonk, _ := jonkjonk(user, honk)
640	jonk["@context"] = itiswhatitis
641	var buf bytes.Buffer
642	WriteJunk(&buf, jonk)
643	msg := buf.Bytes()
644
645	rcpts := make(map[string]bool)
646	for _, a := range honk.Audience {
647		if a != thewholeworld && a != user.URL && !strings.HasSuffix(a, "/followers") {
648			box, _ := getboxes(a)
649			if box != nil && box.Shared != "" {
650				rcpts["%"+box.Shared] = true
651			} else {
652				rcpts[a] = true
653			}
654		}
655	}
656	for _, f := range getdubs(user.ID) {
657		box, _ := getboxes(f.XID)
658		if box != nil && box.Shared != "" {
659			rcpts["%"+box.Shared] = true
660		} else {
661			rcpts[f.XID] = true
662		}
663	}
664	for a := range rcpts {
665		go deliverate(0, user.Name, a, msg)
666	}
667}
668
669func asjonker(user *WhatAbout) map[string]interface{} {
670	about := obfusbreak(user.About)
671
672	j := NewJunk()
673	j["@context"] = itiswhatitis
674	j["id"] = user.URL
675	j["type"] = "Person"
676	j["inbox"] = user.URL + "/inbox"
677	j["outbox"] = user.URL + "/outbox"
678	j["name"] = user.Display
679	j["preferredUsername"] = user.Name
680	j["summary"] = about
681	j["url"] = user.URL
682	a := NewJunk()
683	a["type"] = "icon"
684	a["mediaType"] = "image/png"
685	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
686	j["icon"] = a
687	k := NewJunk()
688	k["id"] = user.URL + "#key"
689	k["owner"] = user.URL
690	k["publicKeyPem"] = user.Key
691	j["publicKey"] = k
692
693	return j
694}