all repos — honk @ fe929ad91cd75fb5ffdafc460b9fe53357de21b6

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