all repos — honk @ d0c3466096be24942914dd6fdc502bb360ce633e

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