all repos — honk @ 7c24aac3d0f284da536834b968e6463f857d7ada

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: ?([^\n]+)")
344var re_avatar = regexp.MustCompile("avatar: ?([^\n]+)")
345
346func memetize(honk *Honk) {
347	repl := func(x string) string {
348		name := x[5:]
349		if name[0] == ' ' {
350			name = name[1:]
351		}
352		fd, err := os.Open("memes/" + name)
353		if err != nil {
354			log.Printf("no meme for %s", name)
355			return x
356		}
357		var peek [512]byte
358		n, _ := fd.Read(peek[:])
359		ct := http.DetectContentType(peek[:n])
360		fd.Close()
361
362		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
363		fileid, err := savefile("", name, name, url, ct, false, nil)
364		if err != nil {
365			log.Printf("error saving meme: %s", err)
366			return x
367		}
368		d := &Donk{
369			FileID: fileid,
370			XID:    "",
371			Name:   name,
372			Media:  ct,
373			URL:    url,
374			Local:  false,
375		}
376		honk.Donks = append(honk.Donks, d)
377		return ""
378	}
379	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
380}
381
382var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]]+([ \n]|$)")
383
384func quickrename(s string, userid int64) string {
385	nonstop := true
386	for nonstop {
387		nonstop = false
388		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
389			prefix := ""
390			if m[0] == ' ' || m[0] == '\n' {
391				prefix = m[:1]
392				m = m[1:]
393			}
394			prefix += "@"
395			m = m[1:]
396			tail := ""
397			if m[len(m)-1] == ' ' || m[len(m)-1] == '\n' {
398				tail = m[len(m)-1:]
399				m = m[:len(m)-1]
400			}
401
402			xid := fullname(m, userid)
403
404			if xid != "" {
405				_, name := handles(xid)
406				if name != "" {
407					nonstop = true
408					m = name
409				}
410			}
411			return prefix + m + tail
412		})
413	}
414	return s
415}
416
417var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
418	honkers := gethonkers(userid)
419	m := make(map[string]string)
420	for _, h := range honkers {
421		m[h.XID] = h.Name
422	}
423	return m, true
424}, Invalidator: &honkerinvalidator})
425
426func shortname(userid int64, xid string) string {
427	var m map[string]string
428	ok := shortnames.Get(userid, &m)
429	if ok {
430		return m[xid]
431	}
432	return ""
433}
434
435var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
436	honkers := gethonkers(userid)
437	m := make(map[string]string)
438	for _, h := range honkers {
439		m[h.Name] = h.XID
440	}
441	return m, true
442}, Invalidator: &honkerinvalidator})
443
444func fullname(name string, userid int64) string {
445	var m map[string]string
446	ok := fullnames.Get(userid, &m)
447	if ok {
448		return m[name]
449	}
450	return ""
451}
452
453func mentionize(s string) string {
454	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
455		where := gofish(m)
456		if where == "" {
457			return m
458		}
459		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
460		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
461			html.EscapeString(where), html.EscapeString(who))
462	})
463	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
464		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
465			html.EscapeString(m[1:]), html.EscapeString(m))
466	})
467	return s
468}
469
470func ontologize(s string) string {
471	s = re_hashes.ReplaceAllStringFunc(s, func(o string) string {
472		if o[0] == '&' {
473			return o
474		}
475		p := ""
476		h := o
477		if h[0] != '#' {
478			p = h[:1]
479			h = h[1:]
480		}
481		return fmt.Sprintf(`%s<a href="https://%s/o/%s">%s</a>`, p, serverName,
482			strings.ToLower(h[1:]), h)
483	})
484	return s
485}
486
487var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
488var re_urlhost = regexp.MustCompile("https://([^/ ]+)")
489
490func originate(u string) string {
491	m := re_urlhost.FindStringSubmatch(u)
492	if len(m) > 1 {
493		return m[1]
494	}
495	return ""
496}
497
498var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
499	var handle string
500	row := stmtGetXonker.QueryRow(xid, "handle")
501	err := row.Scan(&handle)
502	if err != nil {
503		log.Printf("need to get a handle: %s", xid)
504		info, err := investigate(xid)
505		if err != nil {
506			m := re_unurl.FindStringSubmatch(xid)
507			if len(m) > 2 {
508				handle = m[2]
509			} else {
510				handle = xid
511			}
512		} else {
513			handle = info.Name
514		}
515	}
516	return handle, true
517}})
518
519// handle, handle@host
520func handles(xid string) (string, string) {
521	if xid == "" {
522		return "", ""
523	}
524	var handle string
525	allhandles.Get(xid, &handle)
526	if handle == xid {
527		return xid, xid
528	}
529	return handle, handle + "@" + originate(xid)
530}
531
532func butnottooloud(aud []string) {
533	for i, a := range aud {
534		if strings.HasSuffix(a, "/followers") {
535			aud[i] = ""
536		}
537	}
538}
539
540func loudandproud(aud []string) bool {
541	for _, a := range aud {
542		if a == thewholeworld {
543			return true
544		}
545	}
546	return false
547}
548
549func firstclass(honk *Honk) bool {
550	return honk.Audience[0] == thewholeworld
551}
552
553func oneofakind(a []string) []string {
554	seen := make(map[string]bool)
555	seen[""] = true
556	j := 0
557	for _, s := range a {
558		if !seen[s] {
559			seen[s] = true
560			a[j] = s
561			j++
562		}
563	}
564	return a[:j]
565}
566
567var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
568	var user *WhatAbout
569	ok := somenumberedusers.Get(userid, &user)
570	if !ok {
571		return nil, false
572	}
573	ki := new(KeyInfo)
574	ki.keyname = user.URL + "#key"
575	ki.seckey = user.SecKey
576	return ki, true
577}})
578
579func ziggy(userid int64) *KeyInfo {
580	var ki *KeyInfo
581	ziggies.Get(userid, &ki)
582	return ki
583}
584
585var zaggies = cache.New(cache.Options{Filler: func(keyname string) (*rsa.PublicKey, bool) {
586	var data string
587	row := stmtGetXonker.QueryRow(keyname, "pubkey")
588	err := row.Scan(&data)
589	if err != nil {
590		log.Printf("hitting the webs for missing pubkey: %s", keyname)
591		j, err := GetJunk(keyname)
592		if err != nil {
593			log.Printf("error getting %s pubkey: %s", keyname, err)
594			return nil, true
595		}
596		allinjest(originate(keyname), j)
597		row = stmtGetXonker.QueryRow(keyname, "pubkey")
598		err = row.Scan(&data)
599		if err != nil {
600			log.Printf("key not found after ingesting")
601			return nil, true
602		}
603	}
604	_, key, err := httpsig.DecodeKey(data)
605	if err != nil {
606		log.Printf("error decoding %s pubkey: %s", keyname, err)
607		return nil, true
608	}
609	return key, true
610}, Limit: 512})
611
612func zaggy(keyname string) *rsa.PublicKey {
613	var key *rsa.PublicKey
614	zaggies.Get(keyname, &key)
615	return key
616}
617
618func savingthrow(keyname string) {
619	when := time.Now().UTC().Add(-30 * time.Minute).Format(dbtimeformat)
620	stmtDeleteXonker.Exec(keyname, "pubkey", when)
621	zaggies.Clear(keyname)
622}
623
624func keymatch(keyname string, actor string) string {
625	hash := strings.IndexByte(keyname, '#')
626	if hash == -1 {
627		hash = len(keyname)
628	}
629	owner := keyname[0:hash]
630	if owner == actor {
631		return originate(actor)
632	}
633	return ""
634}