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/filetree"
30 "tangled.org/core/appview/models"
31 "tangled.org/core/appview/pages/markup"
32 "tangled.org/core/crypto"
33)
34
35func (p *Pages) funcMap() template.FuncMap {
36 return template.FuncMap{
37 "split": func(s string) []string {
38 return strings.Split(s, "\n")
39 },
40 "trimPrefix": func(s, prefix string) string {
41 return strings.TrimPrefix(s, prefix)
42 },
43 "join": func(elems []string, sep string) string {
44 return strings.Join(elems, sep)
45 },
46 "contains": func(s string, target string) bool {
47 return strings.Contains(s, target)
48 },
49 "stripPort": func(hostname string) string {
50 if strings.Contains(hostname, ":") {
51 return strings.Split(hostname, ":")[0]
52 }
53 return hostname
54 },
55 "mapContains": func(m any, key any) bool {
56 mapValue := reflect.ValueOf(m)
57 if mapValue.Kind() != reflect.Map {
58 return false
59 }
60 keyValue := reflect.ValueOf(key)
61 return mapValue.MapIndex(keyValue).IsValid()
62 },
63 "resolve": func(s string) string {
64 identity, err := p.resolver.ResolveIdent(context.Background(), s)
65
66 if err != nil {
67 return s
68 }
69
70 if identity.Handle.IsInvalidHandle() {
71 return "handle.invalid"
72 }
73
74 return identity.Handle.String()
75 },
76 "ownerSlashRepo": func(repo *models.Repo) string {
77 ownerId, err := p.resolver.ResolveIdent(context.Background(), repo.Did)
78 if err != nil {
79 return repo.DidSlashRepo()
80 }
81 handle := ownerId.Handle
82 if handle != "" && !handle.IsInvalidHandle() {
83 return string(handle) + "/" + repo.Name
84 }
85 return repo.DidSlashRepo()
86 },
87 "truncateAt30": func(s string) string {
88 if len(s) <= 30 {
89 return s
90 }
91 return s[:30] + "…"
92 },
93 "splitOn": func(s, sep string) []string {
94 return strings.Split(s, sep)
95 },
96 "string": func(v any) string {
97 return fmt.Sprint(v)
98 },
99 "int64": func(a int) int64 {
100 return int64(a)
101 },
102 "add": func(a, b int) int {
103 return a + b
104 },
105 "now": func() time.Time {
106 return time.Now()
107 },
108 // the absolute state of go templates
109 "add64": func(a, b int64) int64 {
110 return a + b
111 },
112 "sub": func(a, b int) int {
113 return a - b
114 },
115 "mul": func(a, b int) int {
116 return a * b
117 },
118 "div": func(a, b int) int {
119 return a / b
120 },
121 "mod": func(a, b int) int {
122 return a % b
123 },
124 "f64": func(a int) float64 {
125 return float64(a)
126 },
127 "addf64": func(a, b float64) float64 {
128 return a + b
129 },
130 "subf64": func(a, b float64) float64 {
131 return a - b
132 },
133 "mulf64": func(a, b float64) float64 {
134 return a * b
135 },
136 "divf64": func(a, b float64) float64 {
137 if b == 0 {
138 return 0
139 }
140 return a / b
141 },
142 "negf64": func(a float64) float64 {
143 return -a
144 },
145 "cond": func(cond any, a, b string) string {
146 if cond == nil {
147 return b
148 }
149
150 if boolean, ok := cond.(bool); boolean && ok {
151 return a
152 }
153
154 return b
155 },
156 "assoc": func(values ...string) ([][]string, error) {
157 if len(values)%2 != 0 {
158 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments")
159 }
160 pairs := make([][]string, 0)
161 for i := 0; i < len(values); i += 2 {
162 pairs = append(pairs, []string{values[i], values[i+1]})
163 }
164 return pairs, nil
165 },
166 "append": func(s []any, values ...any) []any {
167 s = append(s, values...)
168 return s
169 },
170 "commaFmt": humanize.Comma,
171 "relTimeFmt": humanize.Time,
172 "shortRelTimeFmt": func(t time.Time) string {
173 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{
174 {D: time.Second, Format: "now", DivBy: time.Second},
175 {D: 2 * time.Second, Format: "1s %s", DivBy: 1},
176 {D: time.Minute, Format: "%ds %s", DivBy: time.Second},
177 {D: 2 * time.Minute, Format: "1min %s", DivBy: 1},
178 {D: time.Hour, Format: "%dmin %s", DivBy: time.Minute},
179 {D: 2 * time.Hour, Format: "1hr %s", DivBy: 1},
180 {D: humanize.Day, Format: "%dhrs %s", DivBy: time.Hour},
181 {D: 2 * humanize.Day, Format: "1d %s", DivBy: 1},
182 {D: 20 * humanize.Day, Format: "%dd %s", DivBy: humanize.Day},
183 {D: 8 * humanize.Week, Format: "%dw %s", DivBy: humanize.Week},
184 {D: humanize.Year, Format: "%dmo %s", DivBy: humanize.Month},
185 {D: 18 * humanize.Month, Format: "1y %s", DivBy: 1},
186 {D: 2 * humanize.Year, Format: "2y %s", DivBy: 1},
187 {D: humanize.LongTime, Format: "%dy %s", DivBy: humanize.Year},
188 {D: math.MaxInt64, Format: "a long while %s", DivBy: 1},
189 })
190 },
191 "longTimeFmt": func(t time.Time) string {
192 return t.Format("Jan 2, 2006, 3:04 PM MST")
193 },
194 "iso8601DateTimeFmt": func(t time.Time) string {
195 return t.Format("2006-01-02T15:04:05-07:00")
196 },
197 "iso8601DurationFmt": func(duration time.Duration) string {
198 days := int64(duration.Hours() / 24)
199 hours := int64(math.Mod(duration.Hours(), 24))
200 minutes := int64(math.Mod(duration.Minutes(), 60))
201 seconds := int64(math.Mod(duration.Seconds(), 60))
202 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds)
203 },
204 "durationFmt": func(duration time.Duration) string {
205 return durationFmt(duration, [4]string{"d", "hr", "min", "s"})
206 },
207 "longDurationFmt": func(duration time.Duration) string {
208 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"})
209 },
210 "byteFmt": humanize.Bytes,
211 "length": func(slice any) int {
212 v := reflect.ValueOf(slice)
213 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
214 return v.Len()
215 }
216 return 0
217 },
218 "splitN": func(s, sep string, n int) []string {
219 return strings.SplitN(s, sep, n)
220 },
221 "escapeHtml": func(s string) template.HTML {
222 if s == "" {
223 return template.HTML("<br>")
224 }
225 return template.HTML(s)
226 },
227 "unescapeHtml": func(s string) string {
228 return html.UnescapeString(s)
229 },
230 "nl2br": func(text string) template.HTML {
231 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
232 },
233 "unwrapText": func(text string) string {
234 paragraphs := strings.Split(text, "\n\n")
235
236 for i, p := range paragraphs {
237 lines := strings.Split(p, "\n")
238 paragraphs[i] = strings.Join(lines, " ")
239 }
240
241 return strings.Join(paragraphs, "\n\n")
242 },
243 "sequence": func(n int) []struct{} {
244 return make([]struct{}, n)
245 },
246 // take atmost N items from this slice
247 "take": func(slice any, n int) any {
248 v := reflect.ValueOf(slice)
249 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
250 return nil
251 }
252 if v.Len() == 0 {
253 return nil
254 }
255 return v.Slice(0, min(n, v.Len())).Interface()
256 },
257 "markdown": func(text string) template.HTML {
258 p.rctx.RendererType = markup.RendererTypeDefault
259 htmlString := p.rctx.RenderMarkdown(text)
260 sanitized := p.rctx.SanitizeDefault(htmlString)
261 return template.HTML(sanitized)
262 },
263 "description": func(text string) template.HTML {
264 p.rctx.RendererType = markup.RendererTypeDefault
265 htmlString := p.rctx.RenderMarkdownWith(text, goldmark.New(
266 goldmark.WithExtensions(
267 emoji.Emoji,
268 ),
269 ))
270 sanitized := p.rctx.SanitizeDescription(htmlString)
271 return template.HTML(sanitized)
272 },
273 "readme": func(text string) template.HTML {
274 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
275 htmlString := p.rctx.RenderMarkdown(text)
276 sanitized := p.rctx.SanitizeDefault(htmlString)
277 return template.HTML(sanitized)
278 },
279 "code": func(content, path string) string {
280 var style *chroma.Style = styles.Get("catpuccin-latte")
281 formatter := chromahtml.New(
282 chromahtml.InlineCode(false),
283 chromahtml.WithLineNumbers(true),
284 chromahtml.WithLinkableLineNumbers(true, "L"),
285 chromahtml.Standalone(false),
286 chromahtml.WithClasses(true),
287 )
288
289 lexer := lexers.Get(filepath.Base(path))
290 if lexer == nil {
291 lexer = lexers.Fallback
292 }
293
294 iterator, err := lexer.Tokenise(nil, content)
295 if err != nil {
296 p.logger.Error("chroma tokenize", "err", "err")
297 return ""
298 }
299
300 var code bytes.Buffer
301 err = formatter.Format(&code, style, iterator)
302 if err != nil {
303 p.logger.Error("chroma format", "err", "err")
304 return ""
305 }
306
307 return code.String()
308 },
309 "trimUriScheme": func(text string) string {
310 text = strings.TrimPrefix(text, "https://")
311 text = strings.TrimPrefix(text, "http://")
312 return text
313 },
314 "isNil": func(t any) bool {
315 // returns false for other "zero" values
316 return t == nil
317 },
318 "list": func(args ...any) []any {
319 return args
320 },
321 "dict": func(values ...any) (map[string]any, error) {
322 if len(values)%2 != 0 {
323 return nil, errors.New("invalid dict call")
324 }
325 dict := make(map[string]any, len(values)/2)
326 for i := 0; i < len(values); i += 2 {
327 key, ok := values[i].(string)
328 if !ok {
329 return nil, errors.New("dict keys must be strings")
330 }
331 dict[key] = values[i+1]
332 }
333 return dict, nil
334 },
335 "deref": func(v any) any {
336 val := reflect.ValueOf(v)
337 if val.Kind() == reflect.Ptr && !val.IsNil() {
338 return val.Elem().Interface()
339 }
340 return nil
341 },
342 "i": func(name string, classes ...string) template.HTML {
343 data, err := p.icon(name, classes)
344 if err != nil {
345 log.Printf("icon %s does not exist", name)
346 data, _ = p.icon("airplay", classes)
347 }
348 return template.HTML(data)
349 },
350 "cssContentHash": p.CssContentHash,
351 "fileTree": filetree.FileTree,
352 "pathEscape": func(s string) string {
353 return url.PathEscape(s)
354 },
355 "pathUnescape": func(s string) string {
356 u, _ := url.PathUnescape(s)
357 return u
358 },
359 "safeUrl": func(s string) template.URL {
360 return template.URL(s)
361 },
362 "tinyAvatar": func(handle string) string {
363 return p.AvatarUrl(handle, "tiny")
364 },
365 "fullAvatar": func(handle string) string {
366 return p.AvatarUrl(handle, "")
367 },
368 "langColor": enry.GetColor,
369 "layoutSide": func() string {
370 return "col-span-1 md:col-span-2 lg:col-span-3"
371 },
372 "layoutCenter": func() string {
373 return "col-span-1 md:col-span-8 lg:col-span-6"
374 },
375
376 "normalizeForHtmlId": func(s string) string {
377 normalized := strings.ReplaceAll(s, ":", "_")
378 normalized = strings.ReplaceAll(normalized, ".", "_")
379 return normalized
380 },
381 "sshFingerprint": func(pubKey string) string {
382 fp, err := crypto.SSHFingerprint(pubKey)
383 if err != nil {
384 return "error"
385 }
386 return fp
387 },
388 }
389}
390
391func (p *Pages) resolveDid(did string) string {
392 identity, err := p.resolver.ResolveIdent(context.Background(), did)
393
394 if err != nil {
395 return did
396 }
397
398 if identity.Handle.IsInvalidHandle() {
399 return "handle.invalid"
400 }
401
402 return identity.Handle.String()
403}
404
405func (p *Pages) AvatarUrl(handle, size string) string {
406 handle = strings.TrimPrefix(handle, "@")
407
408 handle = p.resolveDid(handle)
409
410 secret := p.avatar.SharedSecret
411 h := hmac.New(sha256.New, []byte(secret))
412 h.Write([]byte(handle))
413 signature := hex.EncodeToString(h.Sum(nil))
414
415 sizeArg := ""
416 if size != "" {
417 sizeArg = fmt.Sprintf("size=%s", size)
418 }
419 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg)
420}
421
422func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
423 iconPath := filepath.Join("static", "icons", name)
424
425 if filepath.Ext(name) == "" {
426 iconPath += ".svg"
427 }
428
429 data, err := Files.ReadFile(iconPath)
430 if err != nil {
431 return "", fmt.Errorf("icon %s not found: %w", name, err)
432 }
433
434 // Convert SVG data to string
435 svgStr := string(data)
436
437 svgTagEnd := strings.Index(svgStr, ">")
438 if svgTagEnd == -1 {
439 return "", fmt.Errorf("invalid SVG format for icon %s", name)
440 }
441
442 classTag := ` class="` + strings.Join(classes, " ") + `"`
443
444 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
445 return template.HTML(modifiedSVG), nil
446}
447
448func durationFmt(duration time.Duration, names [4]string) string {
449 days := int64(duration.Hours() / 24)
450 hours := int64(math.Mod(duration.Hours(), 24))
451 minutes := int64(math.Mod(duration.Minutes(), 60))
452 seconds := int64(math.Mod(duration.Seconds(), 60))
453
454 chunks := []struct {
455 name string
456 amount int64
457 }{
458 {names[0], days},
459 {names[1], hours},
460 {names[2], minutes},
461 {names[3], seconds},
462 }
463
464 parts := []string{}
465
466 for _, chunk := range chunks {
467 if chunk.amount != 0 {
468 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
469 }
470 }
471
472 return strings.Join(parts, " ")
473}