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