all repos — honk @ ed39930ffa00f8e100cc6bebab578c03b34e58d6

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