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 if develMode {
436 url = fmt.Sprintf("/emu/%s%s", fname, ext)
437 }
438 return Emu{ID: url, Name: ename, Type: "image/" + ext[1:]}, true
439 }
440 return Emu{Name: ename, ID: "", Type: "image/png"}, true
441}, Duration: 10 * time.Second})
442
443func herdofemus(noise string) []Emu {
444 m := re_emus.FindAllString(noise, -1)
445 m = oneofakind(m)
446 var emus []Emu
447 for _, e := range m {
448 var emu Emu
449 emucache.Get(e, &emu)
450 if emu.ID == "" {
451 continue
452 }
453 emus = append(emus, emu)
454 }
455 return emus
456}
457
458var re_memes = regexp.MustCompile("meme: ?([^\n]+)")
459var re_avatar = regexp.MustCompile("avatar: ?([^\n]+)")
460var re_banner = regexp.MustCompile("banner: ?([^\n]+)")
461var re_convoy = regexp.MustCompile("convoy: ?([^\n]+)")
462var re_retag = regexp.MustCompile("tags: ?([^\n]+)")
463var re_convalidate = regexp.MustCompile("^(https?|tag|data):")
464
465func memetize(honk *Honk) {
466 repl := func(x string) string {
467 name := x[5:]
468 if name[0] == ' ' {
469 name = name[1:]
470 }
471 fd, err := os.Open(dataDir + "/memes/" + name)
472 if err != nil {
473 ilog.Printf("no meme for %s", name)
474 return x
475 }
476 var peek [512]byte
477 n, _ := fd.Read(peek[:])
478 ct := http.DetectContentType(peek[:n])
479 fd.Close()
480
481 url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
482 fileid, err := savefile(name, name, url, ct, false, nil)
483 if err != nil {
484 elog.Printf("error saving meme: %s", err)
485 return x
486 }
487 d := &Donk{
488 FileID: fileid,
489 Name: name,
490 Media: ct,
491 URL: url,
492 Local: false,
493 }
494 honk.Donks = append(honk.Donks, d)
495 return ""
496 }
497 honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
498}
499
500func recategorize(honk *Honk) {
501 repl := func(x string) string {
502 x = x[5:]
503 for _, t := range strings.Split(x, " ") {
504 if t == "" {
505 continue
506 }
507 if t[0] != '#' {
508 t = "#" + t
509 }
510 dlog.Printf("hashtag: %s", t)
511 honk.Onts = append(honk.Onts, t)
512 }
513 return ""
514 }
515 honk.Noise = re_retag.ReplaceAllStringFunc(honk.Noise, repl)
516}
517
518var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]_]+([ \n:;.,']|$)")
519
520func quickrename(s string, userid int64) string {
521 nonstop := true
522 for nonstop {
523 nonstop = false
524 s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
525 prefix := ""
526 if m[0] == ' ' || m[0] == '\n' {
527 prefix = m[:1]
528 m = m[1:]
529 }
530 prefix += "@"
531 m = m[1:]
532 tail := ""
533 if last := m[len(m)-1]; last == ' ' || last == '\n' ||
534 last == ':' || last == ';' ||
535 last == '.' || last == ',' || last == '\'' {
536 tail = m[len(m)-1:]
537 m = m[:len(m)-1]
538 }
539
540 xid := fullname(m, userid)
541
542 if xid != "" {
543 _, name := handles(xid)
544 if name != "" {
545 nonstop = true
546 m = name
547 }
548 }
549 return prefix + m + tail
550 })
551 }
552 return s
553}
554
555var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
556 honkers := gethonkers(userid)
557 m := make(map[string]string)
558 for _, h := range honkers {
559 m[h.XID] = h.Name
560 }
561 return m, true
562}, Invalidator: &honkerinvalidator})
563
564func shortname(userid int64, xid string) string {
565 var m map[string]string
566 ok := shortnames.Get(userid, &m)
567 if ok {
568 return m[xid]
569 }
570 return ""
571}
572
573var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
574 honkers := gethonkers(userid)
575 m := make(map[string]string)
576 for _, h := range honkers {
577 m[h.Name] = h.XID
578 }
579 return m, true
580}, Invalidator: &honkerinvalidator})
581
582func fullname(name string, userid int64) string {
583 var m map[string]string
584 ok := fullnames.Get(userid, &m)
585 if ok {
586 return m[name]
587 }
588 return ""
589}
590
591func attoreplacer(m string) string {
592 fill := `<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`
593 where := gofish(m)
594 if where == "" {
595 return m
596 }
597 who := m[0 : 1+strings.IndexByte(m[1:], '@')]
598 return fmt.Sprintf(fill, html.EscapeString(where), html.EscapeString(who))
599}
600
601func ontoreplacer(h string) string {
602 return fmt.Sprintf(`<a class="mention hashtag" href="https://%s/o/%s">%s</a>`, serverName,
603 strings.ToLower(h[1:]), h)
604}
605
606var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
607var re_urlhost = regexp.MustCompile("https://([^/ #)]+)")
608
609func originate(u string) string {
610 m := re_urlhost.FindStringSubmatch(u)
611 if len(m) > 1 {
612 return m[1]
613 }
614 return ""
615}
616
617var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
618 handle := getxonker(xid, "handle")
619 if handle == "" {
620 dlog.Printf("need to get a handle: %s", xid)
621 info, err := investigate(xid)
622 if err != nil {
623 m := re_unurl.FindStringSubmatch(xid)
624 if len(m) > 2 {
625 handle = m[2]
626 } else {
627 handle = xid
628 }
629 } else {
630 handle = info.Name
631 }
632 }
633 return handle, true
634}})
635
636// handle, handle@host
637func handles(xid string) (string, string) {
638 if xid == "" || xid == thewholeworld || strings.HasSuffix(xid, "/followers") {
639 return "", ""
640 }
641 var handle string
642 allhandles.Get(xid, &handle)
643 if handle == xid {
644 return xid, xid
645 }
646 return handle, handle + "@" + originate(xid)
647}
648
649func butnottooloud(aud []string) {
650 for i, a := range aud {
651 if strings.HasSuffix(a, "/followers") {
652 aud[i] = ""
653 }
654 }
655}
656
657func loudandproud(aud []string) bool {
658 for _, a := range aud {
659 if a == thewholeworld {
660 return true
661 }
662 }
663 return false
664}
665
666func firstclass(honk *Honk) bool {
667 return honk.Audience[0] == thewholeworld
668}
669
670func oneofakind(a []string) []string {
671 seen := make(map[string]bool)
672 seen[""] = true
673 j := 0
674 for _, s := range a {
675 if !seen[s] {
676 seen[s] = true
677 a[j] = s
678 j++
679 }
680 }
681 return a[:j]
682}
683
684var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
685 var user *WhatAbout
686 ok := somenumberedusers.Get(userid, &user)
687 if !ok {
688 return nil, false
689 }
690 ki := new(KeyInfo)
691 ki.keyname = user.URL + "#key"
692 ki.seckey = user.SecKey
693 return ki, true
694}})
695
696func ziggy(userid int64) *KeyInfo {
697 var ki *KeyInfo
698 ziggies.Get(userid, &ki)
699 return ki
700}
701
702var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
703 data := getxonker(keyname, "pubkey")
704 if data == "" {
705 dlog.Printf("hitting the webs for missing pubkey: %s", keyname)
706 j, err := GetJunk(readyLuserOne, keyname)
707 if err != nil {
708 ilog.Printf("error getting %s pubkey: %s", keyname, err)
709 when := time.Now().UTC().Format(dbtimeformat)
710 stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
711 return httpsig.PublicKey{}, true
712 }
713 allinjest(originate(keyname), j)
714 data = getxonker(keyname, "pubkey")
715 if data == "" {
716 ilog.Printf("key not found after ingesting")
717 when := time.Now().UTC().Format(dbtimeformat)
718 stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
719 return httpsig.PublicKey{}, true
720 }
721 }
722 if data == "failed" {
723 ilog.Printf("lookup previously failed key %s", keyname)
724 return httpsig.PublicKey{}, true
725 }
726 _, key, err := httpsig.DecodeKey(data)
727 if err != nil {
728 ilog.Printf("error decoding %s pubkey: %s", keyname, err)
729 return key, true
730 }
731 return key, true
732}, Limit: 512})
733
734func zaggy(keyname string) (httpsig.PublicKey, error) {
735 var key httpsig.PublicKey
736 zaggies.Get(keyname, &key)
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}