all repos — honk @ c06fdf138ba5bb3f4765ed3305663157aa8a38ec

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