all repos — honk @ af18a4b1d3f52d22c4ed97213f2b21c98a90f913

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