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