all repos — honk @ ebdc5482c7c0ec15bdadfcf5375c0ebd78bb3960

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