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 "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 "isNil": func(t any) bool { 250 // returns false for other "zero" values 251 return t == nil 252 }, 253 "list": func(args ...any) []any { 254 return args 255 }, 256 "dict": func(values ...any) (map[string]any, error) { 257 if len(values)%2 != 0 { 258 return nil, errors.New("invalid dict call") 259 } 260 dict := make(map[string]any, len(values)/2) 261 for i := 0; i < len(values); i += 2 { 262 key, ok := values[i].(string) 263 if !ok { 264 return nil, errors.New("dict keys must be strings") 265 } 266 dict[key] = values[i+1] 267 } 268 return dict, nil 269 }, 270 "deref": func(v any) any { 271 val := reflect.ValueOf(v) 272 if val.Kind() == reflect.Ptr && !val.IsNil() { 273 return val.Elem().Interface() 274 } 275 return nil 276 }, 277 "i": func(name string, classes ...string) template.HTML { 278 data, err := p.icon(name, classes) 279 if err != nil { 280 log.Printf("icon %s does not exist", name) 281 data, _ = p.icon("airplay", classes) 282 } 283 return template.HTML(data) 284 }, 285 "cssContentHash": p.CssContentHash, 286 "fileTree": filetree.FileTree, 287 "pathEscape": func(s string) string { 288 return url.PathEscape(s) 289 }, 290 "pathUnescape": func(s string) string { 291 u, _ := url.PathUnescape(s) 292 return u 293 }, 294 "safeUrl": func(s string) template.URL { 295 return template.URL(s) 296 }, 297 "tinyAvatar": func(handle string) string { 298 return p.AvatarUrl(handle, "tiny") 299 }, 300 "fullAvatar": func(handle string) string { 301 return p.AvatarUrl(handle, "") 302 }, 303 "langColor": enry.GetColor, 304 "layoutSide": func() string { 305 return "col-span-1 md:col-span-2 lg:col-span-3" 306 }, 307 "layoutCenter": func() string { 308 return "col-span-1 md:col-span-8 lg:col-span-6" 309 }, 310 311 "normalizeForHtmlId": func(s string) string { 312 normalized := strings.ReplaceAll(s, ":", "_") 313 normalized = strings.ReplaceAll(normalized, ".", "_") 314 return normalized 315 }, 316 "sshFingerprint": func(pubKey string) string { 317 fp, err := crypto.SSHFingerprint(pubKey) 318 if err != nil { 319 return "error" 320 } 321 return fp 322 }, 323 } 324} 325 326func (p *Pages) AvatarUrl(handle, size string) string { 327 handle = strings.TrimPrefix(handle, "@") 328 329 secret := p.avatar.SharedSecret 330 h := hmac.New(sha256.New, []byte(secret)) 331 h.Write([]byte(handle)) 332 signature := hex.EncodeToString(h.Sum(nil)) 333 334 sizeArg := "" 335 if size != "" { 336 sizeArg = fmt.Sprintf("size=%s", size) 337 } 338 return fmt.Sprintf("%s/%s/%s?%s", p.avatar.Host, signature, handle, sizeArg) 339} 340 341func (p *Pages) icon(name string, classes []string) (template.HTML, error) { 342 iconPath := filepath.Join("static", "icons", name) 343 344 if filepath.Ext(name) == "" { 345 iconPath += ".svg" 346 } 347 348 data, err := Files.ReadFile(iconPath) 349 if err != nil { 350 return "", fmt.Errorf("icon %s not found: %w", name, err) 351 } 352 353 // Convert SVG data to string 354 svgStr := string(data) 355 356 svgTagEnd := strings.Index(svgStr, ">") 357 if svgTagEnd == -1 { 358 return "", fmt.Errorf("invalid SVG format for icon %s", name) 359 } 360 361 classTag := ` class="` + strings.Join(classes, " ") + `"` 362 363 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:] 364 return template.HTML(modifiedSVG), nil 365} 366 367func durationFmt(duration time.Duration, names [4]string) string { 368 days := int64(duration.Hours() / 24) 369 hours := int64(math.Mod(duration.Hours(), 24)) 370 minutes := int64(math.Mod(duration.Minutes(), 60)) 371 seconds := int64(math.Mod(duration.Seconds(), 60)) 372 373 chunks := []struct { 374 name string 375 amount int64 376 }{ 377 {names[0], days}, 378 {names[1], hours}, 379 {names[2], minutes}, 380 {names[3], seconds}, 381 } 382 383 parts := []string{} 384 385 for _, chunk := range chunks { 386 if chunk.amount != 0 { 387 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name)) 388 } 389 } 390 391 return strings.Join(parts, " ") 392}