all repos — honk @ 0dec695e683f3cd0e9a7d4d459f91ecec2fd87d9

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