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