all repos — honk @ 6ee14862c0c3842dc1bf86505b6f5b7804d9bf84

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			honk.Noise = strings.Replace(honk.Noise, "<a href=", "<a class=\"mention u-url\" href=", -1)
224		}
225		j := 0
226		for i := 0; i < len(honk.Donks); i++ {
227			if !zap[honk.Donks[i].XID] {
228				honk.Donks[j] = honk.Donks[i]
229				j++
230			}
231		}
232		honk.Donks = honk.Donks[:j]
233	}
234}
235
236func xcelerate(b []byte) string {
237	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
238	for i, c := range b {
239		b[i] = letters[c&63]
240	}
241	s := string(b)
242	return s
243}
244
245func shortxid(xid string) string {
246	h := sha512.New512_256()
247	io.WriteString(h, xid)
248	return xcelerate(h.Sum(nil)[:20])
249}
250
251func xfiltrate() string {
252	var b [18]byte
253	rand.Read(b[:])
254	return xcelerate(b[:])
255}
256
257var re_hashes = regexp.MustCompile(`(?:^| )#[[:alnum:]][[:alnum:]_-]*`)
258
259func ontologies(s string) []string {
260	m := re_hashes.FindAllString(s, -1)
261	j := 0
262	for _, h := range m {
263		if h[0] == '&' {
264			continue
265		}
266		if h[0] != '#' {
267			h = h[1:]
268		}
269		m[j] = h
270		j++
271	}
272	return m[:j]
273}
274
275type Mention struct {
276	who   string
277	where string
278}
279
280var re_mentions = regexp.MustCompile(`@[[:alnum:]._-]+@[[:alnum:].-]*[[:alnum:]]`)
281var re_urltions = regexp.MustCompile(`@https://\S+`)
282
283func grapevine(s string) []string {
284	var mentions []string
285	m := re_mentions.FindAllString(s, -1)
286	for i := range m {
287		where := gofish(m[i])
288		if where != "" {
289			mentions = append(mentions, where)
290		}
291	}
292	m = re_urltions.FindAllString(s, -1)
293	for i := range m {
294		mentions = append(mentions, m[i][1:])
295	}
296	return mentions
297}
298
299func bunchofgrapes(s string) []Mention {
300	m := re_mentions.FindAllString(s, -1)
301	var mentions []Mention
302	for i := range m {
303		where := gofish(m[i])
304		if where != "" {
305			mentions = append(mentions, Mention{who: m[i], where: where})
306		}
307	}
308	m = re_urltions.FindAllString(s, -1)
309	for i := range m {
310		mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
311	}
312	return mentions
313}
314
315type Emu struct {
316	ID   string
317	Name string
318}
319
320var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
321
322func herdofemus(noise string) []Emu {
323	m := re_emus.FindAllString(noise, -1)
324	m = oneofakind(m)
325	var emus []Emu
326	for _, e := range m {
327		fname := e[1 : len(e)-1]
328		_, err := os.Stat("emus/" + fname + ".png")
329		if err != nil {
330			continue
331		}
332		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
333		emus = append(emus, Emu{ID: url, Name: e})
334	}
335	return emus
336}
337
338var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
339
340func memetize(honk *Honk) {
341	repl := func(x string) string {
342		name := x[5:]
343		if name[0] == ' ' {
344			name = name[1:]
345		}
346		fd, err := os.Open("memes/" + name)
347		if err != nil {
348			log.Printf("no meme for %s", name)
349			return x
350		}
351		var peek [512]byte
352		n, _ := fd.Read(peek[:])
353		ct := http.DetectContentType(peek[:n])
354		fd.Close()
355
356		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
357		fileid, err := savefile("", name, name, url, ct, false, nil)
358		if err != nil {
359			log.Printf("error saving meme: %s", err)
360			return x
361		}
362		d := &Donk{
363			FileID: fileid,
364			XID:    "",
365			Name:   name,
366			Media:  ct,
367			URL:    url,
368			Local:  false,
369		}
370		honk.Donks = append(honk.Donks, d)
371		return ""
372	}
373	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
374}
375
376var re_quickmention = regexp.MustCompile("(^| )@[[:alnum:]]+( |$)")
377
378func quickrename(s string, userid int64) string {
379	nonstop := true
380	for nonstop {
381		nonstop = false
382		s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
383			prefix := ""
384			if m[0] == ' ' {
385				prefix = " "
386				m = m[1:]
387			}
388			prefix += "@"
389			m = m[1:]
390			if m[len(m)-1] == ' ' {
391				m = m[:len(m)-1]
392			}
393
394			xid := fullname(m, userid)
395
396			if xid != "" {
397				_, name := handles(xid)
398				if name != "" {
399					nonstop = true
400					m = name
401				}
402			}
403			return prefix + m + " "
404		})
405	}
406	return s
407}
408
409var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
410	honkers := gethonkers(userid)
411	m := make(map[string]string)
412	for _, h := range honkers {
413		m[h.XID] = h.Name
414	}
415	return m, true
416}, Invalidator: &honkerinvalidator})
417
418func shortname(userid int64, xid string) string {
419	var m map[string]string
420	ok := shortnames.Get(userid, &m)
421	if ok {
422		return m[xid]
423	}
424	return ""
425}
426
427var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
428	honkers := gethonkers(userid)
429	m := make(map[string]string)
430	for _, h := range honkers {
431		m[h.Name] = h.XID
432	}
433	return m, true
434}, Invalidator: &honkerinvalidator})
435
436func fullname(name string, userid int64) string {
437	var m map[string]string
438	ok := fullnames.Get(userid, &m)
439	if ok {
440		return m[name]
441	}
442	return ""
443}
444
445func mentionize(s string) string {
446	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
447		where := gofish(m)
448		if where == "" {
449			return m
450		}
451		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
452		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
453			html.EscapeString(where), html.EscapeString(who))
454	})
455	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
456		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
457			html.EscapeString(m[1:]), html.EscapeString(m))
458	})
459	return s
460}
461
462func ontologize(s string) string {
463	s = re_hashes.ReplaceAllStringFunc(s, func(o string) string {
464		if o[0] == '&' {
465			return o
466		}
467		p := ""
468		h := o
469		if h[0] != '#' {
470			p = h[:1]
471			h = h[1:]
472		}
473		return fmt.Sprintf(`%s<a href="https://%s/o/%s">%s</a>`, p, serverName,
474			strings.ToLower(h[1:]), h)
475	})
476	return s
477}
478
479var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
480var re_urlhost = regexp.MustCompile("https://([^/ ]+)")
481
482func originate(u string) string {
483	m := re_urlhost.FindStringSubmatch(u)
484	if len(m) > 1 {
485		return m[1]
486	}
487	return ""
488}
489
490var allhandles = make(map[string]string)
491var handlelock sync.Mutex
492
493// handle, handle@host
494func handles(xid string) (string, string) {
495	if xid == "" {
496		return "", ""
497	}
498	handlelock.Lock()
499	handle := allhandles[xid]
500	handlelock.Unlock()
501	if handle == "" {
502		handle = findhandle(xid)
503		handlelock.Lock()
504		allhandles[xid] = handle
505		handlelock.Unlock()
506	}
507	if handle == xid {
508		return xid, xid
509	}
510	return handle, handle + "@" + originate(xid)
511}
512
513func findhandle(xid string) string {
514	row := stmtGetXonker.QueryRow(xid, "handle")
515	var handle string
516	err := row.Scan(&handle)
517	if err != nil {
518		info, _ := investigate(xid)
519		if info == nil {
520			m := re_unurl.FindStringSubmatch(xid)
521			if len(m) > 2 {
522				handle = m[2]
523			} else {
524				handle = xid
525			}
526		} else {
527			handle = info.Name
528		}
529		_, err = stmtSaveXonker.Exec(xid, handle, "handle")
530		if err != nil {
531			log.Printf("error saving handle: %s", err)
532		}
533	}
534	return handle
535}
536
537var handleprelock sync.Mutex
538
539func prehandle(xid string) {
540	handleprelock.Lock()
541	defer handleprelock.Unlock()
542	handles(xid)
543}
544
545func prepend(s string, x []string) []string {
546	return append([]string{s}, x...)
547}
548
549// pleroma leaks followers addressed posts to followers
550func butnottooloud(aud []string) {
551	for i, a := range aud {
552		if strings.HasSuffix(a, "/followers") {
553			aud[i] = ""
554		}
555	}
556}
557
558func keepitquiet(aud []string) bool {
559	for _, a := range aud {
560		if a == thewholeworld {
561			return false
562		}
563	}
564	return true
565}
566
567func firstclass(honk *Honk) bool {
568	return honk.Audience[0] == thewholeworld
569}
570
571func oneofakind(a []string) []string {
572	seen := make(map[string]bool)
573	seen[""] = true
574	j := 0
575	for _, s := range a {
576		if !seen[s] {
577			seen[s] = true
578			a[j] = s
579			j++
580		}
581	}
582	return a[:j]
583}
584
585var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
586	var user *WhatAbout
587	ok := somenumberedusers.Get(userid, &user)
588	if !ok {
589		return nil, false
590	}
591	ki := new(KeyInfo)
592	ki.keyname = user.URL + "#key"
593	ki.seckey = user.SecKey
594	return ki, true
595}})
596
597func ziggy(userid int64) *KeyInfo {
598	var ki *KeyInfo
599	ziggies.Get(userid, &ki)
600	return ki
601}
602
603var zaggies = make(map[string]*rsa.PublicKey)
604var zaggylock sync.Mutex
605
606func zaggy(keyname string) (key *rsa.PublicKey) {
607	zaggylock.Lock()
608	key = zaggies[keyname]
609	zaggylock.Unlock()
610	if key != nil {
611		return
612	}
613	row := stmtGetXonker.QueryRow(keyname, "pubkey")
614	var data string
615	err := row.Scan(&data)
616	if err != nil {
617		log.Printf("hitting the webs for missing pubkey: %s", keyname)
618		j, err := GetJunk(keyname)
619		if err != nil {
620			log.Printf("error getting %s pubkey: %s", keyname, err)
621			return
622		}
623		keyobj, ok := j.GetMap("publicKey")
624		if ok {
625			j = keyobj
626		}
627		data, ok = j.GetString("publicKeyPem")
628		if !ok {
629			log.Printf("error finding %s pubkey", keyname)
630			return
631		}
632		_, ok = j.GetString("owner")
633		if !ok {
634			log.Printf("error finding %s pubkey owner", keyname)
635			return
636		}
637		_, key, err = httpsig.DecodeKey(data)
638		if err != nil {
639			log.Printf("error decoding %s pubkey: %s", keyname, err)
640			return
641		}
642		_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
643		if err != nil {
644			log.Printf("error saving key: %s", err)
645		}
646	} else {
647		_, key, err = httpsig.DecodeKey(data)
648		if err != nil {
649			log.Printf("error decoding %s pubkey: %s", keyname, err)
650			return
651		}
652	}
653	zaggylock.Lock()
654	zaggies[keyname] = key
655	zaggylock.Unlock()
656	return
657}
658
659func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
660	_, err := stmtDeleteXonker.Exec(keyname, "pubkey")
661	if err != nil {
662		log.Printf("error deleting key: %s", err)
663	}
664	zaggylock.Lock()
665	delete(zaggies, keyname)
666	zaggylock.Unlock()
667	return httpsig.VerifyRequest(r, payload, zaggy)
668}
669
670func keymatch(keyname string, actor string) string {
671	hash := strings.IndexByte(keyname, '#')
672	if hash == -1 {
673		hash = len(keyname)
674	}
675	owner := keyname[0:hash]
676	if owner == actor {
677		return originate(actor)
678	}
679	return ""
680}