all repos — honk @ 56230d6be033aeb62232a4efbdda2d37a9eacf3f

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