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/models"
30 "tangled.org/core/appview/oauth"
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.Pointer && !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 "pathEscape": func(s string) string {
352 return url.PathEscape(s)
353 },
354 "pathUnescape": func(s string) string {
355 u, _ := url.PathUnescape(s)
356 return u
357 },
358 "safeUrl": func(s string) template.URL {
359 return template.URL(s)
360 },
361 "tinyAvatar": func(handle string) string {
362 return p.AvatarUrl(handle, "tiny")
363 },
364 "fullAvatar": func(handle string) string {
365 return p.AvatarUrl(handle, "")
366 },
367 "langColor": enry.GetColor,
368 "reverse": func(s any) any {
369 if s == nil {
370 return nil
371 }
372
373 v := reflect.ValueOf(s)
374
375 if v.Kind() != reflect.Slice {
376 return s
377 }
378
379 length := v.Len()
380 reversed := reflect.MakeSlice(v.Type(), length, length)
381
382 for i := range length {
383 reversed.Index(i).Set(v.Index(length - 1 - i))
384 }
385
386 return reversed.Interface()
387 },
388 "normalizeForHtmlId": func(s string) string {
389 normalized := strings.ReplaceAll(s, ":", "_")
390 normalized = strings.ReplaceAll(normalized, ".", "_")
391 return normalized
392 },
393 "sshFingerprint": func(pubKey string) string {
394 fp, err := crypto.SSHFingerprint(pubKey)
395 if err != nil {
396 return "error"
397 }
398 return fp
399 },
400 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo {
401 result := make([]oauth.AccountInfo, 0, len(accounts))
402 for _, acc := range accounts {
403 if acc.Did != activeDid {
404 result = append(result, acc)
405 }
406 }
407 return result
408 },
409 }
410}
411
412func (p *Pages) resolveDid(did string) string {
413 identity, err := p.resolver.ResolveIdent(context.Background(), did)
414
415 if err != nil {
416 return did
417 }
418
419 if identity.Handle.IsInvalidHandle() {
420 return "handle.invalid"
421 }
422
423 return identity.Handle.String()
424}
425
426func (p *Pages) AvatarUrl(handle, size string) string {
427 handle = strings.TrimPrefix(handle, "@")
428
429 handle = p.resolveDid(handle)
430
431 secret := p.avatar.SharedSecret
432 h := hmac.New(sha256.New, []byte(secret))
433 h.Write([]byte(handle))
434 signature := hex.EncodeToString(h.Sum(nil))
435
436 sizeArg := ""
437 if size != "" {
438 sizeArg = fmt.Sprintf("size=%s", size)
439 }
440 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg)
441}
442
443func (p *Pages) icon(name string, classes []string) (template.HTML, error) {
444 iconPath := filepath.Join("static", "icons", name)
445
446 if filepath.Ext(name) == "" {
447 iconPath += ".svg"
448 }
449
450 data, err := Files.ReadFile(iconPath)
451 if err != nil {
452 return "", fmt.Errorf("icon %s not found: %w", name, err)
453 }
454
455 // Convert SVG data to string
456 svgStr := string(data)
457
458 svgTagEnd := strings.Index(svgStr, ">")
459 if svgTagEnd == -1 {
460 return "", fmt.Errorf("invalid SVG format for icon %s", name)
461 }
462
463 classTag := ` class="` + strings.Join(classes, " ") + `"`
464
465 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
466 return template.HTML(modifiedSVG), nil
467}
468
469func durationFmt(duration time.Duration, names [4]string) string {
470 days := int64(duration.Hours() / 24)
471 hours := int64(math.Mod(duration.Hours(), 24))
472 minutes := int64(math.Mod(duration.Minutes(), 60))
473 seconds := int64(math.Mod(duration.Seconds(), 60))
474
475 chunks := []struct {
476 name string
477 amount int64
478 }{
479 {names[0], days},
480 {names[1], hours},
481 {names[2], minutes},
482 {names[3], seconds},
483 }
484
485 parts := []string{}
486
487 for _, chunk := range chunks {
488 if chunk.amount != 0 {
489 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
490 }
491 }
492
493 return strings.Join(parts, " ")
494}