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 Name: name,
431 Media: ct,
432 URL: url,
433 Local: false,
434 }
435 honk.Donks = append(honk.Donks, d)
436 return ""
437 }
438 honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
439}
440
441var re_quickmention = regexp.MustCompile("(^|[ \n])@[[:alnum:]]+([ \n.]|$)")
442
443func quickrename(s string, userid int64) string {
444 nonstop := true
445 for nonstop {
446 nonstop = false
447 s = re_quickmention.ReplaceAllStringFunc(s, func(m string) string {
448 prefix := ""
449 if m[0] == ' ' || m[0] == '\n' {
450 prefix = m[:1]
451 m = m[1:]
452 }
453 prefix += "@"
454 m = m[1:]
455 tail := ""
456 if last := m[len(m)-1]; last == ' ' || last == '\n' || last == '.' {
457 tail = m[len(m)-1:]
458 m = m[:len(m)-1]
459 }
460
461 xid := fullname(m, userid)
462
463 if xid != "" {
464 _, name := handles(xid)
465 if name != "" {
466 nonstop = true
467 m = name
468 }
469 }
470 return prefix + m + tail
471 })
472 }
473 return s
474}
475
476var shortnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
477 honkers := gethonkers(userid)
478 m := make(map[string]string)
479 for _, h := range honkers {
480 m[h.XID] = h.Name
481 }
482 return m, true
483}, Invalidator: &honkerinvalidator})
484
485func shortname(userid int64, xid string) string {
486 var m map[string]string
487 ok := shortnames.Get(userid, &m)
488 if ok {
489 return m[xid]
490 }
491 return ""
492}
493
494var fullnames = cache.New(cache.Options{Filler: func(userid int64) (map[string]string, bool) {
495 honkers := gethonkers(userid)
496 m := make(map[string]string)
497 for _, h := range honkers {
498 m[h.Name] = h.XID
499 }
500 return m, true
501}, Invalidator: &honkerinvalidator})
502
503func fullname(name string, userid int64) string {
504 var m map[string]string
505 ok := fullnames.Get(userid, &m)
506 if ok {
507 return m[name]
508 }
509 return ""
510}
511
512func attoreplacer(m string) string {
513 fill := `<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`
514 where := gofish(m)
515 if where == "" {
516 return m
517 }
518 who := m[0 : 1+strings.IndexByte(m[1:], '@')]
519 return fmt.Sprintf(fill, html.EscapeString(where), html.EscapeString(who))
520}
521
522func ontoreplacer(h string) string {
523 return fmt.Sprintf(`<a href="https://%s/o/%s">%s</a>`, serverName,
524 strings.ToLower(h[1:]), h)
525}
526
527var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
528var re_urlhost = regexp.MustCompile("https://([^/ #)]+)")
529
530func originate(u string) string {
531 m := re_urlhost.FindStringSubmatch(u)
532 if len(m) > 1 {
533 return m[1]
534 }
535 return ""
536}
537
538var allhandles = cache.New(cache.Options{Filler: func(xid string) (string, bool) {
539 var handle string
540 row := stmtGetXonker.QueryRow(xid, "handle")
541 err := row.Scan(&handle)
542 if err != nil {
543 log.Printf("need to get a handle: %s", xid)
544 info, err := investigate(xid)
545 if err != nil {
546 m := re_unurl.FindStringSubmatch(xid)
547 if len(m) > 2 {
548 handle = m[2]
549 } else {
550 handle = xid
551 }
552 } else {
553 handle = info.Name
554 }
555 }
556 return handle, true
557}})
558
559// handle, handle@host
560func handles(xid string) (string, string) {
561 if xid == "" || xid == thewholeworld || strings.HasSuffix(xid, "/followers") {
562 return "", ""
563 }
564 var handle string
565 allhandles.Get(xid, &handle)
566 if handle == xid {
567 return xid, xid
568 }
569 return handle, handle + "@" + originate(xid)
570}
571
572func butnottooloud(aud []string) {
573 for i, a := range aud {
574 if strings.HasSuffix(a, "/followers") {
575 aud[i] = ""
576 }
577 }
578}
579
580func loudandproud(aud []string) bool {
581 for _, a := range aud {
582 if a == thewholeworld {
583 return true
584 }
585 }
586 return false
587}
588
589func firstclass(honk *Honk) bool {
590 return honk.Audience[0] == thewholeworld
591}
592
593func oneofakind(a []string) []string {
594 seen := make(map[string]bool)
595 seen[""] = true
596 j := 0
597 for _, s := range a {
598 if !seen[s] {
599 seen[s] = true
600 a[j] = s
601 j++
602 }
603 }
604 return a[:j]
605}
606
607var ziggies = cache.New(cache.Options{Filler: func(userid int64) (*KeyInfo, bool) {
608 var user *WhatAbout
609 ok := somenumberedusers.Get(userid, &user)
610 if !ok {
611 return nil, false
612 }
613 ki := new(KeyInfo)
614 ki.keyname = user.URL + "#key"
615 ki.seckey = user.SecKey
616 return ki, true
617}})
618
619func ziggy(userid int64) *KeyInfo {
620 var ki *KeyInfo
621 ziggies.Get(userid, &ki)
622 return ki
623}
624
625var zaggies = cache.New(cache.Options{Filler: func(keyname string) (httpsig.PublicKey, bool) {
626 var data string
627 row := stmtGetXonker.QueryRow(keyname, "pubkey")
628 err := row.Scan(&data)
629 var key httpsig.PublicKey
630 if err != nil {
631 log.Printf("hitting the webs for missing pubkey: %s", keyname)
632 j, err := GetJunk(keyname)
633 if err != nil {
634 log.Printf("error getting %s pubkey: %s", keyname, err)
635 when := time.Now().UTC().Format(dbtimeformat)
636 stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
637 return key, true
638 }
639 allinjest(originate(keyname), j)
640 row = stmtGetXonker.QueryRow(keyname, "pubkey")
641 err = row.Scan(&data)
642 if err != nil {
643 log.Printf("key not found after ingesting")
644 when := time.Now().UTC().Format(dbtimeformat)
645 stmtSaveXonker.Exec(keyname, "failed", "pubkey", when)
646 return key, true
647 }
648 }
649 _, key, err = httpsig.DecodeKey(data)
650 if err != nil {
651 log.Printf("error decoding %s pubkey: %s", keyname, err)
652 return key, true
653 }
654 return key, true
655}, Limit: 512})
656
657func zaggy(keyname string) httpsig.PublicKey {
658 var key httpsig.PublicKey
659 zaggies.Get(keyname, &key)
660 return key
661}
662
663func savingthrow(keyname string) {
664 when := time.Now().UTC().Add(-30 * time.Minute).Format(dbtimeformat)
665 stmtDeleteXonker.Exec(keyname, "pubkey", when)
666 zaggies.Clear(keyname)
667}
668
669func keymatch(keyname string, actor string) string {
670 hash := strings.IndexByte(keyname, '#')
671 if hash == -1 {
672 hash = len(keyname)
673 }
674 owner := keyname[0:hash]
675 if owner == actor {
676 return originate(actor)
677 }
678 return ""
679}