all repos — honk @ e86a497081d41ff952ffcbd6527761d27e21b0b2

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