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