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