forked from
tangled.org/core
Monorepo for Tangled
1package pages
2
3import (
4 "bytes"
5 "context"
6 "crypto/hmac"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "html"
12 "html/template"
13 "log"
14 "math"
15 "math/rand"
16 "net/url"
17 "path/filepath"
18 "reflect"
19 "strings"
20 "time"
21
22 "github.com/alecthomas/chroma/v2"
23 chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
24 "github.com/alecthomas/chroma/v2/lexers"
25 "github.com/alecthomas/chroma/v2/styles"
26 "github.com/bluesky-social/indigo/atproto/syntax"
27 "github.com/dustin/go-humanize"
28 "github.com/dustin/go-humanize/english"
29 "github.com/go-enry/go-enry/v2"
30 "github.com/yuin/goldmark"
31 emoji "github.com/yuin/goldmark-emoji"
32 "tangled.org/core/appview/cache"
33 "tangled.org/core/appview/db"
34 "tangled.org/core/appview/models"
35 "tangled.org/core/appview/oauth"
36 "tangled.org/core/appview/pages/markup"
37 "tangled.org/core/crypto"
38 "tangled.org/core/idresolver"
39)
40
41type tab map[string]string
42
43func (p *Pages) funcMap() template.FuncMap {
44 return template.FuncMap{
45 "split": func(s string) []string {
46 return strings.Split(s, "\n")
47 },
48 "trimPrefix": func(s, prefix string) string {
49 return strings.TrimPrefix(s, prefix)
50 },
51 "join": func(elems []string, sep string) string {
52 return strings.Join(elems, sep)
53 },
54 "contains": func(s string, target string) bool {
55 return strings.Contains(s, target)
56 },
57 "stripPort": func(hostname string) string {
58 if strings.Contains(hostname, ":") {
59 return strings.Split(hostname, ":")[0]
60 }
61 return hostname
62 },
63 "mapContains": func(m any, key any) bool {
64 mapValue := reflect.ValueOf(m)
65 if mapValue.Kind() != reflect.Map {
66 return false
67 }
68 keyValue := reflect.ValueOf(key)
69 return mapValue.MapIndex(keyValue).IsValid()
70 },
71 "resolve": func(s string) string {
72 return p.DisplayHandle(context.Background(), s)
73 },
74 "primaryHandle": func(s string) string {
75 return primaryHandle(p.resolver, s)
76 },
77 "resolvePds": func(s string) string {
78 identity, err := p.resolver.ResolveIdent(context.Background(), s)
79 if err != nil {
80 return ""
81 }
82 return identity.PDSEndpoint()
83 },
84 "ownerSlashRepo": func(repo *models.Repo) string {
85 ownerId, err := p.resolver.ResolveIdent(context.Background(), repo.Did)
86 if err != nil {
87 return repo.RepoIdentifier()
88 }
89 handle := ownerId.Handle
90 if handle != "" && !handle.IsInvalidHandle() {
91 return string(handle) + "/" + repo.Name
92 }
93 return repo.RepoIdentifier()
94 },
95 "truncateAt30": func(s string) string {
96 if len(s) <= 30 {
97 return s
98 }
99 return s[:30] + "…"
100 },
101 "splitOn": func(s, sep string) []string {
102 return strings.Split(s, sep)
103 },
104 "string": func(v any) string {
105 return fmt.Sprint(v)
106 },
107 "int64": func(a int) int64 {
108 return int64(a)
109 },
110 "add": func(a, b int) int {
111 return a + b
112 },
113 "now": func() time.Time {
114 return time.Now()
115 },
116 // the absolute state of go templates
117 "add64": func(a, b int64) int64 {
118 return a + b
119 },
120 "sub": func(a, b int) int {
121 return a - b
122 },
123 "mul": func(a, b int) int {
124 return a * b
125 },
126 "div": func(a, b int) int {
127 return a / b
128 },
129 "mod": func(a, b int) int {
130 return a % b
131 },
132 "randInt": func(bound int) int {
133 return rand.Intn(bound)
134 },
135 "f64": func(a int) float64 {
136 return float64(a)
137 },
138 "addf64": func(a, b float64) float64 {
139 return a + b
140 },
141 "subf64": func(a, b float64) float64 {
142 return a - b
143 },
144 "mulf64": func(a, b float64) float64 {
145 return a * b
146 },
147 "divf64": func(a, b float64) float64 {
148 if b == 0 {
149 return 0
150 }
151 return a / b
152 },
153 "negf64": func(a float64) float64 {
154 return -a
155 },
156 "cond": func(cond any, a, b string) string {
157 if cond == nil {
158 return b
159 }
160
161 if boolean, ok := cond.(bool); boolean && ok {
162 return a
163 }
164
165 return b
166 },
167 "assoc": func(values ...string) ([][]string, error) {
168 if len(values)%2 != 0 {
169 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments")
170 }
171 pairs := make([][]string, 0)
172 for i := 0; i < len(values); i += 2 {
173 pairs = append(pairs, []string{values[i], values[i+1]})
174 }
175 return pairs, nil
176 },
177 "append": func(s []any, values ...any) []any {
178 s = append(s, values...)
179 return s
180 },
181 "commaFmt": humanize.Comma,
182 "plural": english.Plural,
183 "relTimeFmt": humanize.Time,
184 "shortRelTimeFmt": func(t time.Time) string {
185 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{
186 {D: time.Second, Format: "now", DivBy: time.Second},
187 {D: 2 * time.Second, Format: "1s %s", DivBy: 1},
188 {D: time.Minute, Format: "%ds %s", DivBy: time.Second},
189 {D: 2 * time.Minute, Format: "1min %s", DivBy: 1},
190 {D: time.Hour, Format: "%dmin %s", DivBy: time.Minute},
191 {D: 2 * time.Hour, Format: "1hr %s", DivBy: 1},
192 {D: humanize.Day, Format: "%dhrs %s", DivBy: time.Hour},
193 {D: 2 * humanize.Day, Format: "1d %s", DivBy: 1},
194 {D: 20 * humanize.Day, Format: "%dd %s", DivBy: humanize.Day},
195 {D: 8 * humanize.Week, Format: "%dw %s", DivBy: humanize.Week},
196 {D: humanize.Year, Format: "%dmo %s", DivBy: humanize.Month},
197 {D: 18 * humanize.Month, Format: "1y %s", DivBy: 1},
198 {D: 2 * humanize.Year, Format: "2y %s", DivBy: 1},
199 {D: humanize.LongTime, Format: "%dy %s", DivBy: humanize.Year},
200 {D: math.MaxInt64, Format: "a long while %s", DivBy: 1},
201 })
202 },
203 "shortTimeFmt": func(t time.Time) string {
204 return t.Format("Jan 2, 2006")
205 },
206 "longTimeFmt": func(t time.Time) string {
207 return t.Format("Jan 2, 2006, 3:04 PM MST")
208 },
209 "iso8601DateTimeFmt": func(t time.Time) string {
210 return t.Format("2006-01-02T15:04:05-07:00")
211 },
212 "iso8601DurationFmt": func(duration time.Duration) string {
213 days := int64(duration.Hours() / 24)
214 hours := int64(math.Mod(duration.Hours(), 24))
215 minutes := int64(math.Mod(duration.Minutes(), 60))
216 seconds := int64(math.Mod(duration.Seconds(), 60))
217 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds)
218 },
219 "durationFmt": func(duration time.Duration) string {
220 return durationFmt(duration, [4]string{"d", "h", "m", "s"})
221 },
222 "longDurationFmt": func(duration time.Duration) string {
223 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"})
224 },
225 "byteFmt": humanize.Bytes,
226 "length": func(slice any) int {
227 v := reflect.ValueOf(slice)
228 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
229 return v.Len()
230 }
231 return 0
232 },
233 "splitN": func(s, sep string, n int) []string {
234 return strings.SplitN(s, sep, n)
235 },
236 "escapeHtml": func(s string) template.HTML {
237 if s == "" {
238 return template.HTML("<br>")
239 }
240 return template.HTML(s)
241 },
242 "unescapeHtml": func(s string) string {
243 return html.UnescapeString(s)
244 },
245 "nl2br": func(text string) template.HTML {
246 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
247 },
248 "unwrapText": func(text string) string {
249 paragraphs := strings.Split(text, "\n\n")
250
251 for i, p := range paragraphs {
252 lines := strings.Split(p, "\n")
253 paragraphs[i] = strings.Join(lines, " ")
254 }
255
256 return strings.Join(paragraphs, "\n\n")
257 },
258 "sequence": func(n int) []struct{} {
259 return make([]struct{}, n)
260 },
261 // take atmost N items from this slice
262 "take": func(slice any, n int) any {
263 v := reflect.ValueOf(slice)
264 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
265 return nil
266 }
267 if v.Len() == 0 {
268 return nil
269 }
270 return v.Slice(0, min(n, v.Len())).Interface()
271 },
272 "markdown": func(text string) template.HTML {
273 rctx := p.rctx.Clone()
274 rctx.RendererType = markup.RendererTypeDefault
275 htmlString := rctx.RenderMarkdown(text)
276 sanitized := rctx.SanitizeDefault(htmlString)
277 return template.HTML(sanitized)
278 },
279 "description": func(text string) template.HTML {
280 rctx := p.rctx.Clone()
281 rctx.RendererType = markup.RendererTypeDefault
282 htmlString := rctx.RenderMarkdownWith(text, goldmark.New(
283 goldmark.WithExtensions(
284 emoji.Emoji,
285 ),
286 ))
287 sanitized := rctx.SanitizeDescription(htmlString)
288 return template.HTML(sanitized)
289 },
290 "readme": func(text string) template.HTML {
291 rctx := p.rctx.Clone()
292 rctx.RendererType = markup.RendererTypeRepoMarkdown
293 htmlString := rctx.RenderMarkdown(text)
294 sanitized := rctx.SanitizeDefault(htmlString)
295 return template.HTML(sanitized)
296 },
297 "code": func(content, path string) string {
298 var style *chroma.Style = styles.Get("catpuccin-latte")
299 formatter := chromahtml.New(
300 chromahtml.InlineCode(false),
301 chromahtml.WithLineNumbers(true),
302 chromahtml.WithLinkableLineNumbers(true, "L"),
303 chromahtml.Standalone(false),
304 chromahtml.WithClasses(true),
305 )
306
307 lexer := lexers.Get(filepath.Base(path))
308 if lexer == nil {
309 if firstLine, _, ok := strings.Cut(content, "\n"); ok && strings.HasPrefix(firstLine, "#!") {
310 // extract interpreter from shebang (handles "#!/usr/bin/env nu", "#!/usr/bin/nu", etc.)
311 fields := strings.Fields(firstLine[2:])
312 if len(fields) > 0 {
313 interp := filepath.Base(fields[len(fields)-1])
314 lexer = lexers.Get(interp)
315 }
316 }
317 }
318 if lexer == nil {
319 lexer = lexers.Analyse(content)
320 }
321 if lexer == nil {
322 lexer = lexers.Fallback
323 }
324
325 iterator, err := lexer.Tokenise(nil, content)
326 if err != nil {
327 p.logger.Error("chroma tokenize", "err", "err")
328 return ""
329 }
330
331 var code bytes.Buffer
332 err = formatter.Format(&code, style, iterator)
333 if err != nil {
334 p.logger.Error("chroma format", "err", "err")
335 return ""
336 }
337
338 return code.String()
339 },
340 "trimUriScheme": func(text string) string {
341 text = strings.TrimPrefix(text, "https://")
342 text = strings.TrimPrefix(text, "http://")
343 return text
344 },
345 "isNil": func(t any) bool {
346 // returns false for other "zero" values
347 return t == nil
348 },
349 "list": func(args ...any) []any {
350 return args
351 },
352 "dict": func(values ...any) (map[string]any, error) {
353 if len(values)%2 != 0 {
354 return nil, errors.New("invalid dict call")
355 }
356 dict := make(map[string]any, len(values)/2)
357 for i := 0; i < len(values); i += 2 {
358 key, ok := values[i].(string)
359 if !ok {
360 return nil, errors.New("dict keys must be strings")
361 }
362 dict[key] = values[i+1]
363 }
364 return dict, nil
365 },
366 "queryParams": func(params ...any) (url.Values, error) {
367 if len(params)%2 != 0 {
368 return nil, errors.New("invalid queryParams call")
369 }
370 vals := make(url.Values, len(params)/2)
371 for i := 0; i < len(params); i += 2 {
372 key, ok := params[i].(string)
373 if !ok {
374 return nil, errors.New("queryParams keys must be strings")
375 }
376 v, ok := params[i+1].(string)
377 if !ok {
378 return nil, errors.New("queryParams values must be strings")
379 }
380 vals.Add(key, v)
381 }
382 return vals, nil
383 },
384 "deref": func(v any) any {
385 val := reflect.ValueOf(v)
386 if val.Kind() == reflect.Pointer && !val.IsNil() {
387 return val.Elem().Interface()
388 }
389 return nil
390 },
391 "i": func(name string, classes ...string) template.HTML {
392 data, err := p.icon(name, classes)
393 if err != nil {
394 log.Printf("icon %s does not exist", name)
395 data, _ = p.icon("airplay", classes)
396 }
397 return template.HTML(data)
398 },
399 "cssContentHash": p.CssContentHash,
400 "pathEscape": func(s string) string {
401 return url.PathEscape(s)
402 },
403 "pathUnescape": func(s string) string {
404 u, _ := url.PathUnescape(s)
405 return u
406 },
407 "safeUrl": func(s string) template.URL {
408 return template.URL(s)
409 },
410 "tinyAvatar": func(handle string) string {
411 return p.AvatarUrl(handle, "tiny")
412 },
413 "fullAvatar": func(handle string) string {
414 return p.AvatarUrl(handle, "")
415 },
416 "placeholderAvatar": func(size string) template.HTML {
417 sizeClass := "size-6"
418 iconSize := "size-4"
419 switch size {
420 case "tiny":
421 sizeClass = "size-6"
422 iconSize = "size-4"
423 case "small":
424 sizeClass = "size-8"
425 iconSize = "size-5"
426 default:
427 sizeClass = "size-12"
428 iconSize = "size-8"
429 }
430 icon, _ := p.icon("user-round", []string{iconSize, "text-gray-400", "dark:text-gray-500"})
431 return template.HTML(fmt.Sprintf(`<div class="%s rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center flex-shrink-0">%s</div>`, sizeClass, icon))
432 },
433 "profileAvatarUrl": func(profile *models.Profile, size string) string {
434 if profile != nil {
435 return p.AvatarUrl(profile.Did, size)
436 }
437 return ""
438 },
439 "langColor": enry.GetColor,
440 "reverse": func(s any) any {
441 if s == nil {
442 return nil
443 }
444
445 v := reflect.ValueOf(s)
446
447 if v.Kind() != reflect.Slice {
448 return s
449 }
450
451 length := v.Len()
452 reversed := reflect.MakeSlice(v.Type(), length, length)
453
454 for i := range length {
455 reversed.Index(i).Set(v.Index(length - 1 - i))
456 }
457
458 return reversed.Interface()
459 },
460 "normalizeForHtmlId": func(s string) string {
461 normalized := strings.ReplaceAll(s, ":", "_")
462 normalized = strings.ReplaceAll(normalized, ".", "_")
463 return normalized
464 },
465 "sshFingerprint": func(pubKey string) string {
466 fp, err := crypto.SSHFingerprint(pubKey)
467 if err != nil {
468 return "error"
469 }
470 return fp
471 },
472 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo {
473 result := make([]oauth.AccountInfo, 0, len(accounts))
474 for _, acc := range accounts {
475 if acc.Did != activeDid {
476 result = append(result, acc)
477 }
478 }
479 return result
480 },
481 "isGenerated": func(path string) bool {
482 return enry.IsGenerated(path, nil)
483 },
484 // constant values used to define a template
485 "const": func() map[string]any {
486 return map[string]any{
487 "OrderedReactionKinds": models.OrderedReactionKinds,
488 // would be great to have ordered maps right about now
489 "UserSettingsTabs": []tab{
490 {"Name": "profile", "Icon": "user"},
491 {"Name": "keys", "Icon": "key"},
492 {"Name": "emails", "Icon": "mail"},
493 {"Name": "notifications", "Icon": "bell"},
494 {"Name": "knots", "Icon": "volleyball"},
495 {"Name": "spindles", "Icon": "spool"},
496 {"Name": "sites", "Icon": "globe"},
497 },
498 "RepoSettingsTabs": []tab{
499 {"Name": "general", "Icon": "sliders-horizontal"},
500 {"Name": "access", "Icon": "users"},
501 {"Name": "pipelines", "Icon": "layers-2"},
502 {"Name": "hooks", "Icon": "webhook"},
503 {"Name": "sites", "Icon": "globe"},
504 },
505 "PdsUserDomain": p.pdsCfg.UserDomain,
506 }
507 },
508 "did": func(s string) syntax.DID {
509 // cast to DID
510 return syntax.DID(s)
511 },
512 }
513}
514
515func primaryHandle(r *idresolver.Resolver, s string) string {
516 identity, err := r.ResolveIdent(context.Background(), s)
517 if err != nil || identity.Handle.IsInvalidHandle() {
518 return "handle.invalid"
519 }
520 return identity.Handle.String()
521}
522
523func (p *Pages) DisplayHandle(ctx context.Context, did string) string {
524 if p.db != nil {
525 if h := cache.LookupPreferredHandle(ctx, p.rdb, p.db, did); h != "" {
526 return h
527 }
528 }
529 if id, err := p.resolver.ResolveIdent(ctx, did); err == nil && !id.Handle.IsInvalidHandle() {
530 return id.Handle.String()
531 }
532 return did
533}
534
535func (p *Pages) AvatarUrl(actor, size string) string {
536 actor = strings.TrimPrefix(actor, "@")
537
538 identity, err := p.resolver.ResolveIdent(context.Background(), actor)
539 var did string
540 if err != nil {
541 did = actor
542 } else {
543 did = identity.DID.String()
544 }
545
546 secret := p.avatar.SharedSecret
547 if secret == "" {
548 return ""
549 }
550 h := hmac.New(sha256.New, []byte(secret))
551 h.Write([]byte(did))
552 signature := hex.EncodeToString(h.Sum(nil))
553
554 // Get avatar CID for cache busting
555 version := ""
556 if p.db != nil {
557 profile, err := db.GetProfile(p.db, did)
558 if err == nil && profile != nil && profile.Avatar != "" {
559 // Use first 8 chars of avatar CID as version
560 if len(profile.Avatar) > 8 {
561 version = profile.Avatar[:8]
562 } else {
563 version = profile.Avatar
564 }
565 }
566 }
567
568 baseUrl := fmt.Sprintf("%s/%s/%s", p.avatar.Host, signature, did)
569 if size != "" {
570 if version != "" {
571 return fmt.Sprintf("%s?size=%s&v=%s", baseUrl, size, version)
572 }
573 return fmt.Sprintf("%s?size=%s", baseUrl, size)
574 }
575 if version != "" {
576 return fmt.Sprintf("%s?v=%s", baseUrl, version)
577 }
578
579 return baseUrl
580}
581
582func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
583 iconPath := filepath.Join("static", "icons", name)
584
585 if filepath.Ext(name) == "" {
586 iconPath += ".svg"
587 }
588
589 data, err := Files.ReadFile(iconPath)
590 if err != nil {
591 return "", fmt.Errorf("icon %s not found: %w", name, err)
592 }
593
594 // Convert SVG data to string
595 svgStr := string(data)
596
597 svgTagEnd := strings.Index(svgStr, ">")
598 if svgTagEnd == -1 {
599 return "", fmt.Errorf("invalid SVG format for icon %s", name)
600 }
601
602 classTag := ` class="` + strings.Join(classes, " ") + `"`
603
604 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
605 return template.HTML(modifiedSVG), nil
606}
607
608func durationFmt(duration time.Duration, names [4]string) string {
609 days := int64(duration.Hours() / 24)
610 hours := int64(math.Mod(duration.Hours(), 24))
611 minutes := int64(math.Mod(duration.Minutes(), 60))
612 seconds := int64(math.Mod(duration.Seconds(), 60))
613
614 chunks := []struct {
615 name string
616 amount int64
617 }{
618 {names[0], days},
619 {names[1], hours},
620 {names[2], minutes},
621 {names[3], seconds},
622 }
623
624 parts := []string{}
625
626 for _, chunk := range chunks {
627 if chunk.amount != 0 {
628 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
629 }
630 }
631
632 return strings.Join(parts, " ")
633}