all repos — honk @ 4c4664c32a17bf5240a7440321e2b5bb0445dd93

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