all repos — honk @ 4ecb3d97dc4c0b98a5a8f24aa4fad23116be1908

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	"github.com/dustin/go-humanize"
 32	"golang.org/x/net/html"
 33	"humungus.tedunangst.com/r/webs/cache"
 34	"humungus.tedunangst.com/r/webs/htfilter"
 35	"humungus.tedunangst.com/r/webs/httpsig"
 36	"humungus.tedunangst.com/r/webs/mz"
 37	"humungus.tedunangst.com/r/webs/templates"
 38)
 39
 40var allowedclasses = make(map[string]bool)
 41
 42func init() {
 43	allowedclasses["kw"] = true
 44	allowedclasses["bi"] = true
 45	allowedclasses["st"] = true
 46	allowedclasses["nm"] = true
 47	allowedclasses["tp"] = true
 48	allowedclasses["op"] = true
 49	allowedclasses["cm"] = true
 50	allowedclasses["al"] = true
 51	allowedclasses["dl"] = true
 52}
 53
 54var relingo = make(map[string]string)
 55
 56func loadLingo() {
 57	for _, l := range []string{"honked", "bonked", "honked back", "qonked", "evented"} {
 58		v := l
 59		k := "lingo-" + strings.ReplaceAll(l, " ", "")
 60		getconfig(k, &v)
 61		relingo[l] = v
 62	}
 63}
 64
 65func prettifydate(d time.Time) string {
 66	var customMags = []humanize.RelTimeMagnitude{
 67		{time.Second, "now", time.Second},
 68		{2 * time.Second, "1s %s", 1},
 69		{time.Minute, "%ds %s", time.Second},
 70		{2 * time.Minute, "1m %s", 1},
 71		{time.Hour, "%dm %s", time.Minute},
 72		{2 * time.Hour, "1h %s", 1},
 73		{humanize.Day, "%dh %s", time.Hour},
 74		{2 * humanize.Day, "1d %s", 1},
 75		{humanize.Week, "%dd %s", humanize.Day},
 76		{2 * humanize.Week, "1w %s", 1},
 77		{humanize.Month, "%dw %s", humanize.Week},
 78	}
 79
 80	since := time.Since(d)
 81	// More than a month, return the actual date.
 82	if since.Hours() > 730 {
 83		return d.Format("02 Jan 2006 15:04")
 84	}
 85
 86	return humanize.CustomRelTime(d, time.Now(), "", "from now", customMags)
 87}
 88
 89func reverbolate(userid int64, honks []*Honk) {
 90	var user *WhatAbout
 91	somenumberedusers.Get(userid, &user)
 92	for _, h := range honks {
 93		// idk where else to put this
 94		h.DatePretty = prettifydate(h.Date)
 95		h.What += "ed"
 96		if h.What == "tonked" {
 97			h.What = "honked back"
 98			h.Style += " subtle"
 99		}
100		if !h.Public {
101			h.Style += " limited"
102		}
103		if h.Whofore == 1 {
104			h.Style += " atme"
105		}
106		translate(h)
107		local := false
108		if h.Whofore == 2 || h.Whofore == 3 {
109			local = true
110		}
111		if local && h.What != "bonked" {
112			h.Noise = re_memes.ReplaceAllString(h.Noise, "")
113		}
114		h.Username, h.Handle = handles(h.Honker)
115		if !local {
116			short := shortname(userid, h.Honker)
117			if short != "" {
118				h.Username = short
119			} else {
120				h.Username = h.Handle
121				if len(h.Username) > 20 {
122					h.Username = h.Username[:20] + ".."
123				}
124			}
125		}
126		if user != nil {
127			hset := []string{}
128			if h.Honker != user.URL {
129				hset = append(hset, "@"+h.Handle)
130			}
131			if user.Options.MentionAll {
132				for _, a := range h.Audience {
133					if a == h.Honker || a == user.URL {
134						continue
135					}
136					_, hand := handles(a)
137					if hand != "" {
138						hand = "@" + hand
139						hset = append(hset, hand)
140					}
141				}
142			}
143			h.Handles = strings.Join(hset, " ")
144		}
145		if h.URL == "" {
146			h.URL = h.XID
147		}
148		if h.Oonker != "" {
149			_, h.Oondle = handles(h.Oonker)
150		}
151		h.Precis = demoji(h.Precis)
152		h.Noise = demoji(h.Noise)
153		h.Open = "open"
154		for _, m := range h.Mentions {
155			if m.Where != h.Honker && !m.IsPresent(h.Noise) {
156				h.Noise = "(" + m.Who + ")" + h.Noise
157			}
158		}
159
160		zap := make(map[string]bool)
161		{
162			var htf htfilter.Filter
163			htf.Imager = replaceimgsand(zap, false)
164			htf.SpanClasses = allowedclasses
165			htf.BaseURL, _ = url.Parse(h.XID)
166			emuxifier := func(e string) string {
167				for _, d := range h.Donks {
168					if d.Name == e {
169						zap[d.XID] = true
170						if d.Local {
171							return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
172						}
173					}
174				}
175				if local && h.What != "bonked" {
176					var emu Emu
177					emucache.Get(e, &emu)
178					if emu.ID != "" {
179						return fmt.Sprintf(`<img class="emu" title="%s" src="%s">`, emu.Name, emu.ID)
180					}
181				}
182				return e
183			}
184			htf.FilterText = func(w io.Writer, data string) {
185				data = htfilter.EscapeText(data)
186				data = re_emus.ReplaceAllStringFunc(data, emuxifier)
187				io.WriteString(w, data)
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		noise = markitzero(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			var emu Emu
268			emucache.Get(e, &emu)
269			if emu.ID != "" {
270				return fmt.Sprintf(`<img class="emu" title="%s" src="%s">`, emu.Name, emu.ID)
271			}
272		}
273		return e
274	}
275	noise = re_emus.ReplaceAllStringFunc(noise, emuxifier)
276	j := 0
277	for i := 0; i < len(ch.Donks); i++ {
278		if !zap[ch.Donks[i].XID] {
279			ch.Donks[j] = ch.Donks[i]
280			j++
281		}
282	}
283	ch.Donks = ch.Donks[:j]
284
285	if strings.HasPrefix(noise, "<p>") {
286		noise = noise[3:]
287	}
288	ch.HTML = template.HTML(noise)
289	if short := shortname(ch.UserID, ch.Who); short != "" {
290		ch.Handle = short
291	} else {
292		ch.Handle, _ = handles(ch.Who)
293	}
294
295}
296
297func inlineimgsfor(honk *Honk) func(node *html.Node) string {
298	return func(node *html.Node) string {
299		src := htfilter.GetAttr(node, "src")
300		alt := htfilter.GetAttr(node, "alt")
301		d := savedonk(src, "image", alt, "image", true)
302		if d != nil {
303			honk.Donks = append(honk.Donks, d)
304		}
305		dlog.Printf("inline img with src: %s", src)
306		return ""
307	}
308}
309
310func imaginate(honk *Honk) {
311	var htf htfilter.Filter
312	htf.Imager = inlineimgsfor(honk)
313	htf.BaseURL, _ = url.Parse(honk.XID)
314	htf.String(honk.Noise)
315}
316
317var re_dangerous = regexp.MustCompile("^[a-zA-Z]{2}:")
318
319func precipitate(honk *Honk) {
320	noise := honk.Noise
321	if re_dangerous.MatchString(noise) {
322		idx := strings.Index(noise, "\n")
323		if idx == -1 {
324			honk.Precis = noise
325			noise = ""
326		} else {
327			honk.Precis = noise[:idx]
328			noise = noise[idx+1:]
329		}
330		honk.Precis = markitzero(strings.TrimSpace(honk.Precis))
331		honk.Noise = noise
332	}
333}
334
335func translate(honk *Honk) {
336	if honk.Format == "html" {
337		return
338	}
339	noise := honk.Noise
340
341	var marker mz.Marker
342	marker.HashLinker = ontoreplacer
343	marker.AtLinker = attoreplacer
344	noise = strings.TrimSpace(noise)
345	noise = marker.Mark(noise)
346	honk.Noise = noise
347	honk.Onts = oneofakind(marker.HashTags)
348	honk.Mentions = bunchofgrapes(marker.Mentions)
349}
350
351func redoimages(honk *Honk) {
352	zap := make(map[string]bool)
353	{
354		var htf htfilter.Filter
355		htf.Imager = replaceimgsand(zap, true)
356		htf.SpanClasses = allowedclasses
357		p, _ := htf.String(honk.Precis)
358		n, _ := htf.String(honk.Noise)
359		honk.Precis = string(p)
360		honk.Noise = string(n)
361	}
362	j := 0
363	for i := 0; i < len(honk.Donks); i++ {
364		if !zap[honk.Donks[i].XID] {
365			honk.Donks[j] = honk.Donks[i]
366			j++
367		}
368	}
369	honk.Donks = honk.Donks[:j]
370
371	honk.Noise = re_memes.ReplaceAllString(honk.Noise, "")
372	honk.Noise = strings.Replace(honk.Noise, "<a href=", "<a class=\"mention u-url\" href=", -1)
373}
374
375func xcelerate(b []byte) string {
376	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
377	for i, c := range b {
378		b[i] = letters[c&63]
379	}
380	s := string(b)
381	return s
382}
383
384func shortxid(xid string) string {
385	h := sha512.New512_256()
386	io.WriteString(h, xid)
387	return xcelerate(h.Sum(nil)[:20])
388}
389
390func xfiltrate() string {
391	var b [18]byte
392	rand.Read(b[:])
393	return xcelerate(b[:])
394}
395
396func grapevine(mentions []Mention) []string {
397	var s []string
398	for _, m := range mentions {
399		s = append(s, m.Where)
400	}
401	return s
402}
403
404func bunchofgrapes(m []string) []Mention {
405	var mentions []Mention
406	for i := range m {
407		where := gofish(m[i])
408		if where != "" {
409			mentions = append(mentions, Mention{Who: m[i], Where: where})
410		}
411	}
412	return mentions
413}
414
415type Emu struct {
416	ID   string
417	Name string
418	Type string
419}
420
421var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
422
423var emucache = cache.New(cache.Options{Filler: func(ename string) (Emu, bool) {
424	fname := ename[1 : len(ename)-1]
425	exts := []string{".png", ".gif"}
426	for _, ext := range exts {
427		_, err := os.Stat(dataDir + "/emus/" + fname + ext)
428		if err != nil {
429			continue
430		}
431		url := fmt.Sprintf("https://%s/emu/%s%s", serverName, fname, ext)
432		return Emu{ID: url, Name: ename, Type: "image/" + ext[1:]}, true
433	}
434	return Emu{Name: ename, ID: "", Type: "image/png"}, true
435}, Duration: 10 * time.Second})
436
437func herdofemus(noise string) []Emu {
438	m := re_emus.FindAllString(noise, -1)
439	m = oneofakind(m)
440	var emus []Emu
441	for _, e := range m {
442		var emu Emu
443		emucache.Get(e, &emu)
444		if emu.ID == "" {
445			continue
446		}
447		emus = append(emus, emu)
448	}
449	return emus
450}
451
452var re_memes = regexp.MustCompile("meme: ?([^\n]+)")
453var re_avatar = regexp.MustCompile("avatar: ?([^\n]+)")
454var re_banner = regexp.MustCompile("banner: ?([^\n]+)")
455var re_convoy = regexp.MustCompile("convoy: ?([^\n]+)")
456var re_convalidate = regexp.MustCompile("^(https?|tag|data):")
457
458func memetize(honk *Honk) {
459	repl := func(x string) string {
460		name := x[5:]
461		if name[0] == ' ' {
462			name = name[1:]
463		}
464		fd, err := os.Open(dataDir + "/memes/" + name)
465		if err != nil {
466			ilog.Printf("no meme for %s", name)
467			return x
468		}
469		var peek [512]byte
470		n, _ := fd.Read(peek[:])
471		ct := http.DetectContentType(peek[:n])
472		fd.Close()
473
474		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
475		fileid, err := savefile(name, name, url, ct, false, nil)
476		if err != nil {
477			elog.Printf("error saving meme: %s", err)
478			return x
479		}
480		d := &Donk{
481			FileID: fileid,
482			Name:   name,
483			Media:  ct,
484			URL:    url,
485			Local:  false,
486		}
487		honk.Donks = append(honk.Donks, d)
488		return ""
489	}
490	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
491}
492
493var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]_]+([ \n:;.,']|$)")
494
495func quickrename(s string, userid int64) string {
496	nonstop := true
497	for nonstop {
498		nonstop = false
499		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
500			prefix := ""
501			if m[0] == ' ' || m[0] == '\n' {
502				prefix = m[:1]
503				m = m[1:]
504			}
505			prefix += "@"
506			m = m[1:]
507			tail := ""
508			if last := m[len(m)-1]; last == ' ' || last == '\n' ||
509				last == ':' || last == ';' ||
510				last == '.' || last == ',' || last == '\'' {
511				tail = m[len(m)-1:]
512				m = m[:len(m)-1]
513			}
514
515			xid := fullname(m, userid)
516
517			if xid != "" {
518				_, name := handles(xid)
519				if name != "" {
520					nonstop = true
521					m = name
522				}
523			}
524			return prefix + m + tail
525		})
526	}
527	return s
528}
529
530var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
531	honkers := gethonkers(userid)
532	m := make(map[string]string)
533	for _, h := range honkers {
534		m[h.XID] = h.Name
535	}
536	return m, true
537}, Invalidator: &honkerinvalidator})
538
539func shortname(userid int64, xid string) string {
540	var m map[string]string
541	ok := shortnames.Get(userid, &m)
542	if ok {
543		return m[xid]
544	}
545	return ""
546}
547
548var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
549	honkers := gethonkers(userid)
550	m := make(map[string]string)
551	for _, h := range honkers {
552		m[h.Name] = h.XID
553	}
554	return m, true
555}, Invalidator: &honkerinvalidator})
556
557func fullname(name string, userid int64) string {
558	var m map[string]string
559	ok := fullnames.Get(userid, &m)
560	if ok {
561		return m[name]
562	}
563	return ""
564}
565
566func attoreplacer(m string) string {
567	fill := `<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`
568	where := gofish(m)
569	if where == "" {
570		return m
571	}
572	who := m[0 : 1+strings.IndexByte(m[1:], '@')]
573	return fmt.Sprintf(fill, html.EscapeString(where), html.EscapeString(who))
574}
575
576func ontoreplacer(h string) string {
577	return fmt.Sprintf(`<a href="https://%s/o/%s">%s</a>`, serverName,
578		strings.ToLower(h[1:]), h)
579}
580
581var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
582var re_urlhost = regexp.MustCompile("https://([^/ #)]+)")
583
584func originate(u string) string {
585	m := re_urlhost.FindStringSubmatch(u)
586	if len(m) > 1 {
587		return m[1]
588	}
589	return ""
590}
591
592var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
593	handle := getxonker(xid, "handle")
594	if handle == "" {
595		dlog.Printf("need to get a handle: %s", xid)
596		info, err := investigate(xid)
597		if err != nil {
598			m := re_unurl.FindStringSubmatch(xid)
599			if len(m) > 2 {
600				handle = m[2]
601			} else {
602				handle = xid
603			}
604		} else {
605			handle = info.Name
606		}
607	}
608	return handle, true
609}})
610
611// handle, handle@host
612func handles(xid string) (string, string) {
613	if xid == "" || xid == thewholeworld || strings.HasSuffix(xid, "/followers") {
614		return "", ""
615	}
616	var handle string
617	allhandles.Get(xid, &handle)
618	if handle == xid {
619		return xid, xid
620	}
621	return handle, handle + "@" + originate(xid)
622}
623
624func butnottooloud(aud []string) {
625	for i, a := range aud {
626		if strings.HasSuffix(a, "/followers") {
627			aud[i] = ""
628		}
629	}
630}
631
632func loudandproud(aud []string) bool {
633	for _, a := range aud {
634		if a == thewholeworld {
635			return true
636		}
637	}
638	return false
639}
640
641func firstclass(honk *Honk) bool {
642	return honk.Audience[0] == thewholeworld
643}
644
645func oneofakind(a []string) []string {
646	seen := make(map[string]bool)
647	seen[""] = true
648	j := 0
649	for _, s := range a {
650		if !seen[s] {
651			seen[s] = true
652			a[j] = s
653			j++
654		}
655	}
656	return a[:j]
657}
658
659var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
660	var user *WhatAbout
661	ok := somenumberedusers.Get(userid, &user)
662	if !ok {
663		return nil, false
664	}
665	ki := new(KeyInfo)
666	ki.keyname = user.URL + "#key"
667	ki.seckey = user.SecKey
668	return ki, true
669}})
670
671func ziggy(userid int64) *KeyInfo {
672	var ki *KeyInfo
673	ziggies.Get(userid, &ki)
674	return ki
675}
676
677var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
678	data := getxonker(keyname, "pubkey")
679	if data == "" {
680		dlog.Printf("hitting the webs for missing pubkey: %s", keyname)
681		j, err := GetJunk(readyLuserOne, keyname)
682		if err != nil {
683			ilog.Printf("error getting %s pubkey: %s", keyname, err)
684			when := time.Now().UTC().Format(dbtimeformat)
685			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
686			return httpsig.PublicKey{}, true
687		}
688		allinjest(originate(keyname), j)
689		data = getxonker(keyname, "pubkey")
690		if data == "" {
691			ilog.Printf("key not found after ingesting")
692			when := time.Now().UTC().Format(dbtimeformat)
693			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
694			return httpsig.PublicKey{}, true
695		}
696	}
697	if data == "failed" {
698		ilog.Printf("lookup previously failed key %s", keyname)
699		return httpsig.PublicKey{}, true
700	}
701	_, key, err := httpsig.DecodeKey(data)
702	if err != nil {
703		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
704		return key, true
705	}
706	return key, true
707}, Limit: 512})
708
709func zaggy(keyname string) (httpsig.PublicKey, error) {
710	var key httpsig.PublicKey
711	zaggies.Get(keyname, &key)
712	return key, nil
713}
714
715func savingthrow(keyname string) {
716	when := time.Now().Add(-30 * time.Minute).UTC().Format(dbtimeformat)
717	stmtDeleteXonker.Exec(keyname, "pubkey", when)
718	zaggies.Clear(keyname)
719}
720
721func keymatch(keyname string, actor string) string {
722	hash := strings.IndexByte(keyname, '#')
723	if hash == -1 {
724		hash = len(keyname)
725	}
726	owner := keyname[0:hash]
727	if owner == actor {
728		return originate(actor)
729	}
730	return ""
731}