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