This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

core / appview / pages / funcmap.go
17 kB 615 lines
1package pages 2 3import ( 4 "bytes" 5 "context" 6 "crypto/hmac" 7 "crypto/sha256" 8 "encoding/hex" 9 "errors" 10 "fmt" 11 "html" 12 "html/template" 13 "log" 14 "math" 15 "math/rand" 16 "net/url" 17 "path/filepath" 18 "reflect" 19 "strings" 20 "time" 21 22 "github.com/alecthomas/chroma/v2" 23 chromahtml "github.com/alecthomas/chroma/v2/formatters/html" 24 "github.com/alecthomas/chroma/v2/lexers" 25 "github.com/alecthomas/chroma/v2/styles" 26 "github.com/dustin/go-humanize" 27 "github.com/go-enry/go-enry/v2" 28 "github.com/yuin/goldmark" 29 emoji "github.com/yuin/goldmark-emoji" 30 "tangled.org/core/appview/db" 31 "tangled.org/core/appview/models" 32 "tangled.org/core/appview/oauth" 33 "tangled.org/core/appview/pages/markup" 34 "tangled.org/core/crypto" 35) 36 37type tab map[string]string 38 39func (p *Pages) funcMap() template.FuncMap { 40 return template.FuncMap{ 41 "split": func(s string) []string { 42 return strings.Split(s, "\n") 43 }, 44 "trimPrefix": func(s, prefix string) string { 45 return strings.TrimPrefix(s, prefix) 46 }, 47 "join": func(elems []string, sep string) string { 48 return strings.Join(elems, sep) 49 }, 50 "contains": func(s string, target string) bool { 51 return strings.Contains(s, target) 52 }, 53 "stripPort": func(hostname string) string { 54 if strings.Contains(hostname, ":") { 55 return strings.Split(hostname, ":")[0] 56 } 57 return hostname 58 }, 59 "mapContains": func(m any, key any) bool { 60 mapValue := reflect.ValueOf(m) 61 if mapValue.Kind() != reflect.Map { 62 return false 63 } 64 keyValue := reflect.ValueOf(key) 65 return mapValue.MapIndex(keyValue).IsValid() 66 }, 67 "resolve": func(s string) string { 68 profile, err := db.GetProfile(p.db, s) 69 if err == nil && profile != nil && profile.PreferredHandle != "" { 70 return string(profile.PreferredHandle) 71 } 72 73 identity, err := p.resolver.ResolveIdent(context.Background(), s) 74 if err != nil { 75 return s 76 } 77 78 if identity.Handle.IsInvalidHandle() { 79 return "handle.invalid" 80 } 81 82 return identity.Handle.String() 83 }, 84 "resolvePds": func(s string) string { 85 identity, err := p.resolver.ResolveIdent(context.Background(), s) 86 if err != nil { 87 return "" 88 } 89 return identity.PDSEndpoint() 90 }, 91 "ownerSlashRepo": func(repo *models.Repo) string { 92 ownerId, err := p.resolver.ResolveIdent(context.Background(), repo.Did) 93 if err != nil { 94 return repo.RepoIdentifier() 95 } 96 handle := ownerId.Handle 97 if handle != "" && !handle.IsInvalidHandle() { 98 return string(handle) + "/" + repo.Name 99 } 100 return repo.RepoIdentifier() 101 }, 102 "truncateAt30": func(s string) string { 103 if len(s) <= 30 { 104 return s 105 } 106 return s[:30] + "…" 107 }, 108 "splitOn": func(s, sep string) []string { 109 return strings.Split(s, sep) 110 }, 111 "string": func(v any) string { 112 return fmt.Sprint(v) 113 }, 114 "int64": func(a int) int64 { 115 return int64(a) 116 }, 117 "add": func(a, b int) int { 118 return a + b 119 }, 120 "now": func() time.Time { 121 return time.Now() 122 }, 123 // the absolute state of go templates 124 "add64": func(a, b int64) int64 { 125 return a + b 126 }, 127 "sub": func(a, b int) int { 128 return a - b 129 }, 130 "mul": func(a, b int) int { 131 return a * b 132 }, 133 "div": func(a, b int) int { 134 return a / b 135 }, 136 "mod": func(a, b int) int { 137 return a % b 138 }, 139 "randInt": func(bound int) int { 140 return rand.Intn(bound) 141 }, 142 "f64": func(a int) float64 { 143 return float64(a) 144 }, 145 "addf64": func(a, b float64) float64 { 146 return a + b 147 }, 148 "subf64": func(a, b float64) float64 { 149 return a - b 150 }, 151 "mulf64": func(a, b float64) float64 { 152 return a * b 153 }, 154 "divf64": func(a, b float64) float64 { 155 if b == 0 { 156 return 0 157 } 158 return a / b 159 }, 160 "negf64": func(a float64) float64 { 161 return -a 162 }, 163 "cond": func(cond any, a, b string) string { 164 if cond == nil { 165 return b 166 } 167 168 if boolean, ok := cond.(bool); boolean && ok { 169 return a 170 } 171 172 return b 173 }, 174 "assoc": func(values ...string) ([][]string, error) { 175 if len(values)%2 != 0 { 176 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments") 177 } 178 pairs := make([][]string, 0) 179 for i := 0; i < len(values); i += 2 { 180 pairs = append(pairs, []string{values[i], values[i+1]}) 181 } 182 return pairs, nil 183 }, 184 "append": func(s []any, values ...any) []any { 185 s = append(s, values...) 186 return s 187 }, 188 "commaFmt": humanize.Comma, 189 "relTimeFmt": humanize.Time, 190 "shortRelTimeFmt": func(t time.Time) string { 191 return humanize.CustomRelTime(t, time.Now(), "", "", []humanize.RelTimeMagnitude{ 192 {D: time.Second, Format: "now", DivBy: time.Second}, 193 {D: 2 * time.Second, Format: "1s %s", DivBy: 1}, 194 {D: time.Minute, Format: "%ds %s", DivBy: time.Second}, 195 {D: 2 * time.Minute, Format: "1min %s", DivBy: 1}, 196 {D: time.Hour, Format: "%dmin %s", DivBy: time.Minute}, 197 {D: 2 * time.Hour, Format: "1hr %s", DivBy: 1}, 198 {D: humanize.Day, Format: "%dhrs %s", DivBy: time.Hour}, 199 {D: 2 * humanize.Day, Format: "1d %s", DivBy: 1}, 200 {D: 20 * humanize.Day, Format: "%dd %s", DivBy: humanize.Day}, 201 {D: 8 * humanize.Week, Format: "%dw %s", DivBy: humanize.Week}, 202 {D: humanize.Year, Format: "%dmo %s", DivBy: humanize.Month}, 203 {D: 18 * humanize.Month, Format: "1y %s", DivBy: 1}, 204 {D: 2 * humanize.Year, Format: "2y %s", DivBy: 1}, 205 {D: humanize.LongTime, Format: "%dy %s", DivBy: humanize.Year}, 206 {D: math.MaxInt64, Format: "a long while %s", DivBy: 1}, 207 }) 208 }, 209 "shortTimeFmt": func(t time.Time) string { 210 return t.Format("Jan 2, 2006") 211 }, 212 "longTimeFmt": func(t time.Time) string { 213 return t.Format("Jan 2, 2006, 3:04 PM MST") 214 }, 215 "iso8601DateTimeFmt": func(t time.Time) string { 216 return t.Format("2006-01-02T15:04:05-07:00") 217 }, 218 "iso8601DurationFmt": func(duration time.Duration) string { 219 days := int64(duration.Hours() / 24) 220 hours := int64(math.Mod(duration.Hours(), 24)) 221 minutes := int64(math.Mod(duration.Minutes(), 60)) 222 seconds := int64(math.Mod(duration.Seconds(), 60)) 223 return fmt.Sprintf("P%dD%dH%dM%dS", days, hours, minutes, seconds) 224 }, 225 "durationFmt": func(duration time.Duration) string { 226 return durationFmt(duration, [4]string{"d", "h", "m", "s"}) 227 }, 228 "longDurationFmt": func(duration time.Duration) string { 229 return durationFmt(duration, [4]string{"days", "hours", "minutes", "seconds"}) 230 }, 231 "byteFmt": humanize.Bytes, 232 "length": func(slice any) int { 233 v := reflect.ValueOf(slice) 234 if v.Kind() == reflect.Slice || v.Kind() == reflect.Array { 235 return v.Len() 236 } 237 return 0 238 }, 239 "splitN": func(s, sep string, n int) []string { 240 return strings.SplitN(s, sep, n) 241 }, 242 "escapeHtml": func(s string) template.HTML { 243 if s == "" { 244 return template.HTML("<br>") 245 } 246 return template.HTML(s) 247 }, 248 "unescapeHtml": func(s string) string { 249 return html.UnescapeString(s) 250 }, 251 "nl2br": func(text string) template.HTML { 252 return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>")) 253 }, 254 "unwrapText": func(text string) string { 255 paragraphs := strings.Split(text, "\n\n") 256 257 for i, p := range paragraphs { 258 lines := strings.Split(p, "\n") 259 paragraphs[i] = strings.Join(lines, " ") 260 } 261 262 return strings.Join(paragraphs, "\n\n") 263 }, 264 "sequence": func(n int) []struct{} { 265 return make([]struct{}, n) 266 }, 267 // take atmost N items from this slice 268 "take": func(slice any, n int) any { 269 v := reflect.ValueOf(slice) 270 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { 271 return nil 272 } 273 if v.Len() == 0 { 274 return nil 275 } 276 return v.Slice(0, min(n, v.Len())).Interface() 277 }, 278 "markdown": func(text string) template.HTML { 279 rctx := p.rctx.Clone() 280 rctx.RendererType = markup.RendererTypeDefault 281 htmlString := rctx.RenderMarkdown(text) 282 sanitized := rctx.SanitizeDefault(htmlString) 283 return template.HTML(sanitized) 284 }, 285 "description": func(text string) template.HTML { 286 rctx := p.rctx.Clone() 287 rctx.RendererType = markup.RendererTypeDefault 288 htmlString := rctx.RenderMarkdownWith(text, goldmark.New( 289 goldmark.WithExtensions( 290 emoji.Emoji, 291 ), 292 )) 293 sanitized := rctx.SanitizeDescription(htmlString) 294 return template.HTML(sanitized) 295 }, 296 "readme": func(text string) template.HTML { 297 rctx := p.rctx.Clone() 298 rctx.RendererType = markup.RendererTypeRepoMarkdown 299 htmlString := rctx.RenderMarkdown(text) 300 sanitized := rctx.SanitizeDefault(htmlString) 301 return template.HTML(sanitized) 302 }, 303 "code": func(content, path string) string { 304 var style *chroma.Style = styles.Get("catpuccin-latte") 305 formatter := chromahtml.New( 306 chromahtml.InlineCode(false), 307 chromahtml.WithLineNumbers(true), 308 chromahtml.WithLinkableLineNumbers(true, "L"), 309 chromahtml.Standalone(false), 310 chromahtml.WithClasses(true), 311 ) 312 313 lexer := lexers.Get(filepath.Base(path)) 314 if lexer == nil { 315 if firstLine, _, ok := strings.Cut(content, "\n"); ok && strings.HasPrefix(firstLine, "#!") { 316 // extract interpreter from shebang (handles "#!/usr/bin/env nu", "#!/usr/bin/nu", etc.) 317 fields := strings.Fields(firstLine[2:]) 318 if len(fields) > 0 { 319 interp := filepath.Base(fields[len(fields)-1]) 320 lexer = lexers.Get(interp) 321 } 322 } 323 } 324 if lexer == nil { 325 lexer = lexers.Analyse(content) 326 } 327 if lexer == nil { 328 lexer = lexers.Fallback 329 } 330 331 iterator, err := lexer.Tokenise(nil, content) 332 if err != nil { 333 p.logger.Error("chroma tokenize", "err", "err") 334 return "" 335 } 336 337 var code bytes.Buffer 338 err = formatter.Format(&code, style, iterator) 339 if err != nil { 340 p.logger.Error("chroma format", "err", "err") 341 return "" 342 } 343 344 return code.String() 345 }, 346 "trimUriScheme": func(text string) string { 347 text = strings.TrimPrefix(text, "https://") 348 text = strings.TrimPrefix(text, "http://") 349 return text 350 }, 351 "isNil": func(t any) bool { 352 // returns false for other "zero" values 353 return t == nil 354 }, 355 "list": func(args ...any) []any { 356 return args 357 }, 358 "dict": func(values ...any) (map[string]any, error) { 359 if len(values)%2 != 0 { 360 return nil, errors.New("invalid dict call") 361 } 362 dict := make(map[string]any, len(values)/2) 363 for i := 0; i < len(values); i += 2 { 364 key, ok := values[i].(string) 365 if !ok { 366 return nil, errors.New("dict keys must be strings") 367 } 368 dict[key] = values[i+1] 369 } 370 return dict, nil 371 }, 372 "queryParams": func(params ...any) (url.Values, error) { 373 if len(params)%2 != 0 { 374 return nil, errors.New("invalid queryParams call") 375 } 376 vals := make(url.Values, len(params)/2) 377 for i := 0; i < len(params); i += 2 { 378 key, ok := params[i].(string) 379 if !ok { 380 return nil, errors.New("queryParams keys must be strings") 381 } 382 v, ok := params[i+1].(string) 383 if !ok { 384 return nil, errors.New("queryParams values must be strings") 385 } 386 vals.Add(key, v) 387 } 388 return vals, nil 389 }, 390 "deref": func(v any) any { 391 val := reflect.ValueOf(v) 392 if val.Kind() == reflect.Pointer && !val.IsNil() { 393 return val.Elem().Interface() 394 } 395 return nil 396 }, 397 "i": func(name string, classes ...string) template.HTML { 398 data, err := p.icon(name, classes) 399 if err != nil { 400 log.Printf("icon %s does not exist", name) 401 data, _ = p.icon("airplay", classes) 402 } 403 return template.HTML(data) 404 }, 405 "cssContentHash": p.CssContentHash, 406 "pathEscape": func(s string) string { 407 return url.PathEscape(s) 408 }, 409 "pathUnescape": func(s string) string { 410 u, _ := url.PathUnescape(s) 411 return u 412 }, 413 "safeUrl": func(s string) template.URL { 414 return template.URL(s) 415 }, 416 "tinyAvatar": func(handle string) string { 417 return p.AvatarUrl(handle, "tiny") 418 }, 419 "fullAvatar": func(handle string) string { 420 return p.AvatarUrl(handle, "") 421 }, 422 "placeholderAvatar": func(size string) template.HTML { 423 sizeClass := "size-6" 424 iconSize := "size-4" 425 switch size { 426 case "tiny": 427 sizeClass = "size-6" 428 iconSize = "size-4" 429 case "small": 430 sizeClass = "size-8" 431 iconSize = "size-5" 432 default: 433 sizeClass = "size-12" 434 iconSize = "size-8" 435 } 436 icon, _ := p.icon("user-round", []string{iconSize, "text-gray-400", "dark:text-gray-500"}) 437 return template.HTML(fmt.Sprintf(`<div class="%s rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center flex-shrink-0">%s</div>`, sizeClass, icon)) 438 }, 439 "profileAvatarUrl": func(profile *models.Profile, size string) string { 440 if profile != nil { 441 return p.AvatarUrl(profile.Did, size) 442 } 443 return "" 444 }, 445 "langColor": enry.GetColor, 446 "reverse": func(s any) any { 447 if s == nil { 448 return nil 449 } 450 451 v := reflect.ValueOf(s) 452 453 if v.Kind() != reflect.Slice { 454 return s 455 } 456 457 length := v.Len() 458 reversed := reflect.MakeSlice(v.Type(), length, length) 459 460 for i := range length { 461 reversed.Index(i).Set(v.Index(length - 1 - i)) 462 } 463 464 return reversed.Interface() 465 }, 466 "normalizeForHtmlId": func(s string) string { 467 normalized := strings.ReplaceAll(s, ":", "_") 468 normalized = strings.ReplaceAll(normalized, ".", "_") 469 return normalized 470 }, 471 "sshFingerprint": func(pubKey string) string { 472 fp, err := crypto.SSHFingerprint(pubKey) 473 if err != nil { 474 return "error" 475 } 476 return fp 477 }, 478 "otherAccounts": func(activeDid string, accounts []oauth.AccountInfo) []oauth.AccountInfo { 479 result := make([]oauth.AccountInfo, 0, len(accounts)) 480 for _, acc := range accounts { 481 if acc.Did != activeDid { 482 result = append(result, acc) 483 } 484 } 485 return result 486 }, 487 "isGenerated": func(path string) bool { 488 return enry.IsGenerated(path, nil) 489 }, 490 // constant values used to define a template 491 "const": func() map[string]any { 492 return map[string]any{ 493 "OrderedReactionKinds": models.OrderedReactionKinds, 494 // would be great to have ordered maps right about now 495 "UserSettingsTabs": []tab{ 496 {"Name": "profile", "Icon": "user"}, 497 {"Name": "keys", "Icon": "key"}, 498 {"Name": "emails", "Icon": "mail"}, 499 {"Name": "notifications", "Icon": "bell"}, 500 {"Name": "knots", "Icon": "volleyball"}, 501 {"Name": "spindles", "Icon": "spool"}, 502 {"Name": "sites", "Icon": "globe"}, 503 }, 504 "RepoSettingsTabs": []tab{ 505 {"Name": "general", "Icon": "sliders-horizontal"}, 506 {"Name": "access", "Icon": "users"}, 507 {"Name": "pipelines", "Icon": "layers-2"}, 508 {"Name": "hooks", "Icon": "webhook"}, 509 {"Name": "sites", "Icon": "globe"}, 510 }, 511 "PdsUserDomain": p.pdsCfg.UserDomain, 512 } 513 }, 514 } 515} 516 517func (p *Pages) AvatarUrl(actor, size string) string { 518 actor = strings.TrimPrefix(actor, "@") 519 520 identity, err := p.resolver.ResolveIdent(context.Background(), actor) 521 var did string 522 if err != nil { 523 did = actor 524 } else { 525 did = identity.DID.String() 526 } 527 528 secret := p.avatar.SharedSecret 529 if secret == "" { 530 return "" 531 } 532 h := hmac.New(sha256.New, []byte(secret)) 533 h.Write([]byte(did)) 534 signature := hex.EncodeToString(h.Sum(nil)) 535 536 // Get avatar CID for cache busting 537 version := "" 538 if p.db != nil { 539 profile, err := db.GetProfile(p.db, did) 540 if err == nil && profile != nil && profile.Avatar != "" { 541 // Use first 8 chars of avatar CID as version 542 if len(profile.Avatar) > 8 { 543 version = profile.Avatar[:8] 544 } else { 545 version = profile.Avatar 546 } 547 } 548 } 549 550 baseUrl := fmt.Sprintf("%s/%s/%s", p.avatar.Host, signature, did) 551 if size != "" { 552 if version != "" { 553 return fmt.Sprintf("%s?size=%s&v=%s", baseUrl, size, version) 554 } 555 return fmt.Sprintf("%s?size=%s", baseUrl, size) 556 } 557 if version != "" { 558 return fmt.Sprintf("%s?v=%s", baseUrl, version) 559 } 560 561 return baseUrl 562} 563 564func (p *Pages) icon(name string, classes []string) (template.HTML, error) { 565 iconPath := filepath.Join("static", "icons", name) 566 567 if filepath.Ext(name) == "" { 568 iconPath += ".svg" 569 } 570 571 data, err := Files.ReadFile(iconPath) 572 if err != nil { 573 return "", fmt.Errorf("icon %s not found: %w", name, err) 574 } 575 576 // Convert SVG data to string 577 svgStr := string(data) 578 579 svgTagEnd := strings.Index(svgStr, ">") 580 if svgTagEnd == -1 { 581 return "", fmt.Errorf("invalid SVG format for icon %s", name) 582 } 583 584 classTag := ` class="` + strings.Join(classes, " ") + `"` 585 586 modifiedSVG := svgStr[:svgTagEnd] + classTag + svgStr[svgTagEnd:] 587 return template.HTML(modifiedSVG), nil 588} 589 590func durationFmt(duration time.Duration, names [4]string) string { 591 days := int64(duration.Hours() / 24) 592 hours := int64(math.Mod(duration.Hours(), 24)) 593 minutes := int64(math.Mod(duration.Minutes(), 60)) 594 seconds := int64(math.Mod(duration.Seconds(), 60)) 595 596 chunks := []struct { 597 name string 598 amount int64 599 }{ 600 {names[0], days}, 601 {names[1], hours}, 602 {names[2], minutes}, 603 {names[3], seconds}, 604 } 605 606 parts := []string{} 607 608 for _, chunk := range chunks { 609 if chunk.amount != 0 { 610 parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.name)) 611 } 612 } 613 614 return strings.Join(parts, " ") 615}