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