all repos — honk @ 058701b1e5190dc5ab1b97aff801211d6173e012

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