all repos — honk @ 2816bb2db70efac2361b547a426b4efec7c804ea

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