all repos — honk @ 74409de06d55508eaf85daefb3312dc260055579

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 == "honked" && h.RID != "" {
 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		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(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_convalidate = regexp.MustCompile("^(https?|tag|data):")
459
460func memetize(honk *Honk) {
461	repl := func(x string) string {
462		name := x[5:]
463		if name[0] == ' ' {
464			name = name[1:]
465		}
466		fd, err := os.Open(dataDir + "/memes/" + name)
467		if err != nil {
468			ilog.Printf("no meme for %s", name)
469			return x
470		}
471		var peek [512]byte
472		n, _ := fd.Read(peek[:])
473		ct := http.DetectContentType(peek[:n])
474		fd.Close()
475
476		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
477		fileid, err := savefile(name, name, url, ct, false, nil)
478		if err != nil {
479			elog.Printf("error saving meme: %s", err)
480			return x
481		}
482		d := &Donk{
483			FileID: fileid,
484			Name:   name,
485			Media:  ct,
486			URL:    url,
487			Local:  false,
488		}
489		honk.Donks = append(honk.Donks, d)
490		return ""
491	}
492	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
493}
494
495var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]_]+([ \n:;.,']|$)")
496
497func quickrename(s string, userid int64) string {
498	nonstop := true
499	for nonstop {
500		nonstop = false
501		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
502			prefix := ""
503			if m[0] == ' ' || m[0] == '\n' {
504				prefix = m[:1]
505				m = m[1:]
506			}
507			prefix += "@"
508			m = m[1:]
509			tail := ""
510			if last := m[len(m)-1]; last == ' ' || last == '\n' ||
511				last == ':' || last == ';' ||
512				last == '.' || last == ',' || last == '\'' {
513				tail = m[len(m)-1:]
514				m = m[:len(m)-1]
515			}
516
517			xid := fullname(m, userid)
518
519			if xid != "" {
520				_, name := handles(xid)
521				if name != "" {
522					nonstop = true
523					m = name
524				}
525			}
526			return prefix + m + tail
527		})
528	}
529	return s
530}
531
532var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
533	honkers := gethonkers(userid)
534	m := make(map[string]string)
535	for _, h := range honkers {
536		m[h.XID] = h.Name
537	}
538	return m, true
539}, Invalidator: &honkerinvalidator})
540
541func shortname(userid int64, xid string) string {
542	var m map[string]string
543	ok := shortnames.Get(userid, &m)
544	if ok {
545		return m[xid]
546	}
547	return ""
548}
549
550var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
551	honkers := gethonkers(userid)
552	m := make(map[string]string)
553	for _, h := range honkers {
554		m[h.Name] = h.XID
555	}
556	return m, true
557}, Invalidator: &honkerinvalidator})
558
559func fullname(name string, userid int64) string {
560	var m map[string]string
561	ok := fullnames.Get(userid, &m)
562	if ok {
563		return m[name]
564	}
565	return ""
566}
567
568func attoreplacer(m string) string {
569	fill := `<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`
570	where := gofish(m)
571	if where == "" {
572		return m
573	}
574	who := m[0 : 1+strings.IndexByte(m[1:], '@')]
575	return fmt.Sprintf(fill, html.EscapeString(where), html.EscapeString(who))
576}
577
578func ontoreplacer(h string) string {
579	return fmt.Sprintf(`<a class="mention hashtag" href="https://%s/o/%s">%s</a>`, serverName,
580		strings.ToLower(h[1:]), h)
581}
582
583var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
584var re_urlhost = regexp.MustCompile("https://([^/ #)]+)")
585
586func originate(u string) string {
587	m := re_urlhost.FindStringSubmatch(u)
588	if len(m) > 1 {
589		return m[1]
590	}
591	return ""
592}
593
594var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
595	handle := getxonker(xid, "handle")
596	if handle == "" {
597		dlog.Printf("need to get a handle: %s", xid)
598		info, err := investigate(xid)
599		if err != nil {
600			m := re_unurl.FindStringSubmatch(xid)
601			if len(m) > 2 {
602				handle = m[2]
603			} else {
604				handle = xid
605			}
606		} else {
607			handle = info.Name
608		}
609	}
610	return handle, true
611}})
612
613// handle, handle@host
614func handles(xid string) (string, string) {
615	if xid == "" || xid == thewholeworld || strings.HasSuffix(xid, "/followers") {
616		return "", ""
617	}
618	var handle string
619	allhandles.Get(xid, &handle)
620	if handle == xid {
621		return xid, xid
622	}
623	return handle, handle + "@" + originate(xid)
624}
625
626func butnottooloud(aud []string) {
627	for i, a := range aud {
628		if strings.HasSuffix(a, "/followers") {
629			aud[i] = ""
630		}
631	}
632}
633
634func loudandproud(aud []string) bool {
635	for _, a := range aud {
636		if a == thewholeworld {
637			return true
638		}
639	}
640	return false
641}
642
643func firstclass(honk *Honk) bool {
644	return honk.Audience[0] == thewholeworld
645}
646
647func oneofakind(a []string) []string {
648	seen := make(map[string]bool)
649	seen[""] = true
650	j := 0
651	for _, s := range a {
652		if !seen[s] {
653			seen[s] = true
654			a[j] = s
655			j++
656		}
657	}
658	return a[:j]
659}
660
661var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
662	var user *WhatAbout
663	ok := somenumberedusers.Get(userid, &user)
664	if !ok {
665		return nil, false
666	}
667	ki := new(KeyInfo)
668	ki.keyname = user.URL + "#key"
669	ki.seckey = user.SecKey
670	return ki, true
671}})
672
673func ziggy(userid int64) *KeyInfo {
674	var ki *KeyInfo
675	ziggies.Get(userid, &ki)
676	return ki
677}
678
679var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
680	data := getxonker(keyname, "pubkey")
681	if data == "" {
682		dlog.Printf("hitting the webs for missing pubkey: %s", keyname)
683		j, err := GetJunk(readyLuserOne, keyname)
684		if err != nil {
685			ilog.Printf("error getting %s pubkey: %s", keyname, err)
686			when := time.Now().UTC().Format(dbtimeformat)
687			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
688			return httpsig.PublicKey{}, true
689		}
690		allinjest(originate(keyname), j)
691		data = getxonker(keyname, "pubkey")
692		if data == "" {
693			ilog.Printf("key not found after ingesting")
694			when := time.Now().UTC().Format(dbtimeformat)
695			stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
696			return httpsig.PublicKey{}, true
697		}
698	}
699	if data == "failed" {
700		ilog.Printf("lookup previously failed key %s", keyname)
701		return httpsig.PublicKey{}, true
702	}
703	_, key, err := httpsig.DecodeKey(data)
704	if err != nil {
705		ilog.Printf("error decoding %s pubkey: %s", keyname, err)
706		return key, true
707	}
708	return key, true
709}, Limit: 512})
710
711func zaggy(keyname string) (httpsig.PublicKey, error) {
712	var key httpsig.PublicKey
713	zaggies.Get(keyname, &key)
714	return key, nil
715}
716
717func savingthrow(keyname string) {
718	when := time.Now().Add(-30 * time.Minute).UTC().Format(dbtimeformat)
719	stmtDeleteXonker.Exec(keyname, "pubkey", when)
720	zaggies.Clear(keyname)
721}
722
723func keymatch(keyname string, actor string) string {
724	origin := originate(actor)
725	if origin == originate(keyname) {
726		return origin
727	}
728	return ""
729}