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