all repos — honk @ 683d6da2fd61c7acecbf040421275464c1fc7858

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