all repos — honk @ d893465f775e70a9e59c6cf5046ac85f5001d813

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