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