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