all repos — honk @ 2f7172ce8ad77d2655f526ec0d9a4fa0cf30615c

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