all repos — honk @ 22de29fa196462c93a85aeb15329d01955a9596a

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