all repos — honk @ 66c6ced8bf552408c833216614873a616b2720dc

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