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