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