all repos — honk @ b3baae70a8ac76202a5e391a1359536b0dc94dab

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		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 = httpsig.DecodeKey(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 = httpsig.DecodeKey(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 = httpsig.DecodeKey(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 httpsig.VerifyRequest(r, payload, zaggy)
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}