all repos — honk @ a7b12f7cc706b4ad652a52e489019a7f301754a1

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