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