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