all repos — honk @ e7b725fabdc66d45df72fe053e0dbcef55aa2c27

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