all repos — honk @ 5f4d66abf891b0db6b3e5542ae19b22464347200

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