all repos — honk @ c13525c93a061b24597ceebdc928bd78702f8b97

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