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