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