Monorepo for Tangled tangled.org
10

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