all repos — honk @ 488aadcb41487b340f652de651a0d0eae4c3c613

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