all repos — honk @ e44896aaa4dbfea7659dffb88ae3748c40f4e10f

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