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