all repos — honk @ 9a63a4bc42b3661b2442a7afd482d10e12ea6c03

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