all repos — honk @ cdeb724ee0d9d92782a5f48000e8ef8e81af24fe

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