all repos — honk @ 3b1d58b0ab3b08c4fff18282d082c6117c04e355

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