all repos — honk @ b162076c4d37bcff6770ff1ca9299b66d5752b2b

my fork of honk

fun.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	"crypto/rand"
 20	"crypto/rsa"
 21	"fmt"
 22	"html/template"
 23	"log"
 24	"net/http"
 25	"os"
 26	"regexp"
 27	"strings"
 28	"sync"
 29
 30	"golang.org/x/net/html"
 31	"humungus.tedunangst.com/r/webs/cache"
 32	"humungus.tedunangst.com/r/webs/htfilter"
 33	"humungus.tedunangst.com/r/webs/httpsig"
 34)
 35
 36var allowedclasses = make(map[string]bool)
 37
 38func init() {
 39	allowedclasses["kw"] = true
 40	allowedclasses["bi"] = true
 41	allowedclasses["st"] = true
 42	allowedclasses["nm"] = true
 43	allowedclasses["tp"] = true
 44	allowedclasses["op"] = true
 45	allowedclasses["cm"] = true
 46	allowedclasses["al"] = true
 47	allowedclasses["dl"] = true
 48}
 49
 50func reverbolate(userid int64, honks []*Honk) {
 51	filt := htfilter.New()
 52	filt.Imager = replaceimg
 53	filt.SpanClasses = allowedclasses
 54	for _, h := range honks {
 55		h.What += "ed"
 56		if h.What == "tonked" {
 57			h.What = "honked back"
 58			h.Style = "subtle"
 59		}
 60		if !h.Public {
 61			h.Style += " limited"
 62		}
 63		translate(h)
 64		if h.Whofore == 2 || h.Whofore == 3 {
 65			h.URL = h.XID
 66			if h.What != "bonked" {
 67				h.Noise = re_memes.ReplaceAllString(h.Noise, "")
 68				h.Noise = mentionize(h.Noise)
 69				h.Noise = ontologize(h.Noise)
 70			}
 71			h.Username, h.Handle = handles(h.Honker)
 72		} else {
 73			_, h.Handle = handles(h.Honker)
 74			short := shortname(userid, h.Honker)
 75			if short != "" {
 76				h.Username = short
 77			} else {
 78				h.Username = h.Handle
 79				if len(h.Username) > 20 {
 80					h.Username = h.Username[:20] + ".."
 81				}
 82			}
 83			if h.URL == "" {
 84				h.URL = h.XID
 85			}
 86		}
 87		if h.Oonker != "" {
 88			_, h.Oondle = handles(h.Oonker)
 89		}
 90		h.Precis = demoji(h.Precis)
 91		h.Noise = demoji(h.Noise)
 92		h.Open = "open"
 93
 94		{
 95			p, _ := filt.String(h.Precis)
 96			n, _ := filt.String(h.Noise)
 97			h.Precis = string(p)
 98			h.Noise = string(n)
 99		}
100
101		if userid == -1 {
102			if h.Precis != "" {
103				h.Open = ""
104			}
105		} else {
106			unsee(userid, h)
107			if h.Open == "open" && h.Precis == "unspecified horror" {
108				h.Precis = ""
109			}
110		}
111		if len(h.Noise) > 6000 && h.Open == "open" {
112			if h.Precis == "" {
113				h.Precis = "really freaking long"
114			}
115			h.Open = ""
116		}
117
118		zap := make(map[*Donk]bool)
119		emuxifier := func(e string) string {
120			for _, d := range h.Donks {
121				if d.Name == e {
122					zap[d] = true
123					if d.Local {
124						return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
125					}
126				}
127			}
128			return e
129		}
130		h.Precis = re_emus.ReplaceAllStringFunc(h.Precis, emuxifier)
131		h.Noise = re_emus.ReplaceAllStringFunc(h.Noise, emuxifier)
132
133		j := 0
134		for i := 0; i < len(h.Donks); i++ {
135			if !zap[h.Donks[i]] {
136				h.Donks[j] = h.Donks[i]
137				j++
138			}
139		}
140		h.Donks = h.Donks[:j]
141
142		h.HTPrecis = template.HTML(h.Precis)
143		h.HTML = template.HTML(h.Noise)
144	}
145}
146
147func replaceimg(node *html.Node) string {
148	src := htfilter.GetAttr(node, "src")
149	alt := htfilter.GetAttr(node, "alt")
150	//title := GetAttr(node, "title")
151	if htfilter.HasClass(node, "Emoji") && alt != "" {
152		return alt
153	}
154	alt = html.EscapeString(alt)
155	src = html.EscapeString(src)
156	d := finddonk(src)
157	if d != nil {
158		src = fmt.Sprintf("https://%s/d/%s", serverName, d.XID)
159		return fmt.Sprintf(`<img alt="%s" title="%s" src="%s">`, alt, alt, src)
160	}
161	return fmt.Sprintf(`&lt;img alt="%s" src="<a href="%s">%s<a>"&gt;`, alt, src, src)
162}
163
164func inlineimgs(node *html.Node) string {
165	src := htfilter.GetAttr(node, "src")
166	alt := htfilter.GetAttr(node, "alt")
167	//title := GetAttr(node, "title")
168	if htfilter.HasClass(node, "Emoji") && alt != "" {
169		return alt
170	}
171	alt = html.EscapeString(alt)
172	src = html.EscapeString(src)
173	if !strings.HasPrefix(src, "https://"+serverName+"/") {
174		d := savedonk(src, "image", alt, "image", true)
175		if d != nil {
176			src = fmt.Sprintf("https://%s/d/%s", serverName, d.XID)
177		}
178	}
179	log.Printf("inline img with src: %s", src)
180	return fmt.Sprintf(`<img alt="%s" title="%s" src="%s>`, alt, alt, src)
181}
182
183func translate(honk *Honk) {
184	if honk.Format == "html" {
185		return
186	}
187	noise := honk.Noise
188	if strings.HasPrefix(noise, "DZ:") {
189		idx := strings.Index(noise, "\n")
190		if idx == -1 {
191			honk.Precis = noise
192			noise = ""
193		} else {
194			honk.Precis = noise[:idx]
195			noise = noise[idx+1:]
196		}
197	}
198	honk.Precis = strings.TrimSpace(honk.Precis)
199
200	noise = strings.TrimSpace(noise)
201	noise = quickrename(noise, honk.UserID)
202	noise = markitzero(noise)
203
204	honk.Noise = noise
205	honk.Onts = oneofakind(ontologies(honk.Noise))
206}
207
208func shortxid(xid string) string {
209	idx := strings.LastIndexByte(xid, '/')
210	if idx == -1 {
211		return xid
212	}
213	return xid[idx+1:]
214}
215
216func xfiltrate() string {
217	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
218	var b [18]byte
219	rand.Read(b[:])
220	for i, c := range b {
221		b[i] = letters[c&63]
222	}
223	s := string(b[:])
224	return s
225}
226
227var re_hashes = regexp.MustCompile(`(?:^| )#[[:alnum:]][[:alnum:]_-]*`)
228
229func ontologies(s string) []string {
230	m := re_hashes.FindAllString(s, -1)
231	j := 0
232	for _, h := range m {
233		if h[0] == '&' {
234			continue
235		}
236		if h[0] != '#' {
237			h = h[1:]
238		}
239		m[j] = h
240		j++
241	}
242	return m[:j]
243}
244
245type Mention struct {
246	who   string
247	where string
248}
249
250var re_mentions = regexp.MustCompile(`@[[:alnum:]._-]+@[[:alnum:].-]*[[:alnum:]]`)
251var re_urltions = regexp.MustCompile(`@https://\S+`)
252
253func grapevine(s string) []string {
254	var mentions []string
255	m := re_mentions.FindAllString(s, -1)
256	for i := range m {
257		where := gofish(m[i])
258		if where != "" {
259			mentions = append(mentions, where)
260		}
261	}
262	m = re_urltions.FindAllString(s, -1)
263	for i := range m {
264		mentions = append(mentions, m[i][1:])
265	}
266	return mentions
267}
268
269func bunchofgrapes(s string) []Mention {
270	m := re_mentions.FindAllString(s, -1)
271	var mentions []Mention
272	for i := range m {
273		where := gofish(m[i])
274		if where != "" {
275			mentions = append(mentions, Mention{who: m[i], where: where})
276		}
277	}
278	m = re_urltions.FindAllString(s, -1)
279	for i := range m {
280		mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
281	}
282	return mentions
283}
284
285type Emu struct {
286	ID   string
287	Name string
288}
289
290var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
291
292func herdofemus(noise string) []Emu {
293	m := re_emus.FindAllString(noise, -1)
294	m = oneofakind(m)
295	var emus []Emu
296	for _, e := range m {
297		fname := e[1 : len(e)-1]
298		_, err := os.Stat("emus/" + fname + ".png")
299		if err != nil {
300			continue
301		}
302		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
303		emus = append(emus, Emu{ID: url, Name: e})
304	}
305	return emus
306}
307
308var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
309
310func memetize(honk *Honk) {
311	repl := func(x string) string {
312		name := x[5:]
313		if name[0] == ' ' {
314			name = name[1:]
315		}
316		fd, err := os.Open("memes/" + name)
317		if err != nil {
318			log.Printf("no meme for %s", name)
319			return x
320		}
321		var peek [512]byte
322		n, _ := fd.Read(peek[:])
323		ct := http.DetectContentType(peek[:n])
324		fd.Close()
325
326		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
327		fileid, err := savefile("", name, name, url, ct, false, nil)
328		if err != nil {
329			log.Printf("error saving meme: %s", err)
330			return x
331		}
332		d := &Donk{
333			FileID: fileid,
334			XID:    "",
335			Name:   name,
336			Media:  ct,
337			URL:    url,
338			Local:  false,
339		}
340		honk.Donks = append(honk.Donks, d)
341		return ""
342	}
343	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
344}
345
346var re_quickmention = regexp.MustCompile("(^| )@[[:alnum:]]+( |$)")
347
348func quickrename(s string, userid int64) string {
349	nonstop := true
350	for nonstop {
351		nonstop = false
352		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
353			prefix := ""
354			if m[0] == ' ' {
355				prefix = " "
356				m = m[1:]
357			}
358			prefix += "@"
359			m = m[1:]
360			if m[len(m)-1] == ' ' {
361				m = m[:len(m)-1]
362			}
363
364			xid := fullname(m, userid)
365
366			if xid != "" {
367				_, name := handles(xid)
368				if name != "" {
369					nonstop = true
370					m = name
371				}
372			}
373			return prefix + m + " "
374		})
375	}
376	return s
377}
378
379var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
380	honkers := gethonkers(userid)
381	m := make(map[string]string)
382	for _, h := range honkers {
383		m[h.XID] = h.Name
384	}
385	return m, true
386}, Invalidator: &honkerinvalidator})
387
388func shortname(userid int64, xid string) string {
389	var m map[string]string
390	ok := shortnames.Get(userid, &m)
391	if ok {
392		return m[xid]
393	}
394	return ""
395}
396
397var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
398	honkers := gethonkers(userid)
399	m := make(map[string]string)
400	for _, h := range honkers {
401		m[h.Name] = h.XID
402	}
403	return m, true
404}, Invalidator: &honkerinvalidator})
405
406func fullname(name string, userid int64) string {
407	var m map[string]string
408	ok := fullnames.Get(userid, &m)
409	if ok {
410		return m[name]
411	}
412	return ""
413}
414
415func mentionize(s string) string {
416	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
417		where := gofish(m)
418		if where == "" {
419			return m
420		}
421		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
422		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
423			html.EscapeString(where), html.EscapeString(who))
424	})
425	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
426		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
427			html.EscapeString(m[1:]), html.EscapeString(m))
428	})
429	return s
430}
431
432func ontologize(s string) string {
433	s = re_hashes.ReplaceAllStringFunc(s, func(o string) string {
434		if o[0] == '&' {
435			return o
436		}
437		p := ""
438		h := o
439		if h[0] != '#' {
440			p = h[:1]
441			h = h[1:]
442		}
443		return fmt.Sprintf(`%s<a class="mention u-url" href="https://%s/o/%s">%s</a>`, p, serverName,
444			strings.ToLower(h[1:]), h)
445	})
446	return s
447}
448
449var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
450var re_urlhost = regexp.MustCompile("https://([^/ ]+)")
451
452func originate(u string) string {
453	m := re_urlhost.FindStringSubmatch(u)
454	if len(m) > 1 {
455		return m[1]
456	}
457	return ""
458}
459
460var allhandles = make(map[string]string)
461var handlelock sync.Mutex
462
463// handle, handle@host
464func handles(xid string) (string, string) {
465	if xid == "" {
466		return "", ""
467	}
468	handlelock.Lock()
469	handle := allhandles[xid]
470	handlelock.Unlock()
471	if handle == "" {
472		handle = findhandle(xid)
473		handlelock.Lock()
474		allhandles[xid] = handle
475		handlelock.Unlock()
476	}
477	if handle == xid {
478		return xid, xid
479	}
480	return handle, handle + "@" + originate(xid)
481}
482
483func findhandle(xid string) string {
484	row := stmtGetXonker.QueryRow(xid, "handle")
485	var handle string
486	err := row.Scan(&handle)
487	if err != nil {
488		p, _ := investigate(xid)
489		if p == nil {
490			m := re_unurl.FindStringSubmatch(xid)
491			if len(m) > 2 {
492				handle = m[2]
493			} else {
494				handle = xid
495			}
496		} else {
497			handle = p.Handle
498		}
499		_, err = stmtSaveXonker.Exec(xid, handle, "handle")
500		if err != nil {
501			log.Printf("error saving handle: %s", err)
502		}
503	}
504	return handle
505}
506
507var handleprelock sync.Mutex
508
509func prehandle(xid string) {
510	handleprelock.Lock()
511	defer handleprelock.Unlock()
512	handles(xid)
513}
514
515func prepend(s string, x []string) []string {
516	return append([]string{s}, x...)
517}
518
519// pleroma leaks followers addressed posts to followers
520func butnottooloud(aud []string) {
521	for i, a := range aud {
522		if strings.HasSuffix(a, "/followers") {
523			aud[i] = ""
524		}
525	}
526}
527
528func keepitquiet(aud []string) bool {
529	for _, a := range aud {
530		if a == thewholeworld {
531			return false
532		}
533	}
534	return true
535}
536
537func firstclass(honk *Honk) bool {
538	return honk.Audience[0] == thewholeworld
539}
540
541func oneofakind(a []string) []string {
542	seen := make(map[string]bool)
543	seen[""] = true
544	j := 0
545	for _, s := range a {
546		if !seen[s] {
547			seen[s] = true
548			a[j] = s
549			j++
550		}
551	}
552	return a[:j]
553}
554
555var ziggies = make(map[string]*rsa.PrivateKey)
556var zaggies = make(map[string]*rsa.PublicKey)
557var ziggylock sync.Mutex
558
559func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
560	ziggylock.Lock()
561	key = ziggies[username]
562	ziggylock.Unlock()
563	if key == nil {
564		db := opendatabase()
565		row := db.QueryRow("select seckey from users where username = ?", username)
566		var data string
567		row.Scan(&data)
568		var err error
569		key, _, err = httpsig.DecodeKey(data)
570		if err != nil {
571			log.Printf("error decoding %s seckey: %s", username, err)
572			return
573		}
574		ziggylock.Lock()
575		ziggies[username] = key
576		ziggylock.Unlock()
577	}
578	keyname = fmt.Sprintf("https://%s/%s/%s#key", serverName, userSep, username)
579	return
580}
581
582func zaggy(keyname string) (key *rsa.PublicKey) {
583	ziggylock.Lock()
584	key = zaggies[keyname]
585	ziggylock.Unlock()
586	if key != nil {
587		return
588	}
589	row := stmtGetXonker.QueryRow(keyname, "pubkey")
590	var data string
591	err := row.Scan(&data)
592	if err != nil {
593		log.Printf("hitting the webs for missing pubkey: %s", keyname)
594		j, err := GetJunk(keyname)
595		if err != nil {
596			log.Printf("error getting %s pubkey: %s", keyname, err)
597			return
598		}
599		keyobj, ok := j.GetMap("publicKey")
600		if ok {
601			j = keyobj
602		}
603		data, ok = j.GetString("publicKeyPem")
604		if !ok {
605			log.Printf("error finding %s pubkey", keyname)
606			return
607		}
608		_, ok = j.GetString("owner")
609		if !ok {
610			log.Printf("error finding %s pubkey owner", keyname)
611			return
612		}
613		_, key, err = httpsig.DecodeKey(data)
614		if err != nil {
615			log.Printf("error decoding %s pubkey: %s", keyname, err)
616			return
617		}
618		_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
619		if err != nil {
620			log.Printf("error saving key: %s", err)
621		}
622	} else {
623		_, key, err = httpsig.DecodeKey(data)
624		if err != nil {
625			log.Printf("error decoding %s pubkey: %s", keyname, err)
626			return
627		}
628	}
629	ziggylock.Lock()
630	zaggies[keyname] = key
631	ziggylock.Unlock()
632	return
633}
634
635func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
636	_, err := stmtDeleteXonker.Exec(keyname, "pubkey")
637	if err != nil {
638		log.Printf("error deleting key: %s", err)
639	}
640	ziggylock.Lock()
641	delete(zaggies, keyname)
642	ziggylock.Unlock()
643	return httpsig.VerifyRequest(r, payload, zaggy)
644}
645
646func keymatch(keyname string, actor string) string {
647	hash := strings.IndexByte(keyname, '#')
648	if hash == -1 {
649		hash = len(keyname)
650	}
651	owner := keyname[0:hash]
652	if owner == actor {
653		return originate(actor)
654	}
655	return ""
656}