1package pages
2
3import (
4 "context"
5 "crypto/hmac"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "html"
11 "html/template"
12 "log"
13 "math"
14 "net/url"
15 "path/filepath"
16 "reflect"
17 "strings"
18 "time"
19
20 "github.com/dustin/go-humanize"
21 "github.com/go-enry/go-enry/v2"
22 "tangled.org/core/appview/filetree"
23 "tangled.org/core/appview/pages/markup"
24 "tangled.org/core/crypto"
25)
26
27func (p *Pages) funcMap() template.FuncMap {
28 return template.FuncMap{
29 "split": func(s string) []string {
30 return strings.Split(s, "\n")
31 },
32 "trimPrefix": func(s, prefix string) string {
33 return strings.TrimPrefix(s, prefix)
34 },
35 "join": func(elems []string, sep string) string {
36 return strings.Join(elems, sep)
37 },
38 "contains": func(s string, target string) bool {
39 return strings.Contains(s, target)
40 },
41 "mapContains": func(m any, key any) bool {
42 mapValue := reflect.ValueOf(m)
43 if mapValue.Kind() != reflect.Map {
44 return false
45 }
46 keyValue := reflect.ValueOf(key)
47 return mapValue.MapIndex(keyValue).IsValid()
48 },
49 "resolve": func(s string) string {
50 identity, err := p.resolver.ResolveIdent(context.Background(), s)
51
52 if err != nil {
53 return s
54 }
55
56 if identity.Handle.IsInvalidHandle() {
57 return "handle.invalid"
58 }
59
60 return "@" + identity.Handle.String()
61 },
62 "truncateAt30": func(s string) string {
63 if len(s) <= 30 {
64 return s
65 }
66 return s[:30] + "…"
67 },
68 "splitOn": func(s, sep string) []string {
69 return strings.Split(s, sep)
70 },
71 "int64": func(a int) int64 {
72 return int64(a)
73 },
74 "add": func(a, b int) int {
75 return a + b
76 },
77 "now": func() time.Time {
78 return time.Now()
79 },
80 // the absolute state of go templates
81 "add64": func(a, b int64) int64 {
82 return a + b
83 },
84 "sub": func(a, b int) int {
85 return a - b
86 },
87 "f64": func(a int) float64 {
88 return float64(a)
89 },
90 "addf64": func(a, b float64) float64 {
91 return a + b
92 },
93 "subf64": func(a, b float64) float64 {
94 return a - b
95 },
96 "mulf64": func(a, b float64) float64 {
97 return a * b
98 },
99 "divf64": func(a, b float64) float64 {
100 if b == 0 {
101 return 0
102 }
103 return a / b
104 },
105 "negf64": func(a float64) float64 {
106 return -a
107 },
108 "cond": func(cond any, a, b string) string {
109 if cond == nil {
110 return b
111 }
112
113 if boolean, ok := cond.(bool); boolean && ok {
114 return a
115 }
116
117 return b
118 },
119 "didOrHandle": func(did, handle string) string {
120 if handle != "" {
121 return fmt.Sprintf("@%s", handle)
122 } else {
123 return did
124 }
125 },
126 "assoc": func(values ...string) ([][]string, error) {
127 if len(values)%2 != 0 {
128 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments")
129 }
130 pairs := make([][]string, 0)
131 for i := 0; i < len(values); i += 2 {
132 pairs = append(pairs, []string{values[i], values[i+1]})
133 }
134 return pairs, nil
135 },
136 "append": func(s []string, values ...string) []string {
137 s = append(s, values...)
138 return s
139 },
140 "commaFmt": humanize.Comma,
141 "relTimeFmt": humanize.Time,
142 "shortRelTimeFmt": func(t time.Time) string {
143 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{
144 {D: time.Second, Format: "now", DivBy: time.Second},
145 {D: 2 * time.Second, Format: "1s %s", DivBy: 1},
146 {D: time.Minute, Format: "%ds %s", DivBy: time.Second},
147 {D: 2 * time.Minute, Format: "1min %s", DivBy: 1},
148 {D: time.Hour, Format: "%dmin %s", DivBy: time.Minute},
149 {D: 2 * time.Hour, Format: "1hr %s", DivBy: 1},
150 {D: humanize.Day, Format: "%dhrs %s", DivBy: time.Hour},
151 {D: 2 * humanize.Day, Format: "1d %s", DivBy: 1},
152 {D: 20 * humanize.Day, Format: "%dd %s", DivBy: humanize.Day},
153 {D: 8 * humanize.Week, Format: "%dw %s", DivBy: humanize.Week},
154 {D: humanize.Year, Format: "%dmo %s", DivBy: humanize.Month},
155 {D: 18 * humanize.Month, Format: "1y %s", DivBy: 1},
156 {D: 2 * humanize.Year, Format: "2y %s", DivBy: 1},
157 {D: humanize.LongTime, Format: "%dy %s", DivBy: humanize.Year},
158 {D: math.MaxInt64, Format: "a long while %s", DivBy: 1},
159 })
160 },
161 "longTimeFmt": func(t time.Time) string {
162 return t.Format("Jan 2, 2006, 3:04 PM MST")
163 },
164 "iso8601DateTimeFmt": func(t time.Time) string {
165 return t.Format("2006-01-02T15:04:05-07:00")
166 },
167 "iso8601DurationFmt": func(duration time.Duration) string {
168 days := int64(duration.Hours() / 24)
169 hours := int64(math.Mod(duration.Hours(), 24))
170 minutes := int64(math.Mod(duration.Minutes(), 60))
171 seconds := int64(math.Mod(duration.Seconds(), 60))
172 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds)
173 },
174 "durationFmt": func(duration time.Duration) string {
175 return durationFmt(duration, [4]string{"d", "hr", "min", "s"})
176 },
177 "longDurationFmt": func(duration time.Duration) string {
178 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"})
179 },
180 "byteFmt": humanize.Bytes,
181 "length": func(slice any) int {
182 v := reflect.ValueOf(slice)
183 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
184 return v.Len()
185 }
186 return 0
187 },
188 "splitN": func(s, sep string, n int) []string {
189 return strings.SplitN(s, sep, n)
190 },
191 "escapeHtml": func(s string) template.HTML {
192 if s == "" {
193 return template.HTML("<br>")
194 }
195 return template.HTML(s)
196 },
197 "unescapeHtml": func(s string) string {
198 return html.UnescapeString(s)
199 },
200 "nl2br": func(text string) template.HTML {
201 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
202 },
203 "unwrapText": func(text string) string {
204 paragraphs := strings.Split(text, "\n\n")
205
206 for i, p := range paragraphs {
207 lines := strings.Split(p, "\n")
208 paragraphs[i] = strings.Join(lines, " ")
209 }
210
211 return strings.Join(paragraphs, "\n\n")
212 },
213 "sequence": func(n int) []struct{} {
214 return make([]struct{}, n)
215 },
216 // take atmost N items from this slice
217 "take": func(slice any, n int) any {
218 v := reflect.ValueOf(slice)
219 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
220 return nil
221 }
222 if v.Len() == 0 {
223 return nil
224 }
225 return v.Slice(0, min(n, v.Len())).Interface()
226 },
227 "markdown": func(text string) template.HTML {
228 p.rctx.RendererType = markup.RendererTypeDefault
229 htmlString := p.rctx.RenderMarkdown(text)
230 sanitized := p.rctx.SanitizeDefault(htmlString)
231 return template.HTML(sanitized)
232 },
233 "description": func(text string) template.HTML {
234 p.rctx.RendererType = markup.RendererTypeDefault
235 htmlString := p.rctx.RenderMarkdown(text)
236 sanitized := p.rctx.SanitizeDescription(htmlString)
237 return template.HTML(sanitized)
238 },
239 "isNil": func(t any) bool {
240 // returns false for other "zero" values
241 return t == nil
242 },
243 "list": func(args ...any) []any {
244 return args
245 },
246 "dict": func(values ...any) (map[string]any, error) {
247 if len(values)%2 != 0 {
248 return nil, errors.New("invalid dict call")
249 }
250 dict := make(map[string]any, len(values)/2)
251 for i := 0; i < len(values); i += 2 {
252 key, ok := values[i].(string)
253 if !ok {
254 return nil, errors.New("dict keys must be strings")
255 }
256 dict[key] = values[i+1]
257 }
258 return dict, nil
259 },
260 "deref": func(v any) any {
261 val := reflect.ValueOf(v)
262 if val.Kind() == reflect.Ptr && !val.IsNil() {
263 return val.Elem().Interface()
264 }
265 return nil
266 },
267 "i": func(name string, classes ...string) template.HTML {
268 data, err := icon(name, classes)
269 if err != nil {
270 log.Printf("icon %s does not exist", name)
271 data, _ = icon("airplay", classes)
272 }
273 return template.HTML(data)
274 },
275 "cssContentHash": CssContentHash,
276 "fileTree": filetree.FileTree,
277 "pathEscape": func(s string) string {
278 return url.PathEscape(s)
279 },
280 "pathUnescape": func(s string) string {
281 u, _ := url.PathUnescape(s)
282 return u
283 },
284
285 "tinyAvatar": func(handle string) string {
286 return p.avatarUri(handle, "tiny")
287 },
288 "fullAvatar": func(handle string) string {
289 return p.avatarUri(handle, "")
290 },
291 "langColor": enry.GetColor,
292 "layoutSide": func() string {
293 return "col-span-1 md:col-span-2 lg:col-span-3"
294 },
295 "layoutCenter": func() string {
296 return "col-span-1 md:col-span-8 lg:col-span-6"
297 },
298
299 "normalizeForHtmlId": func(s string) string {
300 // TODO: extend this to handle other cases?
301 return strings.ReplaceAll(s, ":", "_")
302 },
303 "sshFingerprint": func(pubKey string) string {
304 fp, err := crypto.SSHFingerprint(pubKey)
305 if err != nil {
306 return "error"
307 }
308 return fp
309 },
310 }
311}
312
313func (p *Pages) avatarUri(handle, size string) string {
314 handle = strings.TrimPrefix(handle, "@")
315
316 secret := p.avatar.SharedSecret
317 h := hmac.New(sha256.New, []byte(secret))
318 h.Write([]byte(handle))
319 signature := hex.EncodeToString(h.Sum(nil))
320
321 sizeArg := ""
322 if size != "" {
323 sizeArg = fmt.Sprintf("size=%s", size)
324 }
325 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg)
326}
327
328func icon(name string, classes []string) (template.HTML, error) {
329 iconPath := filepath.Join("static", "icons", name)
330
331 if filepath.Ext(name) == "" {
332 iconPath += ".svg"
333 }
334
335 data, err := Files.ReadFile(iconPath)
336 if err != nil {
337 return "", fmt.Errorf("icon %s not found: %w", name, err)
338 }
339
340 // Convert SVG data to string
341 svgStr := string(data)
342
343 svgTagEnd := strings.Index(svgStr, ">")
344 if svgTagEnd == -1 {
345 return "", fmt.Errorf("invalid SVG format for icon %s", name)
346 }
347
348 classTag := ` class="` + strings.Join(classes, " ") + `"`
349
350 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:]
351 return template.HTML(modifiedSVG), nil
352}
353
354func durationFmt(duration time.Duration, names [4]string) string {
355 days := int64(duration.Hours() / 24)
356 hours := int64(math.Mod(duration.Hours(), 24))
357 minutes := int64(math.Mod(duration.Minutes(), 60))
358 seconds := int64(math.Mod(duration.Seconds(), 60))
359
360 chunks := []struct {
361 name string
362 amount int64
363 }{
364 {names[0], days},
365 {names[1], hours},
366 {names[2], minutes},
367 {names[3], seconds},
368 }
369
370 parts := []string{}
371
372 for _, chunk := range chunks {
373 if chunk.amount != 0 {
374 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name))
375 }
376 }
377
378 return strings.Join(parts, " ")
379}