all repos — honk @ 018b6c68c9e2b8659008b80fed7c9b984c0f9a38

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/sha512"
 21	"fmt"
 22	"html/template"
 23	"io"
 24	"net/http"
 25	"net/url"
 26	"os"
 27	"regexp"
 28	"strings"
 29	"time"
 30
 31	"golang.org/x/net/html"
 32	"humungus.tedunangst.com/r/webs/cache"
 33	"humungus.tedunangst.com/r/webs/htfilter"
 34	"humungus.tedunangst.com/r/webs/httpsig"
 35	"humungus.tedunangst.com/r/webs/mz"
 36	"humungus.tedunangst.com/r/webs/templates"
 37)
 38
 39var allowedclasses = make(map[string]bool)
 40
 41func init() {
 42	allowedclasses["kw"] = true
 43	allowedclasses["bi"] = true
 44	allowedclasses["st"] = true
 45	allowedclasses["nm"] = true
 46	allowedclasses["tp"] = true
 47	allowedclasses["op"] = true
 48	allowedclasses["cm"] = true
 49	allowedclasses["al"] = true
 50	allowedclasses["dl"] = true
 51}
 52
 53var relingo = make(map[string]string)
 54
 55func loadLingo() {
 56	for _, l := range []string{"honked", "bonked", "honked back", "qonked", "evented"} {
 57		v := l
 58		k := "lingo-" + strings.ReplaceAll(l, " ", "")
 59		getconfig(k, &v)
 60		relingo[l] = v
 61	}
 62}
 63
 64func reverbolate(userid int64, honks []*Honk) {
 65	var user *WhatAbout
 66	somenumberedusers.Get(userid, &user)
 67	for _, h := range honks {
 68		h.What += "ed"
 69		if h.What == "honked" && h.RID != "" {
 70			h.What = "honked back"
 71			h.Style += " subtle"
 72		}
 73		if !h.Public {
 74			h.Style += " limited"
 75		}
 76		if h.Whofore == 1 {
 77			h.Style += " atme"
 78		}
 79		translate(h)
 80		local := false
 81		if h.Whofore == 2 || h.Whofore == 3 {
 82			local = true
 83		}
 84		if local && h.What != "bonked" {
 85			h.Noise = re_retag.ReplaceAllString(h.Noise, "")
 86			h.Noise = re_memes.ReplaceAllString(h.Noise, "")
 87		}
 88		h.Username, h.Handle = handles(h.Honker)
 89		if !local {
 90			short := shortname(userid, h.Honker)
 91			if short != "" {
 92				h.Username = short
 93			} else {
 94				h.Username = h.Handle
 95				if len(h.Username) > 20 {
 96					h.Username = h.Username[:20] + ".."
 97				}
 98			}
 99		}
100		if user != nil {
101			hset := []string{}
102			if h.Honker != user.URL {
103				hset = append(hset, "@"+h.Handle)
104			}
105			if user.Options.MentionAll {
106				for _, a := range h.Audience {
107					if a == h.Honker || a == user.URL {
108						continue
109					}
110					_, hand := handles(a)
111					if hand != "" {
112						hand = "@" + hand
113						hset = append(hset, hand)
114					}
115				}
116			}
117			h.Handles = strings.Join(hset, " ")
118		}
119		if h.URL == "" {
120			h.URL = h.XID
121		}
122		if h.Oonker != "" {
123			_, h.Oondle = handles(h.Oonker)
124		}
125		h.Precis = demoji(h.Precis)
126		h.Noise = demoji(h.Noise)
127		h.Open = "open"
128		var misto string
129		for _, m := range h.Mentions {
130			if m.Where != h.Honker && !m.IsPresent(h.Noise) {
131				misto += " " + m.Who
132			}
133		}
134		var mistag string
135		for _, o := range h.Onts {
136			if !OntIsPresent(o, h.Noise) {
137				mistag += " " + o
138			}
139		}
140		if len(misto) > 0 || len(mistag) > 0 {
141			if len(misto) > 0 {
142				misto = "(" + misto[1:] + ")<p>"
143			}
144			if len(mistag) > 0 {
145				mistag = "<p>(" + mistag[1:] + ")"
146			}
147			h.Noise = misto + h.Noise + mistag
148		}
149
150		zap := make(map[string]bool)
151		{
152			var htf htfilter.Filter
153			htf.Imager = replaceimgsand(zap, false)
154			htf.SpanClasses = allowedclasses
155			htf.BaseURL, _ = url.Parse(h.XID)
156			emuxifier := func(e string) string {
157				for _, d := range h.Donks {
158					if d.Name == e {
159						zap[d.XID] = true
160						if d.Local {
161							return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
162						}
163					}
164				}
165				if local && h.What != "bonked" {
166					var emu Emu
167					emucache.Get(e, &emu)
168					if emu.ID != "" {
169						return fmt.Sprintf(`<img class="emu" title="%s" src="%s">`, emu.Name, emu.ID)
170					}
171				}
172				return e
173			}
174			htf.FilterText = func(w io.Writer, data string) {
175				data = htfilter.EscapeText(data)
176				data = re_emus.ReplaceAllStringFunc(data, emuxifier)
177				io.WriteString(w, data)
178			}
179			if user != nil {
180				htf.RetargetLink = func(href string) string {
181					h2 := strings.ReplaceAll(href, "/@", "/users/")
182					for _, m := range h.Mentions {
183						if h2 == m.Where || href == m.Where {
184							return "/h?xid=" + url.QueryEscape(m.Where)
185						}
186					}
187					return href
188				}
189			}
190			p, _ := htf.String(h.Precis)
191			n, _ := htf.String(h.Noise)
192			h.Precis = string(p)
193			h.Noise = string(n)
194		}
195		j := 0
196		for i := 0; i < len(h.Donks); i++ {
197			if !zap[h.Donks[i].XID] {
198				h.Donks[j] = h.Donks[i]
199				j++
200			}
201		}
202		h.Donks = h.Donks[:j]
203	}
204
205	unsee(honks, userid)
206
207	for _, h := range honks {
208		renderflags(h)
209
210		h.HTPrecis = template.HTML(h.Precis)
211		h.HTML = template.HTML(h.Noise)
212		if redo := relingo[h.What]; redo != "" {
213			h.What = redo
214		}
215	}
216}
217
218func replaceimgsand(zap map[string]bool, absolute bool) func(node *html.Node) string {
219	return func(node *html.Node) string {
220		src := htfilter.GetAttr(node, "src")
221		alt := htfilter.GetAttr(node, "alt")
222		//title := GetAttr(node, "title")
223		if htfilter.HasClass(node, "Emoji") && alt != "" {
224			return alt
225		}
226		d := finddonk(src)
227		if d != nil {
228			zap[d.XID] = true
229			base := ""
230			if absolute {
231				base = "https://" + serverName
232			}
233			return string(templates.Sprintf(`<img alt="%s" title="%s" src="%s/d/%s">`, alt, alt, base, d.XID))
234		}
235		return string(templates.Sprintf(`&lt;img alt="%s" src="<a href="%s">%s</a>"&gt;`, alt, src, src))
236	}
237}
238
239func translatechonk(ch *Chonk) {
240	noise := ch.Noise
241	if ch.Format == "markdown" {
242		var marker mz.Marker
243		noise = marker.Mark(noise)
244	}
245	var htf htfilter.Filter
246	htf.SpanClasses = allowedclasses
247	htf.BaseURL, _ = url.Parse(ch.XID)
248	ch.HTML, _ = htf.String(noise)
249}
250
251func filterchonk(ch *Chonk) {
252	translatechonk(ch)
253
254	noise := string(ch.HTML)
255
256	local := originate(ch.XID) == serverName
257
258	zap := make(map[string]bool)
259	emuxifier := func(e string) string {
260		for _, d := range ch.Donks {
261			if d.Name == e {
262				zap[d.XID] = true
263				if d.Local {
264					return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
265				}
266			}
267		}
268		if local {
269			var emu Emu
270			emucache.Get(e, &emu)
271			if emu.ID != "" {
272				return fmt.Sprintf(`<img class="emu" title="%s" src="%s">`, emu.Name, emu.ID)
273			}
274		}
275		return e
276	}
277	noise = re_emus.ReplaceAllStringFunc(noise, emuxifier)
278	j := 0
279	for i := 0; i < len(ch.Donks); i++ {
280		if !zap[ch.Donks[i].XID] {
281			ch.Donks[j] = ch.Donks[i]
282			j++
283		}
284	}
285	ch.Donks = ch.Donks[:j]
286
287	if strings.HasPrefix(noise, "<p>") {
288		noise = noise[3:]
289	}
290	ch.HTML = template.HTML(noise)
291	if short := shortname(ch.UserID, ch.Who); short != "" {
292		ch.Handle = short
293	} else {
294		ch.Handle, _ = handles(ch.Who)
295	}
296
297}
298
299func inlineimgsfor(honk *Honk) func(node *html.Node) string {
300	return func(node *html.Node) string {
301		src := htfilter.GetAttr(node, "src")
302		alt := htfilter.GetAttr(node, "alt")
303		d := savedonk(src, "image", alt, "image", true)
304		if d != nil {
305			honk.Donks = append(honk.Donks, d)
306		}
307		dlog.Printf("inline img with src: %s", src)
308		return ""
309	}
310}
311
312func imaginate(honk *Honk) {
313	var htf htfilter.Filter
314	htf.Imager = inlineimgsfor(honk)
315	htf.BaseURL, _ = url.Parse(honk.XID)
316	htf.String(honk.Noise)
317}
318
319var re_dangerous = regexp.MustCompile("^[a-zA-Z]{2}:")
320
321func precipitate(honk *Honk) {
322	noise := honk.Noise
323	if re_dangerous.MatchString(noise) {
324		idx := strings.Index(noise, "\n")
325		if idx == -1 {
326			honk.Precis = noise
327			noise = ""
328		} else {
329			honk.Precis = noise[:idx]
330			noise = noise[idx+1:]
331		}
332		var marker mz.Marker
333		marker.Short = true
334		honk.Precis = marker.Mark(strings.TrimSpace(honk.Precis))
335		honk.Noise = noise
336	}
337}
338
339func translate(honk *Honk) {
340	if honk.Format == "html" {
341		return
342	}
343	noise := honk.Noise
344
345	var marker mz.Marker
346	marker.HashLinker = ontoreplacer
347	marker.AtLinker = attoreplacer
348	marker.AllowImages = true
349	noise = strings.TrimSpace(noise)
350	noise = marker.Mark(noise)
351	honk.Noise = noise
352	honk.Onts = oneofakind(append(honk.Onts, marker.HashTags...))
353	honk.Mentions = bunchofgrapes(marker.Mentions)
354}
355
356func redoimages(honk *Honk) {
357	zap := make(map[string]bool)
358	{
359		var htf htfilter.Filter
360		htf.Imager = replaceimgsand(zap, true)
361		htf.SpanClasses = allowedclasses
362		p, _ := htf.String(honk.Precis)
363		n, _ := htf.String(honk.Noise)
364		honk.Precis = string(p)
365		honk.Noise = string(n)
366	}
367	j := 0
368	for i := 0; i < len(honk.Donks); i++ {
369		if !zap[honk.Donks[i].XID] {
370			honk.Donks[j] = honk.Donks[i]
371			j++
372		}
373	}
374	honk.Donks = honk.Donks[:j]
375
376	honk.Noise = re_memes.ReplaceAllString(honk.Noise, "")
377	honk.Noise = strings.Replace(honk.Noise, "<a href=", "<a class=\"mention u-url\" href=", -1)
378}
379
380func xcelerate(b []byte) string {
381	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
382	for i, c := range b {
383		b[i] = letters[c&63]
384	}
385	s := string(b)
386	return s
387}
388
389func shortxid(xid string) string {
390	h := sha512.New512_256()
391	io.WriteString(h, xid)
392	return xcelerate(h.Sum(nil)[:20])
393}
394
395func xfiltrate() string {
396	var b [18]byte
397	rand.Read(b[:])
398	return xcelerate(b[:])
399}
400
401func grapevine(mentions []Mention) []string {
402	var s []string
403	for _, m := range mentions {
404		s = append(s, m.Where)
405	}
406	return s
407}
408
409func bunchofgrapes(m []string) []Mention {
410	var mentions []Mention
411	for i := range m {
412		where := gofish(m[i])
413		if where != "" {
414			mentions = append(mentions, Mention{Who: m[i], Where: where})
415		}
416	}
417	return mentions
418}
419
420type Emu struct {
421	ID   string
422	Name string
423	Type string
424}
425
426var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
427
428var emucache = cache.New(cache.Options{Filler: func(ename string) (Emu, bool) {
429	fname := ename[1 : len(ename)-1]
430	exts := []string{".png", ".gif"}
431	for _, ext := range exts {
432		_, err := os.Stat(dataDir + "/emus/" + fname + ext)
433		if err != nil {
434			continue
435		}
436		url := fmt.Sprintf("https://%s/emu/%s%s", serverName, fname, ext)
437		if develMode {
438			url = fmt.Sprintf("/emu/%s%s", fname, ext)
439		}
440		return Emu{ID: url, Name: ename, Type: "image/" + ext[1:]}, true
441	}
442	return Emu{Name: ename, ID: "", Type: "image/png"}, true
443}, Duration: 10 * time.Second})
444
445func herdofemus(noise string) []Emu {
446	m := re_emus.FindAllString(noise, -1)
447	m = oneofakind(m)
448	var emus []Emu
449	for _, e := range m {
450		var emu Emu
451		emucache.Get(e, &emu)
452		if emu.ID == "" {
453			continue
454		}
455		emus = append(emus, emu)
456	}
457	return emus
458}
459
460var re_memes = regexp.MustCompile("meme: ?([^\n]+)")
461var re_avatar = regexp.MustCompile("avatar: ?([^\n]+)")
462var re_banner = regexp.MustCompile("banner: ?([^\n]+)")
463var re_convoy = regexp.MustCompile("convoy: ?([^\n]+)")
464var re_retag = regexp.MustCompile("tags: ?([^\n]+)")
465var re_convalidate = regexp.MustCompile("^(https?|tag|data):")
466
467func memetize(honk *Honk) {
468	repl := func(x string) string {
469		name := x[5:]
470		if name[0] == ' ' {
471			name = name[1:]
472		}
473		fd, err := os.Open(dataDir + "/memes/" + name)
474		if err != nil {
475			ilog.Printf("no meme for %s", name)
476			return x
477		}
478		var peek [512]byte
479		n, _ := fd.Read(peek[:])
480		ct := http.DetectContentType(peek[:n])
481		fd.Close()
482
483		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
484		fileid, err := savefile(name, name, url, ct, false, nil)
485		if err != nil {
486			elog.Printf("error saving meme: %s", err)
487			return x
488		}
489		d := &Donk{
490			FileID: fileid,
491			Name:   name,
492			Media:  ct,
493			URL:    url,
494			Local:  false,
495		}
496		honk.Donks = append(honk.Donks, d)
497		return ""
498	}
499	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
500}
501
502func recategorize(honk *Honk) {
503	repl := func(x string) string {
504		x = x[5:]
505		for _, t := range strings.Split(x, " ") {
506			if t == "" {
507				continue
508			}
509			if t[0] != '#' {
510				t = "#" + t
511			}
512			dlog.Printf("hashtag: %s", t)
513			honk.Onts = append(honk.Onts, t)
514		}
515		return ""
516	}
517	honk.Noise = re_retag.ReplaceAllStringFunc(honk.Noise, repl)
518}
519
520var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]_]+([ \n:;.,']|$)")
521
522func quickrename(s string, userid int64) string {
523	nonstop := true
524	for nonstop {
525		nonstop = false
526		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
527			prefix := ""
528			if m[0] == ' ' || m[0] == '\n' {
529				prefix = m[:1]
530				m = m[1:]
531			}
532			prefix += "@"
533			m = m[1:]
534			tail := ""
535			if last := m[len(m)-1]; last == ' ' || last == '\n' ||
536				last == ':' || last == ';' ||
537				last == '.' || last == ',' || last == '\'' {
538				tail = m[len(m)-1:]
539				m = m[:len(m)-1]
540			}
541
542			xid := fullname(m, userid)
543
544			if xid != "" {
545				_, name := handles(xid)
546				if name != "" {
547					nonstop = true
548					m = name
549				}
550			}
551			return prefix + m + tail
552		})
553	}
554	return s
555}
556
557var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
558	honkers := gethonkers(userid)
559	m := make(map[string]string)
560	for _, h := range honkers {
561		m[h.XID] = h.Name
562	}
563	return m, true
564}, Invalidator: &honkerinvalidator})
565
566func shortname(userid int64, xid string) string {
567	var m map[string]string
568	ok := shortnames.Get(userid, &m)
569	if ok {
570		return m[xid]
571	}
572	return ""
573}
574
575var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
576	honkers := gethonkers(userid)
577	m := make(map[string]string)
578	for _, h := range honkers {
579		m[h.Name] = h.XID
580	}
581	return m, true
582}, Invalidator: &honkerinvalidator})
583
584func fullname(name string, userid int64) string {
585	var m map[string]string
586	ok := fullnames.Get(userid, &m)
587	if ok {
588		return m[name]
589	}
590	return ""
591}
592
593func attoreplacer(m string) string {
594	fill := `<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`
595	where := gofish(m)
596	if where == "" {
597		return m
598	}
599	who := m[0 : 1+strings.IndexByte(m[1:], '@')]
600	return fmt.Sprintf(fill, html.EscapeString(where), html.EscapeString(who))
601}
602
603func ontoreplacer(h string) string {
604	return fmt.Sprintf(`<a class="mention hashtag" href="https://%s/o/%s">%s</a>`, serverName,
605		strings.ToLower(h[1:]), h)
606}
607
608var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
609var re_urlhost = regexp.MustCompile("https://([^/ #)]+)")
610
611func originate(u string) string {
612	m := re_urlhost.FindStringSubmatch(u)
613	if len(m) > 1 {
614		return m[1]
615	}
616	return ""
617}
618
619var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
620	handle := getxonker(xid, "handle")
621	if handle == "" {
622		dlog.Printf("need to get a handle: %s", xid)
623		info, err := investigate(xid)
624		if err != nil {
625			m := re_unurl.FindStringSubmatch(xid)
626			if len(m) > 2 {
627				handle = m[2]
628			} else {
629				handle = xid
630			}
631		} else {
632			handle = info.Name
633		}
634	}
635	return handle, true
636}})
637
638// handle, handle@host
639func handles(xid string) (string, string) {
640	if xid == "" || xid == thewholeworld || strings.HasSuffix(xid, "/followers") {
641		return "", ""
642	}
643	var handle string
644	allhandles.Get(xid, &handle)
645	if handle == xid {
646		return xid, xid
647	}
648	return handle, handle + "@" + originate(xid)
649}
650
651func butnottooloud(aud []string) {
652	for i, a := range aud {
653		if strings.HasSuffix(a, "/followers") {
654			aud[i] = ""
655		}
656	}
657}
658
659func loudandproud(aud []string) bool {
660	for _, a := range aud {
661		if a == thewholeworld {
662			return true
663		}
664	}
665	return false
666}
667
668func firstclass(honk *Honk) bool {
669	return honk.Audience[0] == thewholeworld
670}
671
672func oneofakind(a []string) []string {
673	seen := make(map[string]bool)
674	seen[""] = true
675	j := 0
676	for _, s := range a {
677		if !seen[s] {
678			seen[s] = true
679			a[j] = s
680			j++
681		}
682	}
683	return a[:j]
684}
685
686var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
687	var user *WhatAbout
688	ok := somenumberedusers.Get(userid, &user)
689	if !ok {
690		return nil, false
691	}
692	ki := new(KeyInfo)
693	ki.keyname = user.URL + "#key"
694	ki.seckey = user.SecKey
695	return ki, true
696}})
697
698func ziggy(userid int64) *KeyInfo {
699	var ki *KeyInfo
700	ziggies.Get(userid, &ki)
701	return ki
702}
703
704var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
705	data := getxonker(keyname, "pubkey")
706	if data == "" {
707		dlog.Printf("hitting the webs for missing pubkey: %s", keyname)
708		j, err := GetJunk(readyLuserOne, keyname)
709		if err != nil {
710			ilog.Printf("error getting %s pubkey: %s", keyname, err)
711			when := time.Now().UTC().Format(dbtimeformat)
712			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
713			return httpsig.PublicKey{}, true
714		}
715		allinjest(originate(keyname), j)
716		data = getxonker(keyname, "pubkey")
717		if data == "" {
718			ilog.Printf("key not found after ingesting")
719			when := time.Now().UTC().Format(dbtimeformat)
720			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
721			return httpsig.PublicKey{}, true
722		}
723	}
724	if data == "failed" {
725		ilog.Printf("lookup previously failed key %s", keyname)
726		return httpsig.PublicKey{}, true
727	}
728	_, key, err := httpsig.DecodeKey(data)
729	if err != nil {
730		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
731		return key, true
732	}
733	return key, true
734}, Limit: 512})
735
736func zaggy(keyname string) (httpsig.PublicKey, error) {
737	var key httpsig.PublicKey
738	zaggies.Get(keyname, &key)
739	return key, nil
740}
741
742func savingthrow(keyname string) {
743	when := time.Now().Add(-30 * time.Minute).UTC().Format(dbtimeformat)
744	stmtDeleteXonker.Exec(keyname, "pubkey", when)
745	zaggies.Clear(keyname)
746}
747
748func keymatch(keyname string, actor string) string {
749	origin := originate(actor)
750	if origin == originate(keyname) {
751		return origin
752	}
753	return ""
754}