all repos — honk @ 064190785d488d3a51619dfe78676debfffb13e4

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