all repos — honk @ cc242e7717d573a1e2798384cbe168818c4ec9d8

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