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