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