all repos — honk @ 88213dafa812870950cd40d11b5fb7cd054cb976

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		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
197		emus = append(emus, Emu{ID: url, Name: e})
198	}
199	return emus
200}
201
202var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
203
204func memetize(honk *Honk) {
205	repl := func(x string) string {
206		name := x[5:]
207		if name[0] == ' ' {
208			name = name[1:]
209		}
210		fd, err := os.Open("memes/" + name)
211		if err != nil {
212			log.Printf("no meme for %s", name)
213			return x
214		}
215		var peek [512]byte
216		n, _ := fd.Read(peek[:])
217		ct := http.DetectContentType(peek[:n])
218		fd.Close()
219
220		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
221		res, err := stmtSaveFile.Exec("", name, url, ct, 0, "")
222		if err != nil {
223			log.Printf("error saving meme: %s", err)
224			return x
225		}
226		var d Donk
227		d.FileID, _ = res.LastInsertId()
228		d.XID = ""
229		d.Name = name
230		d.Media = ct
231		d.URL = url
232		d.Local = false
233		honk.Donks = append(honk.Donks, &d)
234		log.Printf("replace with -")
235		return ""
236	}
237	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
238}
239
240var re_bolder = regexp.MustCompile(`(^|\W)\*\*([\w\s,.!?'-]+)\*\*($|\W)`)
241var re_italicer = regexp.MustCompile(`(^|\W)\*([\w\s,.!?'-]+)\*($|\W)`)
242var re_bigcoder = regexp.MustCompile("```\n?((?s:.*?))\n?```\n?")
243var re_coder = regexp.MustCompile("`([^`]*)`")
244var re_quoter = regexp.MustCompile(`(?m:^&gt; (.*)\n?)`)
245
246func markitzero(s string) string {
247	var bigcodes []string
248	bigsaver := func(code string) string {
249		bigcodes = append(bigcodes, code)
250		return "``````"
251	}
252	s = re_bigcoder.ReplaceAllStringFunc(s, bigsaver)
253	var lilcodes []string
254	lilsaver := func(code string) string {
255		lilcodes = append(lilcodes, code)
256		return "`x`"
257	}
258	s = re_coder.ReplaceAllStringFunc(s, lilsaver)
259	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
260	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
261	s = re_quoter.ReplaceAllString(s, "<blockquote>$1</blockquote><p>")
262	lilun := func(s string) string {
263		code := lilcodes[0]
264		lilcodes = lilcodes[1:]
265		return code
266	}
267	s = re_coder.ReplaceAllStringFunc(s, lilun)
268	bigun := func(s string) string {
269		code := bigcodes[0]
270		bigcodes = bigcodes[1:]
271		return code
272	}
273	s = re_bigcoder.ReplaceAllStringFunc(s, bigun)
274	s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre><p>")
275	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
276	return s
277}
278
279func obfusbreak(s string) string {
280	s = strings.TrimSpace(s)
281	s = strings.Replace(s, "\r", "", -1)
282	s = html.EscapeString(s)
283	// dammit go
284	s = strings.Replace(s, "&#39;", "'", -1)
285	linkfn := func(url string) string {
286		if url[0] == '@' {
287			return url
288		}
289		addparen := false
290		adddot := false
291		if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
292			url = url[:len(url)-1]
293			addparen = true
294		}
295		if strings.HasSuffix(url, ".") {
296			url = url[:len(url)-1]
297			adddot = true
298		}
299		url = fmt.Sprintf(`<a class="mention" href="%s">%s</a>`, url, url)
300		if adddot {
301			url += "."
302		}
303		if addparen {
304			url += ")"
305		}
306		return url
307	}
308	s = re_link.ReplaceAllStringFunc(s, linkfn)
309
310	s = markitzero(s)
311
312	s = strings.Replace(s, "\n", "<br>", -1)
313	return s
314}
315
316func mentionize(s string) string {
317	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
318		where := gofish(m)
319		if where == "" {
320			return m
321		}
322		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
323		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
324			html.EscapeString(where), html.EscapeString(who))
325	})
326	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
327		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
328			html.EscapeString(m[1:]), html.EscapeString(m))
329	})
330	return s
331}
332
333var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
334var re_urlhost = regexp.MustCompile("https://([^/]+)")
335
336func originate(u string) string {
337	m := re_urlhost.FindStringSubmatch(u)
338	if len(m) > 1 {
339		return m[1]
340	}
341	return ""
342}
343
344func honkerhandle(h string) (string, string) {
345	m := re_unurl.FindStringSubmatch(h)
346	if len(m) > 2 {
347		return m[2], fmt.Sprintf("%s@%s", m[2], m[1])
348	}
349	return h, h
350}
351
352func prepend(s string, x []string) []string {
353	return append([]string{s}, x...)
354}
355
356// pleroma leaks followers addressed posts to followers
357func butnottooloud(aud []string) {
358	for i, a := range aud {
359		if strings.HasSuffix(a, "/followers") {
360			aud[i] = ""
361		}
362	}
363}
364
365func keepitquiet(aud []string) bool {
366	for _, a := range aud {
367		if a == thewholeworld {
368			return false
369		}
370	}
371	return true
372}
373
374func oneofakind(a []string) []string {
375	var x []string
376	for n, s := range a {
377		if s != "" {
378			x = append(x, s)
379			for i := n + 1; i < len(a); i++ {
380				if a[i] == s {
381					a[i] = ""
382				}
383			}
384		}
385	}
386	return x
387}
388
389var ziggies = make(map[string]*rsa.PrivateKey)
390var zaggies = make(map[string]*rsa.PublicKey)
391var ziggylock sync.Mutex
392
393func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
394	ziggylock.Lock()
395	key = ziggies[username]
396	ziggylock.Unlock()
397	if key == nil {
398		db := opendatabase()
399		row := db.QueryRow("select seckey from users where username = ?", username)
400		var data string
401		row.Scan(&data)
402		var err error
403		key, _, err = pez(data)
404		if err != nil {
405			log.Printf("error decoding %s seckey: %s", username, err)
406			return
407		}
408		ziggylock.Lock()
409		ziggies[username] = key
410		ziggylock.Unlock()
411	}
412	keyname = fmt.Sprintf("https://%s/u/%s#key", serverName, username)
413	return
414}
415
416func zaggy(keyname string) (key *rsa.PublicKey) {
417	ziggylock.Lock()
418	key = zaggies[keyname]
419	ziggylock.Unlock()
420	if key != nil {
421		return
422	}
423	row := stmtGetXonker.QueryRow(keyname, "pubkey")
424	var data string
425	err := row.Scan(&data)
426	if err != nil {
427		log.Printf("hitting the webs for missing pubkey: %s", keyname)
428		j, err := GetJunk(keyname)
429		if err != nil {
430			log.Printf("error getting %s pubkey: %s", keyname, err)
431			return
432		}
433		var ok bool
434		data, ok = j.FindString([]string{"publicKey", "publicKeyPem"})
435		if !ok {
436			log.Printf("error finding %s pubkey", keyname)
437			return
438		}
439		_, ok = j.FindString([]string{"publicKey", "owner"})
440		if !ok {
441			log.Printf("error finding %s pubkey owner", keyname)
442			return
443		}
444		_, key, err = pez(data)
445		if err != nil {
446			log.Printf("error decoding %s pubkey: %s", keyname, err)
447			return
448		}
449		_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
450		if err != nil {
451			log.Printf("error saving key: %s", err)
452		}
453	} else {
454		_, key, err = pez(data)
455		if err != nil {
456			log.Printf("error decoding %s pubkey: %s", keyname, err)
457			return
458		}
459	}
460	ziggylock.Lock()
461	zaggies[keyname] = key
462	ziggylock.Unlock()
463	return
464}
465
466func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
467	_, err := stmtDeleteXonker.Exec(keyname, "pubkey")
468	if err != nil {
469		log.Printf("error deleting key: %s", err)
470	}
471	ziggylock.Lock()
472	delete(zaggies, keyname)
473	ziggylock.Unlock()
474	return zag(r, payload)
475}
476
477var thumbbiters map[int64]map[string]bool
478var zordses map[int64][]*regexp.Regexp
479var thumblock sync.Mutex
480
481func bitethethumbs() {
482	rows, err := stmtThumbBiters.Query()
483	if err != nil {
484		log.Printf("error getting thumbbiters: %s", err)
485		return
486	}
487	defer rows.Close()
488
489	thumblock.Lock()
490	defer thumblock.Unlock()
491	thumbbiters = make(map[int64]map[string]bool)
492	zordses = make(map[int64][]*regexp.Regexp)
493	for rows.Next() {
494		var userid int64
495		var name, wherefore string
496		err = rows.Scan(&userid, &name, &wherefore)
497		if err != nil {
498			log.Printf("error scanning zonker: %s", err)
499			continue
500		}
501		if wherefore == "zord" {
502			zord := "\\b(?i:" + name + ")\\b"
503			re, err := regexp.Compile(zord)
504			if err != nil {
505				log.Printf("error compiling zord: %s", err)
506			} else {
507				zordses[userid] = append(zordses[userid], re)
508			}
509			continue
510		}
511		m := thumbbiters[userid]
512		if m == nil {
513			m = make(map[string]bool)
514			thumbbiters[userid] = m
515		}
516		m[name] = true
517	}
518}
519
520func getzords(userid int64) []*regexp.Regexp {
521	thumblock.Lock()
522	defer thumblock.Unlock()
523	return zordses[userid]
524}
525
526func thoudostbitethythumb(userid int64, who []string, objid string) bool {
527	thumblock.Lock()
528	biters := thumbbiters[userid]
529	thumblock.Unlock()
530	for _, w := range who {
531		if biters[w] {
532			return true
533		}
534		where := originate(w)
535		if where != "" {
536			if biters[where] {
537				return true
538			}
539		}
540	}
541	return false
542}
543
544func keymatch(keyname string, actor string) string {
545	hash := strings.IndexByte(keyname, '#')
546	if hash == -1 {
547		hash = len(keyname)
548	}
549	owner := keyname[0:hash]
550	if owner == actor {
551		return originate(actor)
552	}
553	return ""
554}