Monorepo for Tangled tangled.org
5

Configure Feed

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

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