all repos — honk @ 2bb87a7cff4cd5c6fcae45f8cd40dfbd85bd456b

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?```")
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>")
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>")
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 honkerhandle(h string) string {
256	m := re_unurl.FindStringSubmatch(h)
257	if len(m) > 2 {
258		return fmt.Sprintf("%s@%s", m[2], m[1])
259	}
260	return h
261}
262
263func prepend(s string, x []string) []string {
264	return append([]string{s}, x...)
265}
266
267// pleroma leaks followers addressed posts to followers
268func butnottooloud(aud []string) {
269	for i, a := range aud {
270		if strings.HasSuffix(a, "/followers") {
271			aud[i] = ""
272		}
273	}
274}
275
276func oneofakind(a []string) []string {
277	var x []string
278	for n, s := range a {
279		if s != "" {
280			x = append(x, s)
281			for i := n + 1; i < len(a); i++ {
282				if a[i] == s {
283					a[i] = ""
284				}
285			}
286		}
287	}
288	return x
289}
290
291var ziggies = make(map[string]*rsa.PrivateKey)
292var zaggies = make(map[string]*rsa.PublicKey)
293var ziggylock sync.Mutex
294
295func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
296	ziggylock.Lock()
297	key = ziggies[username]
298	ziggylock.Unlock()
299	if key == nil {
300		db := opendatabase()
301		row := db.QueryRow("select seckey from users where username = ?", username)
302		var data string
303		row.Scan(&data)
304		var err error
305		key, _, err = pez(data)
306		if err != nil {
307			log.Printf("error decoding %s seckey: %s", username, err)
308			return
309		}
310		ziggylock.Lock()
311		ziggies[username] = key
312		ziggylock.Unlock()
313	}
314	keyname = fmt.Sprintf("https://%s/u/%s#key", serverName, username)
315	return
316}
317
318func zaggy(keyname string) (key *rsa.PublicKey) {
319	ziggylock.Lock()
320	key = zaggies[keyname]
321	ziggylock.Unlock()
322	if key != nil {
323		return
324	}
325	db := opendatabase()
326	row := db.QueryRow("select pubkey from xonkers where xid = ?", keyname)
327	var data string
328	err := row.Scan(&data)
329	if err != nil {
330		log.Printf("hitting the webs for missing pubkey: %s", keyname)
331		j, err := GetJunk(keyname)
332		if err != nil {
333			log.Printf("error getting %s pubkey: %s", keyname, err)
334			return
335		}
336		var ok bool
337		data, ok = jsonfindstring(j, []string{"publicKey", "publicKeyPem"})
338		if !ok {
339			log.Printf("error finding %s pubkey", keyname)
340			return
341		}
342		_, ok = jsonfindstring(j, []string{"publicKey", "owner"})
343		if !ok {
344			log.Printf("error finding %s pubkey owner", keyname)
345			return
346		}
347		_, key, err = pez(data)
348		if err != nil {
349			log.Printf("error decoding %s pubkey: %s", keyname, err)
350			return
351		}
352		_, err = stmtSaveBoxes.Exec(keyname, "", "", "", data)
353		if err != nil {
354			log.Printf("error saving key: %s", err)
355		}
356	} else {
357		_, key, err = pez(data)
358		if err != nil {
359			log.Printf("error decoding %s pubkey: %s", keyname, err)
360			return
361		}
362	}
363	ziggylock.Lock()
364	zaggies[keyname] = key
365	ziggylock.Unlock()
366	return
367}
368
369func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
370	db := opendatabase()
371	_, err := db.Exec("delete from xonkers where xid = ?", keyname)
372	if err != nil {
373		log.Printf("error deleting key: %s", err)
374	}
375	ziggylock.Lock()
376	delete(zaggies, keyname)
377	ziggylock.Unlock()
378	return zag(r, payload)
379}
380
381var thumbbiters map[int64]map[string]bool
382var thumblock sync.Mutex
383
384func bitethethumbs() {
385	rows, err := stmtThumbBiters.Query()
386	if err != nil {
387		log.Printf("error getting thumbbiters: %s", err)
388		return
389	}
390	defer rows.Close()
391	thumblock.Lock()
392	defer thumblock.Unlock()
393	thumbbiters = make(map[int64]map[string]bool)
394	for rows.Next() {
395		var userid int64
396		var name, wherefore string
397		err = rows.Scan(&userid, &name, &wherefore)
398		if err != nil {
399			log.Printf("error scanning zonker: %s", err)
400			continue
401		}
402		m := thumbbiters[userid]
403		if m == nil {
404			m = make(map[string]bool)
405			thumbbiters[userid] = m
406		}
407		m[name] = true
408	}
409}
410
411func thoudostbitethythumb(userid int64, who []string, objid string) bool {
412	thumblock.Lock()
413	biters := thumbbiters[userid]
414	thumblock.Unlock()
415	for _, w := range who {
416		if biters[w] {
417			return true
418		}
419		m := re_unurl.FindStringSubmatch(w)
420		if len(m) > 2 {
421			where := m[1]
422			if biters[where] {
423				return true
424			}
425		}
426	}
427	return false
428}
429
430func keymatch(keyname string, actor string, what string, userid int64) bool {
431	hash := strings.IndexByte(keyname, '#')
432	if hash == -1 {
433		hash = len(keyname)
434	}
435	owner := keyname[0:hash]
436	if owner == actor {
437		return true
438	}
439	return false
440}