all repos — honk @ c000eb3c1f6a745c87715e77a1ee5fac9f1ecf73

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		honk.Precis = marker.Mark(strings.TrimSpace(honk.Precis))
334		honk.Noise = noise
335	}
336}
337
338func translate(honk *Honk) {
339	if honk.Format == "html" {
340		return
341	}
342	noise := honk.Noise
343
344	var marker mz.Marker
345	marker.HashLinker = ontoreplacer
346	marker.AtLinker = attoreplacer
347	marker.AllowImages = true
348	noise = strings.TrimSpace(noise)
349	noise = marker.Mark(noise)
350	honk.Noise = noise
351	honk.Onts = oneofakind(append(honk.Onts, marker.HashTags...))
352	honk.Mentions = bunchofgrapes(marker.Mentions)
353}
354
355func redoimages(honk *Honk) {
356	zap := make(map[string]bool)
357	{
358		var htf htfilter.Filter
359		htf.Imager = replaceimgsand(zap, true)
360		htf.SpanClasses = allowedclasses
361		p, _ := htf.String(honk.Precis)
362		n, _ := htf.String(honk.Noise)
363		honk.Precis = string(p)
364		honk.Noise = string(n)
365	}
366	j := 0
367	for i := 0; i < len(honk.Donks); i++ {
368		if !zap[honk.Donks[i].XID] {
369			honk.Donks[j] = honk.Donks[i]
370			j++
371		}
372	}
373	honk.Donks = honk.Donks[:j]
374
375	honk.Noise = re_memes.ReplaceAllString(honk.Noise, "")
376	honk.Noise = strings.Replace(honk.Noise, "<a href=", "<a class=\"mention u-url\" href=", -1)
377}
378
379func xcelerate(b []byte) string {
380	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
381	for i, c := range b {
382		b[i] = letters[c&63]
383	}
384	s := string(b)
385	return s
386}
387
388func shortxid(xid string) string {
389	h := sha512.New512_256()
390	io.WriteString(h, xid)
391	return xcelerate(h.Sum(nil)[:20])
392}
393
394func xfiltrate() string {
395	var b [18]byte
396	rand.Read(b[:])
397	return xcelerate(b[:])
398}
399
400func grapevine(mentions []Mention) []string {
401	var s []string
402	for _, m := range mentions {
403		s = append(s, m.Where)
404	}
405	return s
406}
407
408func bunchofgrapes(m []string) []Mention {
409	var mentions []Mention
410	for i := range m {
411		where := gofish(m[i])
412		if where != "" {
413			mentions = append(mentions, Mention{Who: m[i], Where: where})
414		}
415	}
416	return mentions
417}
418
419type Emu struct {
420	ID   string
421	Name string
422	Type string
423}
424
425var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
426
427var emucache = cache.New(cache.Options{Filler: func(ename string) (Emu, bool) {
428	fname := ename[1 : len(ename)-1]
429	exts := []string{".png", ".gif"}
430	for _, ext := range exts {
431		_, err := os.Stat(dataDir + "/emus/" + fname + ext)
432		if err != nil {
433			continue
434		}
435		url := fmt.Sprintf("https://%s/emu/%s%s", serverName, fname, ext)
436		if develMode {
437			url = fmt.Sprintf("/emu/%s%s", fname, ext)
438		}
439		return Emu{ID: url, Name: ename, Type: "image/" + ext[1:]}, true
440	}
441	return Emu{Name: ename, ID: "", Type: "image/png"}, true
442}, Duration: 10 * time.Second})
443
444func herdofemus(noise string) []Emu {
445	m := re_emus.FindAllString(noise, -1)
446	m = oneofakind(m)
447	var emus []Emu
448	for _, e := range m {
449		var emu Emu
450		emucache.Get(e, &emu)
451		if emu.ID == "" {
452			continue
453		}
454		emus = append(emus, emu)
455	}
456	return emus
457}
458
459var re_memes = regexp.MustCompile("meme: ?([^\n]+)")
460var re_avatar = regexp.MustCompile("avatar: ?([^\n]+)")
461var re_banner = regexp.MustCompile("banner: ?([^\n]+)")
462var re_convoy = regexp.MustCompile("convoy: ?([^\n]+)")
463var re_retag = regexp.MustCompile("tags: ?([^\n]+)")
464var re_convalidate = regexp.MustCompile("^(https?|tag|data):")
465
466func memetize(honk *Honk) {
467	repl := func(x string) string {
468		name := x[5:]
469		if name[0] == ' ' {
470			name = name[1:]
471		}
472		fd, err := os.Open(dataDir + "/memes/" + name)
473		if err != nil {
474			ilog.Printf("no meme for %s", name)
475			return x
476		}
477		var peek [512]byte
478		n, _ := fd.Read(peek[:])
479		ct := http.DetectContentType(peek[:n])
480		fd.Close()
481
482		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
483		fileid, err := savefile(name, name, url, ct, false, nil)
484		if err != nil {
485			elog.Printf("error saving meme: %s", err)
486			return x
487		}
488		d := &Donk{
489			FileID: fileid,
490			Name:   name,
491			Media:  ct,
492			URL:    url,
493			Local:  false,
494		}
495		honk.Donks = append(honk.Donks, d)
496		return ""
497	}
498	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
499}
500
501func recategorize(honk *Honk) {
502	repl := func(x string) string {
503		x = x[5:]
504		for _, t := range strings.Split(x, " ") {
505			if t == "" {
506				continue
507			}
508			if t[0] != '#' {
509				t = "#" + t
510			}
511			dlog.Printf("hashtag: %s", t)
512			honk.Onts = append(honk.Onts, t)
513		}
514		return ""
515	}
516	honk.Noise = re_retag.ReplaceAllStringFunc(honk.Noise, repl)
517}
518
519var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]_]+([ \n:;.,']|$)")
520
521func quickrename(s string, userid int64) string {
522	nonstop := true
523	for nonstop {
524		nonstop = false
525		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
526			prefix := ""
527			if m[0] == ' ' || m[0] == '\n' {
528				prefix = m[:1]
529				m = m[1:]
530			}
531			prefix += "@"
532			m = m[1:]
533			tail := ""
534			if last := m[len(m)-1]; last == ' ' || last == '\n' ||
535				last == ':' || last == ';' ||
536				last == '.' || last == ',' || last == '\'' {
537				tail = m[len(m)-1:]
538				m = m[:len(m)-1]
539			}
540
541			xid := fullname(m, userid)
542
543			if xid != "" {
544				_, name := handles(xid)
545				if name != "" {
546					nonstop = true
547					m = name
548				}
549			}
550			return prefix + m + tail
551		})
552	}
553	return s
554}
555
556var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
557	honkers := gethonkers(userid)
558	m := make(map[string]string)
559	for _, h := range honkers {
560		m[h.XID] = h.Name
561	}
562	return m, true
563}, Invalidator: &honkerinvalidator})
564
565func shortname(userid int64, xid string) string {
566	var m map[string]string
567	ok := shortnames.Get(userid, &m)
568	if ok {
569		return m[xid]
570	}
571	return ""
572}
573
574var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
575	honkers := gethonkers(userid)
576	m := make(map[string]string)
577	for _, h := range honkers {
578		m[h.Name] = h.XID
579	}
580	return m, true
581}, Invalidator: &honkerinvalidator})
582
583func fullname(name string, userid int64) string {
584	var m map[string]string
585	ok := fullnames.Get(userid, &m)
586	if ok {
587		return m[name]
588	}
589	return ""
590}
591
592func attoreplacer(m string) string {
593	fill := `<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`
594	where := gofish(m)
595	if where == "" {
596		return m
597	}
598	who := m[0 : 1+strings.IndexByte(m[1:], '@')]
599	return fmt.Sprintf(fill, html.EscapeString(where), html.EscapeString(who))
600}
601
602func ontoreplacer(h string) string {
603	return fmt.Sprintf(`<a class="mention hashtag" href="https://%s/o/%s">%s</a>`, serverName,
604		strings.ToLower(h[1:]), h)
605}
606
607var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
608var re_urlhost = regexp.MustCompile("https://([^/ #)]+)")
609
610func originate(u string) string {
611	m := re_urlhost.FindStringSubmatch(u)
612	if len(m) > 1 {
613		return m[1]
614	}
615	return ""
616}
617
618var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
619	handle := getxonker(xid, "handle")
620	if handle == "" {
621		dlog.Printf("need to get a handle: %s", xid)
622		info, err := investigate(xid)
623		if err != nil {
624			m := re_unurl.FindStringSubmatch(xid)
625			if len(m) > 2 {
626				handle = m[2]
627			} else {
628				handle = xid
629			}
630		} else {
631			handle = info.Name
632		}
633	}
634	return handle, true
635}})
636
637// handle, handle@host
638func handles(xid string) (string, string) {
639	if xid == "" || xid == thewholeworld || strings.HasSuffix(xid, "/followers") {
640		return "", ""
641	}
642	var handle string
643	allhandles.Get(xid, &handle)
644	if handle == xid {
645		return xid, xid
646	}
647	return handle, handle + "@" + originate(xid)
648}
649
650func butnottooloud(aud []string) {
651	for i, a := range aud {
652		if strings.HasSuffix(a, "/followers") {
653			aud[i] = ""
654		}
655	}
656}
657
658func loudandproud(aud []string) bool {
659	for _, a := range aud {
660		if a == thewholeworld {
661			return true
662		}
663	}
664	return false
665}
666
667func firstclass(honk *Honk) bool {
668	return honk.Audience[0] == thewholeworld
669}
670
671func oneofakind(a []string) []string {
672	seen := make(map[string]bool)
673	seen[""] = true
674	j := 0
675	for _, s := range a {
676		if !seen[s] {
677			seen[s] = true
678			a[j] = s
679			j++
680		}
681	}
682	return a[:j]
683}
684
685var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
686	var user *WhatAbout
687	ok := somenumberedusers.Get(userid, &user)
688	if !ok {
689		return nil, false
690	}
691	ki := new(KeyInfo)
692	ki.keyname = user.URL + "#key"
693	ki.seckey = user.SecKey
694	return ki, true
695}})
696
697func ziggy(userid int64) *KeyInfo {
698	var ki *KeyInfo
699	ziggies.Get(userid, &ki)
700	return ki
701}
702
703var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
704	data := getxonker(keyname, "pubkey")
705	if data == "" {
706		dlog.Printf("hitting the webs for missing pubkey: %s", keyname)
707		j, err := GetJunk(readyLuserOne, keyname)
708		if err != nil {
709			ilog.Printf("error getting %s pubkey: %s", keyname, err)
710			when := time.Now().UTC().Format(dbtimeformat)
711			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
712			return httpsig.PublicKey{}, true
713		}
714		allinjest(originate(keyname), j)
715		data = getxonker(keyname, "pubkey")
716		if data == "" {
717			ilog.Printf("key not found after ingesting")
718			when := time.Now().UTC().Format(dbtimeformat)
719			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
720			return httpsig.PublicKey{}, true
721		}
722	}
723	if data == "failed" {
724		ilog.Printf("lookup previously failed key %s", keyname)
725		return httpsig.PublicKey{}, true
726	}
727	_, key, err := httpsig.DecodeKey(data)
728	if err != nil {
729		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
730		return key, true
731	}
732	return key, true
733}, Limit: 512})
734
735func zaggy(keyname string) (httpsig.PublicKey, error) {
736	var key httpsig.PublicKey
737	zaggies.Get(keyname, &key)
738	return key, nil
739}
740
741func savingthrow(keyname string) {
742	when := time.Now().Add(-30 * time.Minute).UTC().Format(dbtimeformat)
743	stmtDeleteXonker.Exec(keyname, "pubkey", when)
744	zaggies.Clear(keyname)
745}
746
747func keymatch(keyname string, actor string) string {
748	origin := originate(actor)
749	if origin == originate(keyname) {
750		return origin
751	}
752	return ""
753}