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