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