all repos — honk @ 79d3e5e0dba858ca533d38976328017a00dcfc57

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