all repos — honk @ eaceb0995f874d48c43fcb0fe0bdb3d54a63cd89

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"
 23	"html/template"
 24	"log"
 25	"net/http"
 26	"os"
 27	"regexp"
 28	"strings"
 29	"sync"
 30
 31	"humungus.tedunangst.com/r/webs/htfilter"
 32	"humungus.tedunangst.com/r/webs/httpsig"
 33)
 34
 35func reverbolate(userid int64, honks []*Honk) {
 36	filt := htfilter.New()
 37	zilences := getzilences(userid)
 38	for _, h := range honks {
 39		h.What += "ed"
 40		if h.What == "tonked" {
 41			h.What = "honked back"
 42			h.Style = "subtle"
 43		}
 44		if !h.Public {
 45			h.Style += " limited"
 46		}
 47		if h.Whofore == 2 || h.Whofore == 3 {
 48			h.URL = h.XID
 49			if h.What != "bonked" {
 50				h.Noise = mentionize(h.Noise)
 51				h.Noise = ontologize(h.Noise)
 52			} else {
 53				h.Flags |= flagIsBonked
 54			}
 55			h.Username, h.Handle = handles(h.Honker)
 56		} else {
 57			_, h.Handle = handles(h.Honker)
 58			h.Username = h.Handle
 59			if len(h.Username) > 20 {
 60				h.Username = h.Username[:20] + ".."
 61			}
 62			if h.URL == "" {
 63				h.URL = h.XID
 64			}
 65		}
 66		if h.Oonker != "" {
 67			_, h.Oondle = handles(h.Oonker)
 68		}
 69		zap := make(map[*Donk]bool)
 70		h.Noise = unpucker(h.Noise)
 71		h.Open = "open"
 72		if badword := unsee(zilences, h.Precis, h.Noise); badword != "" {
 73			if h.Precis == "" {
 74				h.Precis = badword
 75			}
 76			h.Open = ""
 77		} else if h.Precis == "unspecified horror" {
 78			h.Precis = ""
 79		}
 80		h.Precis = unpucker(h.Precis)
 81		h.HTML, _ = filt.String(h.Noise)
 82		emuxifier := func(e string) string {
 83			for _, d := range h.Donks {
 84				if d.Name == e {
 85					zap[d] = true
 86					if d.Local {
 87						return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
 88					}
 89				}
 90			}
 91			return e
 92		}
 93		h.HTML = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTML), emuxifier))
 94		j := 0
 95		for i := 0; i < len(h.Donks); i++ {
 96			if !zap[h.Donks[i]] {
 97				h.Donks[j] = h.Donks[i]
 98				j++
 99			}
100		}
101		h.Donks = h.Donks[:j]
102	}
103}
104
105func unsee(zilences []*regexp.Regexp, precis string, noise string) string {
106	for _, z := range zilences {
107		if z.MatchString(precis) || z.MatchString(noise) {
108			if precis == "" {
109				w := z.String()
110				return w[6 : len(w)-3]
111			}
112			return precis
113		}
114	}
115	return ""
116}
117
118func osmosis(honks []*Honk, userid int64) []*Honk {
119	zords := getzords(userid)
120	j := 0
121outer:
122	for _, h := range honks {
123		for _, z := range zords {
124			if z.MatchString(h.Precis) || z.MatchString(h.Noise) {
125				continue outer
126			}
127		}
128		honks[j] = h
129		j++
130	}
131	honks = honks[0:j]
132	return honks
133}
134
135func shortxid(xid string) string {
136	idx := strings.LastIndexByte(xid, '/')
137	if idx == -1 {
138		return xid
139	}
140	return xid[idx+1:]
141}
142
143func xfiltrate() string {
144	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
145	var b [18]byte
146	rand.Read(b[:])
147	for i, c := range b {
148		b[i] = letters[c&63]
149	}
150	s := string(b[:])
151	return s
152}
153
154var re_hashes = regexp.MustCompile(`(?:^| )#[[:alpha:]][[:alnum:]-]*`)
155
156func ontologies(s string) []string {
157	m := re_hashes.FindAllString(s, -1)
158	j := 0
159	for _, h := range m {
160		if h[0] == '&' {
161			continue
162		}
163		if h[0] != '#' {
164			h = h[1:]
165		}
166		m[j] = h
167		j++
168	}
169	return m[:j]
170}
171
172type Mention struct {
173	who   string
174	where string
175}
176
177var re_mentions = regexp.MustCompile(`@[[:alnum:]._-]+@[[:alnum:].-]*[[:alnum:]]`)
178var re_urltions = regexp.MustCompile(`@https://\S+`)
179
180func grapevine(s string) []string {
181	var mentions []string
182	m := re_mentions.FindAllString(s, -1)
183	for i := range m {
184		where := gofish(m[i])
185		if where != "" {
186			mentions = append(mentions, where)
187		}
188	}
189	m = re_urltions.FindAllString(s, -1)
190	for i := range m {
191		mentions = append(mentions, m[i][1:])
192	}
193	return mentions
194}
195
196func bunchofgrapes(s string) []Mention {
197	m := re_mentions.FindAllString(s, -1)
198	var mentions []Mention
199	for i := range m {
200		where := gofish(m[i])
201		if where != "" {
202			mentions = append(mentions, Mention{who: m[i], where: where})
203		}
204	}
205	m = re_urltions.FindAllString(s, -1)
206	for i := range m {
207		mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
208	}
209	return mentions
210}
211
212type Emu struct {
213	ID   string
214	Name string
215}
216
217var re_link = regexp.MustCompile(`@?https?://[^\s"]+[\w/)]`)
218var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
219
220func herdofemus(noise string) []Emu {
221	m := re_emus.FindAllString(noise, -1)
222	m = oneofakind(m)
223	var emus []Emu
224	for _, e := range m {
225		fname := e[1 : len(e)-1]
226		_, err := os.Stat("emus/" + fname + ".png")
227		if err != nil {
228			continue
229		}
230		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
231		emus = append(emus, Emu{ID: url, Name: e})
232	}
233	return emus
234}
235
236var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
237
238func memetize(honk *Honk) {
239	repl := func(x string) string {
240		name := x[5:]
241		if name[0] == ' ' {
242			name = name[1:]
243		}
244		fd, err := os.Open("memes/" + name)
245		if err != nil {
246			log.Printf("no meme for %s", name)
247			return x
248		}
249		var peek [512]byte
250		n, _ := fd.Read(peek[:])
251		ct := http.DetectContentType(peek[:n])
252		fd.Close()
253
254		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
255		res, err := stmtSaveFile.Exec("", name, url, ct, 0, "")
256		if err != nil {
257			log.Printf("error saving meme: %s", err)
258			return x
259		}
260		var d Donk
261		d.FileID, _ = res.LastInsertId()
262		d.XID = ""
263		d.Name = name
264		d.Media = ct
265		d.URL = url
266		d.Local = false
267		honk.Donks = append(honk.Donks, &d)
268		return ""
269	}
270	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
271}
272
273var re_bolder = regexp.MustCompile(`(^|\W)\*\*([\w\s,.!?'-]+)\*\*($|\W)`)
274var re_italicer = regexp.MustCompile(`(^|\W)\*([\w\s,.!?'-]+)\*($|\W)`)
275var re_bigcoder = regexp.MustCompile("```\n?((?s:.*?))\n?```\n?")
276var re_coder = regexp.MustCompile("`([^`]*)`")
277var re_quoter = regexp.MustCompile(`(?m:^&gt; (.*)\n?)`)
278
279func markitzero(s string) string {
280	var bigcodes []string
281	bigsaver := func(code string) string {
282		bigcodes = append(bigcodes, code)
283		return "``````"
284	}
285	s = re_bigcoder.ReplaceAllStringFunc(s, bigsaver)
286	var lilcodes []string
287	lilsaver := func(code string) string {
288		lilcodes = append(lilcodes, code)
289		return "`x`"
290	}
291	s = re_coder.ReplaceAllStringFunc(s, lilsaver)
292	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
293	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
294	s = re_quoter.ReplaceAllString(s, "<blockquote>$1</blockquote><p>")
295	lilun := func(s string) string {
296		code := lilcodes[0]
297		lilcodes = lilcodes[1:]
298		return code
299	}
300	s = re_coder.ReplaceAllStringFunc(s, lilun)
301	bigun := func(s string) string {
302		code := bigcodes[0]
303		bigcodes = bigcodes[1:]
304		return code
305	}
306	s = re_bigcoder.ReplaceAllStringFunc(s, bigun)
307	s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre><p>")
308	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
309	return s
310}
311
312func obfusbreak(s string) string {
313	s = strings.TrimSpace(s)
314	s = strings.Replace(s, "\r", "", -1)
315	s = html.EscapeString(s)
316	// dammit go
317	s = strings.Replace(s, "&#39;", "'", -1)
318	linkfn := func(url string) string {
319		if url[0] == '@' {
320			return url
321		}
322		addparen := false
323		adddot := false
324		if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
325			url = url[:len(url)-1]
326			addparen = true
327		}
328		if strings.HasSuffix(url, ".") {
329			url = url[:len(url)-1]
330			adddot = true
331		}
332		url = fmt.Sprintf(`<a class="mention u-url" href="%s">%s</a>`, url, url)
333		if adddot {
334			url += "."
335		}
336		if addparen {
337			url += ")"
338		}
339		return url
340	}
341	s = re_link.ReplaceAllStringFunc(s, linkfn)
342
343	s = markitzero(s)
344
345	s = strings.Replace(s, "\n", "<br>", -1)
346	return s
347}
348
349var re_quickmention = regexp.MustCompile("(^| )@[[:alnum:]]+ ")
350
351func quickrename(s string, userid int64) string {
352	return re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
353		prefix := ""
354		if m[0] == ' ' {
355			prefix = " "
356			m = m[1:]
357		}
358		prefix += "@"
359		m = m[1:]
360		m = m[:len(m)-1]
361
362		row := stmtOneHonker.QueryRow(m, userid)
363		var xid string
364		err := row.Scan(&xid)
365		if err == nil {
366			_, name := handles(xid)
367			if name != "" {
368				m = name
369			}
370		}
371		return prefix + m + " "
372	})
373}
374
375func mentionize(s string) string {
376	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
377		where := gofish(m)
378		if where == "" {
379			return m
380		}
381		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
382		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
383			html.EscapeString(where), html.EscapeString(who))
384	})
385	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
386		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
387			html.EscapeString(m[1:]), html.EscapeString(m))
388	})
389	return s
390}
391
392func ontologize(s string) string {
393	s = re_hashes.ReplaceAllStringFunc(s, func(o string) string {
394		if o[0] == '&' {
395			return o
396		}
397		p := ""
398		h := o
399		if h[0] != '#' {
400			p = h[:1]
401			h = h[1:]
402		}
403		return fmt.Sprintf(`%s<a class="mention u-url" href="https://%s/o/%s">%s</a>`, p, serverName,
404			strings.ToLower(h[1:]), h)
405	})
406	return s
407}
408
409var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
410var re_urlhost = regexp.MustCompile("https://([^/]+)")
411
412func originate(u string) string {
413	m := re_urlhost.FindStringSubmatch(u)
414	if len(m) > 1 {
415		return m[1]
416	}
417	return ""
418}
419
420var allhandles = make(map[string]string)
421var handlelock sync.Mutex
422
423// handle, handle@host
424func handles(xid string) (string, string) {
425	if xid == "" {
426		return "", ""
427	}
428	handlelock.Lock()
429	handle := allhandles[xid]
430	handlelock.Unlock()
431	if handle == "" {
432		handle = findhandle(xid)
433		handlelock.Lock()
434		allhandles[xid] = handle
435		handlelock.Unlock()
436	}
437	if handle == xid {
438		return xid, xid
439	}
440	return handle, handle + "@" + originate(xid)
441}
442
443func findhandle(xid string) string {
444	row := stmtGetXonker.QueryRow(xid, "handle")
445	var handle string
446	err := row.Scan(&handle)
447	if err != nil {
448		p, _ := investigate(xid)
449		if p == nil {
450			m := re_unurl.FindStringSubmatch(xid)
451			if len(m) > 2 {
452				handle = m[2]
453			} else {
454				handle = xid
455			}
456		} else {
457			handle = p.Handle
458		}
459		_, err = stmtSaveXonker.Exec(xid, handle, "handle")
460		if err != nil {
461			log.Printf("error saving handle: %s", err)
462		}
463	}
464	return handle
465}
466
467var handleprelock sync.Mutex
468
469func prehandle(xid string) {
470	handleprelock.Lock()
471	defer handleprelock.Unlock()
472	handles(xid)
473}
474
475func prepend(s string, x []string) []string {
476	return append([]string{s}, x...)
477}
478
479// pleroma leaks followers addressed posts to followers
480func butnottooloud(aud []string) {
481	for i, a := range aud {
482		if strings.HasSuffix(a, "/followers") {
483			aud[i] = ""
484		}
485	}
486}
487
488func keepitquiet(aud []string) bool {
489	for _, a := range aud {
490		if a == thewholeworld {
491			return false
492		}
493	}
494	return true
495}
496
497func firstclass(honk *Honk) bool {
498	return honk.Audience[0] == thewholeworld
499}
500
501func oneofakind(a []string) []string {
502	var x []string
503	for n, s := range a {
504		if s != "" {
505			x = append(x, s)
506			for i := n + 1; i < len(a); i++ {
507				if a[i] == s {
508					a[i] = ""
509				}
510			}
511		}
512	}
513	return x
514}
515
516var ziggies = make(map[string]*rsa.PrivateKey)
517var zaggies = make(map[string]*rsa.PublicKey)
518var ziggylock sync.Mutex
519
520func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
521	ziggylock.Lock()
522	key = ziggies[username]
523	ziggylock.Unlock()
524	if key == nil {
525		db := opendatabase()
526		row := db.QueryRow("select seckey from users where username = ?", username)
527		var data string
528		row.Scan(&data)
529		var err error
530		key, _, err = httpsig.DecodeKey(data)
531		if err != nil {
532			log.Printf("error decoding %s seckey: %s", username, err)
533			return
534		}
535		ziggylock.Lock()
536		ziggies[username] = key
537		ziggylock.Unlock()
538	}
539	keyname = fmt.Sprintf("https://%s/%s/%s#key", serverName, userSep, username)
540	return
541}
542
543func zaggy(keyname string) (key *rsa.PublicKey) {
544	ziggylock.Lock()
545	key = zaggies[keyname]
546	ziggylock.Unlock()
547	if key != nil {
548		return
549	}
550	row := stmtGetXonker.QueryRow(keyname, "pubkey")
551	var data string
552	err := row.Scan(&data)
553	if err != nil {
554		log.Printf("hitting the webs for missing pubkey: %s", keyname)
555		j, err := GetJunk(keyname)
556		if err != nil {
557			log.Printf("error getting %s pubkey: %s", keyname, err)
558			return
559		}
560		keyobj, ok := j.GetMap("publicKey")
561		if ok {
562			j = keyobj
563		}
564		data, ok = j.GetString("publicKeyPem")
565		if !ok {
566			log.Printf("error finding %s pubkey", keyname)
567			return
568		}
569		_, ok = j.GetString("owner")
570		if !ok {
571			log.Printf("error finding %s pubkey owner", keyname)
572			return
573		}
574		_, key, err = httpsig.DecodeKey(data)
575		if err != nil {
576			log.Printf("error decoding %s pubkey: %s", keyname, err)
577			return
578		}
579		_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
580		if err != nil {
581			log.Printf("error saving key: %s", err)
582		}
583	} else {
584		_, key, err = httpsig.DecodeKey(data)
585		if err != nil {
586			log.Printf("error decoding %s pubkey: %s", keyname, err)
587			return
588		}
589	}
590	ziggylock.Lock()
591	zaggies[keyname] = key
592	ziggylock.Unlock()
593	return
594}
595
596func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
597	_, err := stmtDeleteXonker.Exec(keyname, "pubkey")
598	if err != nil {
599		log.Printf("error deleting key: %s", err)
600	}
601	ziggylock.Lock()
602	delete(zaggies, keyname)
603	ziggylock.Unlock()
604	return httpsig.VerifyRequest(r, payload, zaggy)
605}
606
607var thumbbiters map[int64]map[string]bool
608var zordses map[int64][]*regexp.Regexp
609var zilences map[int64][]*regexp.Regexp
610var thumblock sync.Mutex
611
612func bitethethumbs() {
613	rows, err := stmtThumbBiters.Query()
614	if err != nil {
615		log.Printf("error getting thumbbiters: %s", err)
616		return
617	}
618	defer rows.Close()
619
620	thumblock.Lock()
621	defer thumblock.Unlock()
622	thumbbiters = make(map[int64]map[string]bool)
623	zordses = make(map[int64][]*regexp.Regexp)
624	zilences = make(map[int64][]*regexp.Regexp)
625	for rows.Next() {
626		var userid int64
627		var name, wherefore string
628		err = rows.Scan(&userid, &name, &wherefore)
629		if err != nil {
630			log.Printf("error scanning zonker: %s", err)
631			continue
632		}
633		if wherefore == "zord" || wherefore == "zilence" {
634			zord := "\\b(?i:" + name + ")\\b"
635			re, err := regexp.Compile(zord)
636			if err != nil {
637				log.Printf("error compiling zord: %s", err)
638			} else {
639				if wherefore == "zord" {
640					zordses[userid] = append(zordses[userid], re)
641				} else {
642					zilences[userid] = append(zilences[userid], re)
643				}
644			}
645			continue
646		}
647		m := thumbbiters[userid]
648		if m == nil {
649			m = make(map[string]bool)
650			thumbbiters[userid] = m
651		}
652		m[name] = true
653	}
654}
655
656func getzords(userid int64) []*regexp.Regexp {
657	thumblock.Lock()
658	defer thumblock.Unlock()
659	return zordses[userid]
660}
661
662func getzilences(userid int64) []*regexp.Regexp {
663	thumblock.Lock()
664	defer thumblock.Unlock()
665	return zilences[userid]
666}
667
668func thoudostbitethythumb(userid int64, who []string, objid string) bool {
669	thumblock.Lock()
670	biters := thumbbiters[userid]
671	thumblock.Unlock()
672	objwhere := originate(objid)
673	if objwhere != "" && biters[objwhere] {
674		log.Printf("thumbbiter: %s", objid)
675		return true
676	}
677	for _, w := range who {
678		if biters[w] {
679			log.Printf("thumbbiter: %s", w)
680			return true
681		}
682		where := originate(w)
683		if where != "" {
684			if biters[where] {
685				log.Printf("thumbbiter: %s", w)
686				return true
687			}
688		}
689	}
690	return false
691}
692
693func keymatch(keyname string, actor string) string {
694	hash := strings.IndexByte(keyname, '#')
695	if hash == -1 {
696		hash = len(keyname)
697	}
698	owner := keyname[0:hash]
699	if owner == actor {
700		return originate(actor)
701	}
702	return ""
703}