all repos — honk @ eb9d60e1996a0cc48e279b735d2e15bf68e194ef

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