all repos — honk @ f75b4a2427a12311d530a24c3e705f09ae607eea

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