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