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