all repos — honk @ c95733102f7d2fc27b69a20b983c17aa35b15891

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