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