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