all repos — honk @ 523738fd4c85ae005137c36394bb55cf656ab315

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