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