all repos — honk @ 4f00542fd6ab7201c56fb9c885b334debcae7e93

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