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