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