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