all repos — honk @ 9ecbd57f09a044972ef5ee5772d5df1808343171

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("`([^`]*)`")
164
165func markitzero(s string) string {
166	var bigcodes []string
167	bigsaver := func(code string) string {
168		bigcodes = append(bigcodes, code)
169		return "``````"
170	}
171	s = re_bigcoder.ReplaceAllStringFunc(s, bigsaver)
172	var lilcodes []string
173	lilsaver := func(code string) string {
174		lilcodes = append(lilcodes, code)
175		return "`x`"
176	}
177	s = re_coder.ReplaceAllStringFunc(s, lilsaver)
178	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
179	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
180	lilun := func(s string) string {
181		code := lilcodes[0]
182		lilcodes = lilcodes[1:]
183		return code
184	}
185	s = re_coder.ReplaceAllStringFunc(s, lilun)
186	bigun := func(s string) string {
187		code := bigcodes[0]
188		bigcodes = bigcodes[1:]
189		return code
190	}
191	s = re_bigcoder.ReplaceAllStringFunc(s, bigun)
192	s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre>")
193	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
194	return s
195}
196
197func obfusbreak(s string) string {
198	s = strings.TrimSpace(s)
199	s = strings.Replace(s, "\r", "", -1)
200	s = html.EscapeString(s)
201	// dammit go
202	s = strings.Replace(s, "&#39;", "'", -1)
203	linkfn := func(url string) string {
204		if url[0] == '@' {
205			return url
206		}
207		addparen := false
208		adddot := false
209		if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
210			url = url[:len(url)-1]
211			addparen = true
212		}
213		if strings.HasSuffix(url, ".") {
214			url = url[:len(url)-1]
215			adddot = true
216		}
217		url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
218		if adddot {
219			url += "."
220		}
221		if addparen {
222			url += ")"
223		}
224		return url
225	}
226	s = re_link.ReplaceAllStringFunc(s, linkfn)
227
228	s = markitzero(s)
229
230	s = strings.Replace(s, "\n", "<br>", -1)
231	return s
232}
233
234func mentionize(s string) string {
235	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
236		where := gofish(m)
237		if where == "" {
238			return m
239		}
240		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
241		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
242			html.EscapeString(where), html.EscapeString(who))
243	})
244	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
245		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
246			html.EscapeString(m[1:]), html.EscapeString(m))
247	})
248	return s
249}
250
251var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
252
253func honkerhandle(h string) string {
254	m := re_unurl.FindStringSubmatch(h)
255	if len(m) > 2 {
256		return fmt.Sprintf("%s@%s", m[2], m[1])
257	}
258	return h
259}
260
261func prepend(s string, x []string) []string {
262	return append([]string{s}, x...)
263}
264
265// pleroma leaks followers addressed posts to followers
266func butnottooloud(aud []string) {
267	for i, a := range aud {
268		if strings.HasSuffix(a, "/followers") {
269			aud[i] = ""
270		}
271	}
272}
273
274func oneofakind(a []string) []string {
275	var x []string
276	for n, s := range a {
277		if s != "" {
278			x = append(x, s)
279			for i := n + 1; i < len(a); i++ {
280				if a[i] == s {
281					a[i] = ""
282				}
283			}
284		}
285	}
286	return x
287}
288
289var ziggies = make(map[string]*rsa.PrivateKey)
290var zaggies = make(map[string]*rsa.PublicKey)
291var ziggylock sync.Mutex
292
293func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
294	ziggylock.Lock()
295	key = ziggies[username]
296	ziggylock.Unlock()
297	if key == nil {
298		db := opendatabase()
299		row := db.QueryRow("select seckey from users where username = ?", username)
300		var data string
301		row.Scan(&data)
302		var err error
303		key, _, err = pez(data)
304		if err != nil {
305			log.Printf("error decoding %s seckey: %s", username, err)
306			return
307		}
308		ziggylock.Lock()
309		ziggies[username] = key
310		ziggylock.Unlock()
311	}
312	keyname = fmt.Sprintf("https://%s/u/%s#key", serverName, username)
313	return
314}
315
316func zaggy(keyname string) (key *rsa.PublicKey) {
317	ziggylock.Lock()
318	key = zaggies[keyname]
319	ziggylock.Unlock()
320	if key != nil {
321		return
322	}
323	db := opendatabase()
324	row := db.QueryRow("select pubkey from xonkers where xid = ?", keyname)
325	var data string
326	err := row.Scan(&data)
327	if err != nil {
328		log.Printf("hitting the webs for missing pubkey: %s", keyname)
329		j, err := GetJunk(keyname)
330		if err != nil {
331			log.Printf("error getting %s pubkey: %s", keyname, err)
332			return
333		}
334		var ok bool
335		data, ok = jsonfindstring(j, []string{"publicKey", "publicKeyPem"})
336		if !ok {
337			log.Printf("error finding %s pubkey", keyname)
338			return
339		}
340		_, ok = jsonfindstring(j, []string{"publicKey", "owner"})
341		if !ok {
342			log.Printf("error finding %s pubkey owner", keyname)
343			return
344		}
345		_, key, err = pez(data)
346		if err != nil {
347			log.Printf("error decoding %s pubkey: %s", keyname, err)
348			return
349		}
350		_, err = stmtSaveBoxes.Exec(keyname, "", "", "", data)
351		if err != nil {
352			log.Printf("error saving key: %s", err)
353		}
354	} else {
355		_, key, err = pez(data)
356		if err != nil {
357			log.Printf("error decoding %s pubkey: %s", keyname, err)
358			return
359		}
360	}
361	ziggylock.Lock()
362	zaggies[keyname] = key
363	ziggylock.Unlock()
364	return
365}
366
367func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
368	db := opendatabase()
369	_, err := db.Exec("delete from xonkers where xid = ?", keyname)
370	if err != nil {
371		log.Printf("error deleting key: %s", err)
372	}
373	ziggylock.Lock()
374	delete(zaggies, keyname)
375	ziggylock.Unlock()
376	return zag(r, payload)
377}
378
379var thumbbiters map[int64]map[string]bool
380var thumblock sync.Mutex
381
382func bitethethumbs() {
383	rows, err := stmtThumbBiters.Query()
384	if err != nil {
385		log.Printf("error getting thumbbiters: %s", err)
386		return
387	}
388	defer rows.Close()
389	thumblock.Lock()
390	defer thumblock.Unlock()
391	thumbbiters = make(map[int64]map[string]bool)
392	for rows.Next() {
393		var userid int64
394		var name, wherefore string
395		err = rows.Scan(&userid, &name, &wherefore)
396		if err != nil {
397			log.Printf("error scanning zonker: %s", err)
398			continue
399		}
400		m := thumbbiters[userid]
401		if m == nil {
402			m = make(map[string]bool)
403			thumbbiters[userid] = m
404		}
405		m[name] = true
406	}
407}
408
409func thoudostbitethythumb(userid int64, who []string, objid string) bool {
410	thumblock.Lock()
411	biters := thumbbiters[userid]
412	thumblock.Unlock()
413	for _, w := range who {
414		if biters[w] {
415			return true
416		}
417		m := re_unurl.FindStringSubmatch(w)
418		if len(m) > 2 {
419			where := m[1]
420			if biters[where] {
421				return true
422			}
423		}
424	}
425	return false
426}
427
428func keymatch(keyname string, actor string, what string, userid int64) bool {
429	hash := strings.IndexByte(keyname, '#')
430	if hash == -1 {
431		hash = len(keyname)
432	}
433	owner := keyname[0:hash]
434	if owner == actor {
435		return true
436	}
437	return false
438}