all repos — honk @ 82ecaf2fcf586e7ec899dd0e6d272e17249ed573

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