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