all repos — honk @ 6e06b3da023f9d93e3d71c6da0c889e803d06c9c

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