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