all repos — honk @ v0.1.1

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	zig(keyname, key, req, buf.Bytes())
 86	req.Header.Set("Content-Type", theonetruename)
 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 newphone(a []string, obj map[string]interface{}) []string {
331	for _, addr := range []string{"to", "cc", "attributedTo"} {
332		who, _ := jsongetstring(obj, addr)
333		if who != "" {
334			a = append(a, who)
335		}
336		whos, _ := jsongetarray(obj, addr)
337		for _, w := range whos {
338			who, _ := w.(string)
339			if who != "" {
340				a = append(a, who)
341			}
342		}
343	}
344	return a
345}
346
347func oneofakind(a []string) []string {
348	var x []string
349	for n, s := range a {
350		for i := n + 1; i < len(a); i++ {
351			if a[i] == s {
352				a[i] = ""
353			}
354		}
355	}
356	for _, s := range a {
357		if s != "" {
358			x = append(x, s)
359		}
360	}
361	return x
362}
363
364func xonkxonk(item interface{}) *Honk {
365
366	// id, _ := jsongetstring(item, "id")
367	what, _ := jsongetstring(item, "type")
368	dt, _ := jsongetstring(item, "published")
369
370	var audience []string
371	var err error
372	var xid, rid, url, content string
373	var obj map[string]interface{}
374	switch what {
375	case "Announce":
376		xid, _ = jsongetstring(item, "object")
377		log.Printf("getting bonk: %s", xid)
378		obj, err = GetJunk(xid)
379		if err != nil {
380			log.Printf("error regetting: %s", err)
381		}
382		what = "bonk"
383	case "Create":
384		obj, _ = jsongetmap(item, "object")
385		what = "honk"
386	case "Delete":
387		obj, _ = jsongetmap(item, "object")
388		what = "eradicate"
389	default:
390		log.Printf("unknown activity: %s", what)
391		return nil
392	}
393	who, _ := jsongetstring(item, "actor")
394
395	var xonk Honk
396	if obj != nil {
397		ot, _ := jsongetstring(obj, "type")
398		url, _ = jsongetstring(obj, "url")
399		if ot == "Note" {
400			audience = newphone(audience, obj)
401			xid, _ = jsongetstring(obj, "id")
402			content, _ = jsongetstring(obj, "content")
403			rid, _ = jsongetstring(obj, "inReplyTo")
404			if what == "honk" && rid != "" {
405				what = "tonk"
406			}
407		}
408		if ot == "Tombstone" {
409			rid, _ = jsongetstring(obj, "id")
410		}
411		atts, _ := jsongetarray(obj, "attachment")
412		for _, att := range atts {
413			at, _ := jsongetstring(att, "type")
414			mt, _ := jsongetstring(att, "mediaType")
415			u, _ := jsongetstring(att, "url")
416			name, _ := jsongetstring(att, "name")
417			if at == "Document" {
418				mt = strings.ToLower(mt)
419				log.Printf("attachment: %s %s", mt, u)
420				if mt == "image/jpeg" || mt == "image/png" ||
421					mt == "image/gif" {
422					donk := savedonk(u, name, mt)
423					if donk != nil {
424						xonk.Donks = append(xonk.Donks, donk)
425					}
426				}
427			}
428		}
429	}
430	audience = append(audience, who)
431
432	audience = oneofakind(audience)
433
434	xonk.What = what
435	xonk.Honker = who
436	xonk.XID = xid
437	xonk.RID = rid
438	xonk.Date, _ = time.Parse(time.RFC3339, dt)
439	xonk.URL = url
440	xonk.Noise = content
441	xonk.Audience = audience
442
443	return &xonk
444}
445
446func rubadubdub(user *WhatAbout, req map[string]interface{}) {
447	xid, _ := jsongetstring(req, "id")
448	reqactor, _ := jsongetstring(req, "actor")
449	j := NewJunk()
450	j["@context"] = itiswhatitis
451	j["id"] = user.URL + "/dub/" + xid
452	j["type"] = "Accept"
453	j["actor"] = user.URL
454	j["to"] = reqactor
455	j["published"] = time.Now().UTC().Format(time.RFC3339)
456	j["object"] = req
457
458	WriteJunk(os.Stdout, j)
459
460	actor, _ := jsongetstring(req, "actor")
461	inbox, _, err := getboxes(actor)
462	if err != nil {
463		log.Printf("can't get dub box: %s", err)
464		return
465	}
466	keyname, key := ziggy(user)
467	err = PostJunk(keyname, key, inbox, j)
468	if err != nil {
469		log.Printf("can't rub a dub: %s", err)
470		return
471	}
472	stmtSaveDub.Exec(user.ID, actor, actor, "dub")
473}
474
475func subsub(user *WhatAbout, xid string) {
476
477	j := NewJunk()
478	j["@context"] = itiswhatitis
479	j["id"] = user.URL + "/sub/" + xid
480	j["type"] = "Follow"
481	j["actor"] = user.URL
482	j["to"] = xid
483	j["object"] = xid
484	j["published"] = time.Now().UTC().Format(time.RFC3339)
485
486	inbox, _, err := getboxes(xid)
487	if err != nil {
488		log.Printf("can't send follow: %s", err)
489		return
490	}
491	WriteJunk(os.Stdout, j)
492	keyname, key := ziggy(user)
493	err = PostJunk(keyname, key, inbox, j)
494	if err != nil {
495		log.Printf("failed to subsub: %s", err)
496	}
497}
498
499func jonkjonk(user *WhatAbout, h *Honk) (map[string]interface{}, map[string]interface{}) {
500	dt := h.Date.Format(time.RFC3339)
501	var jo map[string]interface{}
502	j := NewJunk()
503	j["id"] = user.URL + "/" + h.What + "/" + h.XID
504	j["actor"] = user.URL
505	j["published"] = dt
506	j["to"] = h.Audience[0]
507	if len(h.Audience) > 1 {
508		j["cc"] = h.Audience[1:]
509	}
510
511	switch h.What {
512	case "tonk":
513		fallthrough
514	case "honk":
515		j["type"] = "Create"
516		jo = NewJunk()
517		jo["id"] = user.URL + "/h/" + h.XID
518		jo["type"] = "Note"
519		jo["published"] = dt
520		jo["url"] = user.URL + "/h/" + h.XID
521		jo["attributedTo"] = user.URL
522		if h.RID != "" {
523			jo["inReplyTo"] = h.RID
524		}
525		jo["to"] = h.Audience[0]
526		if len(h.Audience) > 1 {
527			jo["cc"] = h.Audience[1:]
528		}
529		jo["content"] = h.Noise
530		g := bunchofgrapes(h.Noise)
531		if len(g) > 0 {
532			var tags []interface{}
533			for _, m := range g {
534				t := NewJunk()
535				t["type"] = "Mention"
536				t["name"] = m.who
537				t["href"] = m.where
538				tags = append(tags, t)
539			}
540			jo["tag"] = tags
541		}
542		var atts []interface{}
543		for _, d := range h.Donks {
544			jd := NewJunk()
545			jd["mediaType"] = d.Media
546			jd["name"] = d.Name
547			jd["type"] = "Document"
548			jd["url"] = d.URL
549			atts = append(atts, jd)
550		}
551		if len(atts) > 0 {
552			jo["attachment"] = atts
553		}
554		j["object"] = jo
555	case "bonk":
556		j["type"] = "Announce"
557		j["object"] = h.XID
558	}
559
560	return j, jo
561}
562
563func honkworldwide(user *WhatAbout, honk *Honk) {
564	aud := append([]string{}, honk.Audience...)
565	for i, a := range aud {
566		if a == thewholeworld || a == user.URL {
567			aud[i] = ""
568		}
569	}
570	keyname, key := ziggy(user)
571	jonk, _ := jonkjonk(user, honk)
572	jonk["@context"] = itiswhatitis
573	for _, f := range getdubs(user.ID) {
574		inbox, _, err := getboxes(f.XID)
575		if err != nil {
576			log.Printf("error getting inbox %s: %s", f.XID, err)
577			continue
578		}
579		err = PostJunk(keyname, key, inbox, jonk)
580		if err != nil {
581			log.Printf("failed to post json to %s: %s", inbox, err)
582		}
583		for i, a := range aud {
584			if a == f.XID {
585				aud[i] = ""
586			}
587		}
588	}
589	for _, a := range aud {
590		if a != "" && !strings.HasSuffix(a, "/followers") {
591			inbox, _, err := getboxes(a)
592			if err != nil {
593				log.Printf("error getting inbox %s: %s", a, err)
594				continue
595			}
596			err = PostJunk(keyname, key, inbox, jonk)
597			if err != nil {
598				log.Printf("failed to post json to %s: %s", inbox, err)
599			}
600		}
601	}
602}
603
604func asjonker(user *WhatAbout) map[string]interface{} {
605	whatabout := obfusbreak(user.About)
606
607	j := NewJunk()
608	j["@context"] = itiswhatitis
609	j["id"] = user.URL
610	j["type"] = "Person"
611	j["inbox"] = user.URL + "/inbox"
612	j["outbox"] = user.URL + "/outbox"
613	j["name"] = user.Display
614	j["preferredUsername"] = user.Name
615	j["summary"] = whatabout
616	j["url"] = user.URL
617	a := NewJunk()
618	a["type"] = "icon"
619	a["mediaType"] = "image/png"
620	a["url"] = fmt.Sprintf("https://%s/a?a=%s", serverName, url.QueryEscape(user.URL))
621	j["icon"] = a
622	k := NewJunk()
623	k["id"] = user.URL + "#key"
624	k["owner"] = user.URL
625	k["publicKeyPem"] = user.Key
626	j["publicKey"] = k
627
628	return j
629}