all repos — honk @ 785d9cec00c28561f6636f17f194b7e29584e1bf

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		_, err = stmtSaveBoxes.Exec(keyname, "", "", "", data)
311		if err != nil {
312			log.Printf("error saving key: %s", err)
313		}
314	} else {
315		_, key, err = pez(data)
316		if err != nil {
317			log.Printf("error decoding %s pubkey: %s", keyname, err)
318			return
319		}
320	}
321	ziggylock.Lock()
322	zaggies[keyname] = key
323	ziggylock.Unlock()
324	return
325}
326
327func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
328	db := opendatabase()
329	_, err := db.Exec("delete from xonkers where xid = ?", keyname)
330	if err != nil {
331		log.Printf("error deleting key: %s", err)
332	}
333	ziggylock.Lock()
334	delete(zaggies, keyname)
335	ziggylock.Unlock()
336	return zag(r, payload)
337}
338
339var thumbbiters map[int64]map[string]bool
340var thumblock sync.Mutex
341
342func bitethethumbs() {
343	rows, err := stmtThumbBiters.Query()
344	if err != nil {
345		log.Printf("error getting thumbbiters: %s", err)
346		return
347	}
348	defer rows.Close()
349	thumblock.Lock()
350	defer thumblock.Unlock()
351	thumbbiters = make(map[int64]map[string]bool)
352	for rows.Next() {
353		var userid int64
354		var name, wherefore string
355		err = rows.Scan(&userid, &name, &wherefore)
356		if err != nil {
357			log.Printf("error scanning zonker: %s", err)
358			continue
359		}
360		m := thumbbiters[userid]
361		if m == nil {
362			m = make(map[string]bool)
363			thumbbiters[userid] = m
364		}
365		m[name] = true
366	}
367}
368
369func thoudostbitethythumb(userid int64, who []string, objid string) bool {
370	thumblock.Lock()
371	biters := thumbbiters[userid]
372	thumblock.Unlock()
373	for _, w := range who {
374		if biters[w] {
375			return true
376		}
377		m := re_unurl.FindStringSubmatch(w)
378		if len(m) > 2 {
379			where := m[1]
380			if biters[where] {
381				return true
382			}
383		}
384	}
385	return false
386}
387
388func keymatch(keyname string, actor string, what string, userid int64) bool {
389	hash := strings.IndexByte(keyname, '#')
390	if hash == -1 {
391		hash = len(keyname)
392	}
393	owner := keyname[0:hash]
394	if owner == actor {
395		return true
396	}
397	if what != "Create" {
398		return false
399	}
400	row := stmtHasHonker.QueryRow(owner, userid)
401	var id int64
402	err := row.Scan(&id)
403	if err == nil {
404		log.Printf("allowing resigned content by %s", keyname)
405		return true
406	}
407	return false
408}