all repos — honk @ 70f4ec402d58561098e475b788c7f3c7e648cc30

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					for _, m := range h.Mentions {
182						if href == m.Where {
183							return "/h?xid=" + url.QueryEscape(href)
184						}
185					}
186					return href
187				}
188			}
189			p, _ := htf.String(h.Precis)
190			n, _ := htf.String(h.Noise)
191			h.Precis = string(p)
192			h.Noise = string(n)
193		}
194		j := 0
195		for i := 0; i < len(h.Donks); i++ {
196			if !zap[h.Donks[i].XID] {
197				h.Donks[j] = h.Donks[i]
198				j++
199			}
200		}
201		h.Donks = h.Donks[:j]
202	}
203
204	unsee(honks, userid)
205
206	for _, h := range honks {
207		renderflags(h)
208
209		h.HTPrecis = template.HTML(h.Precis)
210		h.HTML = template.HTML(h.Noise)
211		if redo := relingo[h.What]; redo != "" {
212			h.What = redo
213		}
214	}
215}
216
217func replaceimgsand(zap map[string]bool, absolute bool) func(node *html.Node) string {
218	return func(node *html.Node) string {
219		src := htfilter.GetAttr(node, "src")
220		alt := htfilter.GetAttr(node, "alt")
221		//title := GetAttr(node, "title")
222		if htfilter.HasClass(node, "Emoji") && alt != "" {
223			return alt
224		}
225		d := finddonk(src)
226		if d != nil {
227			zap[d.XID] = true
228			base := ""
229			if absolute {
230				base = "https://" + serverName
231			}
232			return string(templates.Sprintf(`<img alt="%s" title="%s" src="%s/d/%s">`, alt, alt, base, d.XID))
233		}
234		return string(templates.Sprintf(`&lt;img alt="%s" src="<a href="%s">%s</a>"&gt;`, alt, src, src))
235	}
236}
237
238func translatechonk(ch *Chonk) {
239	noise := ch.Noise
240	if ch.Format == "markdown" {
241		var marker mz.Marker
242		noise = marker.Mark(noise)
243	}
244	var htf htfilter.Filter
245	htf.SpanClasses = allowedclasses
246	htf.BaseURL, _ = url.Parse(ch.XID)
247	ch.HTML, _ = htf.String(noise)
248}
249
250func filterchonk(ch *Chonk) {
251	translatechonk(ch)
252
253	noise := string(ch.HTML)
254
255	local := originate(ch.XID) == serverName
256
257	zap := make(map[string]bool)
258	emuxifier := func(e string) string {
259		for _, d := range ch.Donks {
260			if d.Name == e {
261				zap[d.XID] = true
262				if d.Local {
263					return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
264				}
265			}
266		}
267		if local {
268			var emu Emu
269			emucache.Get(e, &emu)
270			if emu.ID != "" {
271				return fmt.Sprintf(`<img class="emu" title="%s" src="%s">`, emu.Name, emu.ID)
272			}
273		}
274		return e
275	}
276	noise = re_emus.ReplaceAllStringFunc(noise, emuxifier)
277	j := 0
278	for i := 0; i < len(ch.Donks); i++ {
279		if !zap[ch.Donks[i].XID] {
280			ch.Donks[j] = ch.Donks[i]
281			j++
282		}
283	}
284	ch.Donks = ch.Donks[:j]
285
286	if strings.HasPrefix(noise, "<p>") {
287		noise = noise[3:]
288	}
289	ch.HTML = template.HTML(noise)
290	if short := shortname(ch.UserID, ch.Who); short != "" {
291		ch.Handle = short
292	} else {
293		ch.Handle, _ = handles(ch.Who)
294	}
295
296}
297
298func inlineimgsfor(honk *Honk) func(node *html.Node) string {
299	return func(node *html.Node) string {
300		src := htfilter.GetAttr(node, "src")
301		alt := htfilter.GetAttr(node, "alt")
302		d := savedonk(src, "image", alt, "image", true)
303		if d != nil {
304			honk.Donks = append(honk.Donks, d)
305		}
306		dlog.Printf("inline img with src: %s", src)
307		return ""
308	}
309}
310
311func imaginate(honk *Honk) {
312	var htf htfilter.Filter
313	htf.Imager = inlineimgsfor(honk)
314	htf.BaseURL, _ = url.Parse(honk.XID)
315	htf.String(honk.Noise)
316}
317
318var re_dangerous = regexp.MustCompile("^[a-zA-Z]{2}:")
319
320func precipitate(honk *Honk) {
321	noise := honk.Noise
322	if re_dangerous.MatchString(noise) {
323		idx := strings.Index(noise, "\n")
324		if idx == -1 {
325			honk.Precis = noise
326			noise = ""
327		} else {
328			honk.Precis = noise[:idx]
329			noise = noise[idx+1:]
330		}
331		var marker mz.Marker
332		honk.Precis = marker.Mark(strings.TrimSpace(honk.Precis))
333		honk.Noise = noise
334	}
335}
336
337func translate(honk *Honk) {
338	if honk.Format == "html" {
339		return
340	}
341	noise := honk.Noise
342
343	var marker mz.Marker
344	marker.HashLinker = ontoreplacer
345	marker.AtLinker = attoreplacer
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 = cache.New(cache.Options{Filler: 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		return Emu{ID: url, Name: ename, Type: "image/" + ext[1:]}, true
435	}
436	return Emu{Name: ename, ID: "", Type: "image/png"}, true
437}, Duration: 10 * time.Second})
438
439func herdofemus(noise string) []Emu {
440	m := re_emus.FindAllString(noise, -1)
441	m = oneofakind(m)
442	var emus []Emu
443	for _, e := range m {
444		var emu Emu
445		emucache.Get(e, &emu)
446		if emu.ID == "" {
447			continue
448		}
449		emus = append(emus, emu)
450	}
451	return emus
452}
453
454var re_memes = regexp.MustCompile("meme: ?([^\n]+)")
455var re_avatar = regexp.MustCompile("avatar: ?([^\n]+)")
456var re_banner = regexp.MustCompile("banner: ?([^\n]+)")
457var re_convoy = regexp.MustCompile("convoy: ?([^\n]+)")
458var re_retag = regexp.MustCompile("tags: ?([^\n]+)")
459var re_convalidate = regexp.MustCompile("^(https?|tag|data):")
460
461func memetize(honk *Honk) {
462	repl := func(x string) string {
463		name := x[5:]
464		if name[0] == ' ' {
465			name = name[1:]
466		}
467		fd, err := os.Open(dataDir + "/memes/" + name)
468		if err != nil {
469			ilog.Printf("no meme for %s", name)
470			return x
471		}
472		var peek [512]byte
473		n, _ := fd.Read(peek[:])
474		ct := http.DetectContentType(peek[:n])
475		fd.Close()
476
477		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
478		fileid, err := savefile(name, name, url, ct, false, nil)
479		if err != nil {
480			elog.Printf("error saving meme: %s", err)
481			return x
482		}
483		d := &Donk{
484			FileID: fileid,
485			Name:   name,
486			Media:  ct,
487			URL:    url,
488			Local:  false,
489		}
490		honk.Donks = append(honk.Donks, d)
491		return ""
492	}
493	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
494}
495
496func recategorize(honk *Honk) {
497	repl := func(x string) string {
498		x = x[5:]
499		for _, t := range strings.Split(x, " ") {
500			if t == "" {
501				continue
502			}
503			if t[0] != '#' {
504				t = "#" + t
505			}
506			dlog.Printf("hashtag: %s", t)
507			honk.Onts = append(honk.Onts, t)
508		}
509		return ""
510	}
511	honk.Noise = re_retag.ReplaceAllStringFunc(honk.Noise, repl)
512}
513
514var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]_]+([ \n:;.,']|$)")
515
516func quickrename(s string, userid int64) string {
517	nonstop := true
518	for nonstop {
519		nonstop = false
520		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
521			prefix := ""
522			if m[0] == ' ' || m[0] == '\n' {
523				prefix = m[:1]
524				m = m[1:]
525			}
526			prefix += "@"
527			m = m[1:]
528			tail := ""
529			if last := m[len(m)-1]; last == ' ' || last == '\n' ||
530				last == ':' || last == ';' ||
531				last == '.' || last == ',' || last == '\'' {
532				tail = m[len(m)-1:]
533				m = m[:len(m)-1]
534			}
535
536			xid := fullname(m, userid)
537
538			if xid != "" {
539				_, name := handles(xid)
540				if name != "" {
541					nonstop = true
542					m = name
543				}
544			}
545			return prefix + m + tail
546		})
547	}
548	return s
549}
550
551var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
552	honkers := gethonkers(userid)
553	m := make(map[string]string)
554	for _, h := range honkers {
555		m[h.XID] = h.Name
556	}
557	return m, true
558}, Invalidator: &honkerinvalidator})
559
560func shortname(userid int64, xid string) string {
561	var m map[string]string
562	ok := shortnames.Get(userid, &m)
563	if ok {
564		return m[xid]
565	}
566	return ""
567}
568
569var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
570	honkers := gethonkers(userid)
571	m := make(map[string]string)
572	for _, h := range honkers {
573		m[h.Name] = h.XID
574	}
575	return m, true
576}, Invalidator: &honkerinvalidator})
577
578func fullname(name string, userid int64) string {
579	var m map[string]string
580	ok := fullnames.Get(userid, &m)
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 = cache.New(cache.Options{Filler: 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	var handle string
638	allhandles.Get(xid, &handle)
639	if handle == xid {
640		return xid, xid
641	}
642	return handle, handle + "@" + originate(xid)
643}
644
645func butnottooloud(aud []string) {
646	for i, a := range aud {
647		if strings.HasSuffix(a, "/followers") {
648			aud[i] = ""
649		}
650	}
651}
652
653func loudandproud(aud []string) bool {
654	for _, a := range aud {
655		if a == thewholeworld {
656			return true
657		}
658	}
659	return false
660}
661
662func firstclass(honk *Honk) bool {
663	return honk.Audience[0] == thewholeworld
664}
665
666func oneofakind(a []string) []string {
667	seen := make(map[string]bool)
668	seen[""] = true
669	j := 0
670	for _, s := range a {
671		if !seen[s] {
672			seen[s] = true
673			a[j] = s
674			j++
675		}
676	}
677	return a[:j]
678}
679
680var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
681	var user *WhatAbout
682	ok := somenumberedusers.Get(userid, &user)
683	if !ok {
684		return nil, false
685	}
686	ki := new(KeyInfo)
687	ki.keyname = user.URL + "#key"
688	ki.seckey = user.SecKey
689	return ki, true
690}})
691
692func ziggy(userid int64) *KeyInfo {
693	var ki *KeyInfo
694	ziggies.Get(userid, &ki)
695	return ki
696}
697
698var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
699	data := getxonker(keyname, "pubkey")
700	if data == "" {
701		dlog.Printf("hitting the webs for missing pubkey: %s", keyname)
702		j, err := GetJunk(readyLuserOne, keyname)
703		if err != nil {
704			ilog.Printf("error getting %s pubkey: %s", keyname, err)
705			when := time.Now().UTC().Format(dbtimeformat)
706			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
707			return httpsig.PublicKey{}, true
708		}
709		allinjest(originate(keyname), j)
710		data = getxonker(keyname, "pubkey")
711		if data == "" {
712			ilog.Printf("key not found after ingesting")
713			when := time.Now().UTC().Format(dbtimeformat)
714			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
715			return httpsig.PublicKey{}, true
716		}
717	}
718	if data == "failed" {
719		ilog.Printf("lookup previously failed key %s", keyname)
720		return httpsig.PublicKey{}, true
721	}
722	_, key, err := httpsig.DecodeKey(data)
723	if err != nil {
724		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
725		return key, true
726	}
727	return key, true
728}, Limit: 512})
729
730func zaggy(keyname string) (httpsig.PublicKey, error) {
731	var key httpsig.PublicKey
732	zaggies.Get(keyname, &key)
733	return key, nil
734}
735
736func savingthrow(keyname string) {
737	when := time.Now().Add(-30 * time.Minute).UTC().Format(dbtimeformat)
738	stmtDeleteXonker.Exec(keyname, "pubkey", when)
739	zaggies.Clear(keyname)
740}
741
742func keymatch(keyname string, actor string) string {
743	origin := originate(actor)
744	if origin == originate(keyname) {
745		return origin
746	}
747	return ""
748}