all repos — honk @ a0b721897cb67ad05c730f2440e180998f9d8dec

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