From c61472b7f42940f0e5c5a2eaf2d4fc949d98bd15 Mon Sep 17 00:00:00 2001 From: sudoquasar Date: Mon, 28 Sep 2026 20:53:52 +0530 Subject: [PATCH] Add Phase 2: where to watch in India Implements docs/phase-2-plan.md end to end: an availability block on every title page (Stream/Free/Rent/Buy, tier-1 TMDB links, verified tier-2 search links, cost lines), a "Your services" picker persisted per browser, a "Watchable now" lens across home rails, genre discover and search (partitioned, never hidden), and a nightly job that folds India availability into the catalogue and provider list. Shipped behind config.features.watchProviders, now flipped to true. Verified against live TMDB data (DDLJ, JioHotstar pricing, Watchable-now filtering) as well as the full typecheck/lint/vitest/build/bundle/e2e gate. Co-Authored-By: Claude Sonnet 5 Co-Authored-By: Claude Opus 4.8 (1M context) --- .env.example | 2 + .github/workflows/enrich-data.yml | 9 + README.md | 24 +- config/app.config.ts | 2 +- config/provider-links.ts | 41 +++ config/providers.ts | 30 ++ docs/DECISIONS.md | 46 ++++ docs/RUNBOOK.md | 11 + e2e/fixtures/data/catalog/popular-in.json | 36 ++- e2e/fixtures/data/catalog/trending.json | 51 +++- e2e/fixtures/data/providers-tmdb-in.json | 8 + e2e/fixtures/tmdb.ts | 107 ++++++++ e2e/smoke.spec.ts | 53 +++- package.json | 1 + public/providers-in.json | 88 ++++++ scripts/build-providers.ts | 181 ++++++++++++ scripts/lib/availability.test.ts | 127 +++++++++ scripts/lib/availability.ts | 73 +++++ scripts/lib/state.ts | 1 + src/app/Footer.tsx | 18 +- src/app/Header.tsx | 2 + src/app/overlays.tsx | 10 + src/app/queryClient.ts | 2 +- src/features/browse/GenrePage.tsx | 22 +- src/features/browse/HomePage.tsx | 135 +++++++-- src/features/browse/filters.test.ts | 20 ++ src/features/browse/filters.ts | 6 +- src/features/search/CommandPalette.tsx | 7 +- src/features/search/SearchPage.tsx | 80 +++++- src/features/search/partition.test.ts | 39 +++ src/features/search/partition.ts | 28 ++ src/features/title/TitlePage.tsx | 6 + src/features/watch/CostLine.tsx | 28 ++ src/features/watch/ProviderChip.tsx | 67 +++++ src/features/watch/ServicesButton.tsx | 27 ++ src/features/watch/ServicesDialog.tsx | 121 ++++++++ src/features/watch/WatchBlock.tsx | 181 ++++++++++++ src/features/watch/WatchableToggle.tsx | 60 ++++ src/lib/catalog-format.ts | 8 + src/lib/data.ts | 5 + src/lib/model.test.ts | 77 +++++- src/lib/model.ts | 25 +- src/lib/providers-format.test.ts | 320 ++++++++++++++++++++++ src/lib/providers-format.ts | 306 +++++++++++++++++++++ src/lib/providers.ts | 91 ++++++ src/lib/queries.ts | 17 +- src/lib/tmdb-types.ts | 28 ++ src/lib/tmdb.ts | 23 +- src/store/preferences.test.ts | 18 ++ src/store/preferences.ts | 50 +++- src/store/ui.ts | 11 +- src/ui/icons.tsx | 9 + 52 files changed, 2673 insertions(+), 65 deletions(-) create mode 100644 config/provider-links.ts create mode 100644 config/providers.ts create mode 100644 e2e/fixtures/data/providers-tmdb-in.json create mode 100644 public/providers-in.json create mode 100644 scripts/build-providers.ts create mode 100644 scripts/lib/availability.test.ts create mode 100644 scripts/lib/availability.ts create mode 100644 src/features/search/partition.test.ts create mode 100644 src/features/search/partition.ts create mode 100644 src/features/watch/CostLine.tsx create mode 100644 src/features/watch/ProviderChip.tsx create mode 100644 src/features/watch/ServicesButton.tsx create mode 100644 src/features/watch/ServicesDialog.tsx create mode 100644 src/features/watch/WatchBlock.tsx create mode 100644 src/features/watch/WatchableToggle.tsx create mode 100644 src/lib/providers-format.test.ts create mode 100644 src/lib/providers-format.ts create mode 100644 src/lib/providers.ts create mode 100644 src/store/preferences.test.ts diff --git a/.env.example b/.env.example index e0aa5bb..2468813 100644 --- a/.env.example +++ b/.env.example @@ -8,3 +8,5 @@ TMDB_READ_TOKEN= # OMDb key. Only the nightly job and local data scripts read it; it never reaches the browser. OMDB_API_KEY= + +# WATCHMODE_API_KEY= (optional, tier-3 deep links, not used yet) diff --git a/.github/workflows/enrich-data.yml b/.github/workflows/enrich-data.yml index 02223d7..8335dcd 100644 --- a/.github/workflows/enrich-data.yml +++ b/.github/workflows/enrich-data.yml @@ -48,6 +48,15 @@ jobs: DATA_DIR: data TMDB_READ_TOKEN: ${{ secrets.TMDB_READ_TOKEN }} + - name: Fold in where-to-watch availability (TMDB / JustWatch) + # A providers failure keeps last night's provider catalogue and publishes tonight's + # rails without `watch`; the UI treats that as unknown, never as unavailable. + continue-on-error: true + run: pnpm data:providers + env: + DATA_DIR: data + TMDB_READ_TOKEN: ${{ secrets.TMDB_READ_TOKEN }} + - name: Fetch ratings from OMDb (hard cap 1,000 requests) # A rejected OMDb key fails this step visibly but still publishes tonight's catalogue. continue-on-error: true diff --git a/README.md b/README.md index fd2f351..9439977 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # Interval What to watch, and where. A static film and series discovery site with IMDb, Rotten Tomatoes, -Metacritic and TMDB scores side by side. Phase 1 of [PLAN.md](PLAN.md). +Metacritic and TMDB scores side by side, plus where each title streams, rents or buys in India. +Phase 1 and Phase 2 of [PLAN.md](PLAN.md) (see [docs/phase-2-plan.md](docs/phase-2-plan.md)). Non-commercial by design: TMDB's free tier and OMDb's CC BY-NC licence both depend on it. @@ -32,6 +33,9 @@ OMDB_MAX_NEW=50 pnpm data:ratings # OMDb → public/data/ratings/NN.json | `pnpm e2e` | Playwright smoke tests against a GitHub-Pages-like server, TMDB mocked | | `pnpm lint` / `pnpm lint:fix` | Biome | | `pnpm check:bundle` | Fails if first-load JS exceeds 180 KB gzipped | +| `pnpm data:catalog` | TMDB → `public/data/catalog/*.json` | +| `pnpm data:providers` | TMDB watch/providers → `public/data/providers-tmdb-in.json`, folds `watch` into every catalogue entry | +| `pnpm data:ratings` | OMDb → `public/data/ratings/NN.json` | ## One-time setup (PLAN.md §16, Phase 0) @@ -56,6 +60,8 @@ OMDB_MAX_NEW=50 pnpm data:ratings # OMDb → public/data/ratings/NN.json ``` Nightly, 02:30 IST (.github/workflows/enrich-data.yml) build-catalog.ts TMDB lists → data/catalog/.json, resolves IMDb IDs + build-providers.ts TMDB watch/providers → data/providers-tmdb-in.json, + folds `watch` (India availability) into every catalogue entry build-ratings.ts OMDb, ≤500 new + ≤500 stale, hard cap 1,000 → data/ratings/00…99.json then folds scores into the catalogue entries force-push `data` branch, one squashed commit @@ -63,8 +69,10 @@ Deploy (on push to main, and after each nightly run) data branch → public/data → vite build → GitHub Pages and Cloudflare Pages ``` -The browser calls TMDB directly for search and title pages, and reads ratings from the -prebuilt shards. It never talks to OMDb and never sees the OMDb key. +The browser calls TMDB directly for search, title pages and per-result availability lookups, and +reads ratings from the prebuilt shards. It never talks to OMDb and never sees the OMDb key. A +title page's own availability comes bundled into the same TMDB detail call +(`append_to_response=watch/providers`), not a separate request. Search can surface titles the ratings index has not reached yet; they show "—" for IMDb and RT. Add their IMDb IDs to `scripts/wanted.txt` (or the workflow's manual-run input) and the @@ -73,8 +81,14 @@ next run fetches them first. ## Where things live - `config/app.config.ts`: name, regions, home genre rails, credibility floor, cache TTLs. -- `src/lib/`: TMDB client and types, ratings shard loader, shared formats. -- `src/features/`: browse (home, genre), search, title, watchlist. +- `config/providers.ts`, `config/provider-links.ts`: the streaming-service picker list, provider + ID aliases, and verified tier-2 search-link URLs (docs/phase-2-plan.md §4.4). +- `public/providers-in.json`: hand-maintained India subscription prices, re-verified quarterly + (docs/RUNBOOK.md). +- `src/lib/`: TMDB client and types, ratings shard loader, watch-providers formatting, shared formats. +- `src/features/`: browse (home, genre), search, title, watch (availability block, services + picker, Watchable-now toggle), watchlist. - `src/ui/`: the handful of primitives: poster card, rail, grid, scorecard and friends. - `scripts/`: the nightly pipeline and its tests. - `docs/DECISIONS.md`: why things are the way they are. `docs/RUNBOOK.md`: what breaks. + `docs/phase-2-plan.md`: the Phase 2 ("where to watch") implementation plan. diff --git a/config/app.config.ts b/config/app.config.ts index 5627076..c2c9e63 100644 --- a/config/app.config.ts +++ b/config/app.config.ts @@ -7,7 +7,7 @@ export const app = { tmdbStaleMinutes: 60, ratingsCacheTtlMinutes: 60, priceStaleAfterDays: 120, // hide prices older than this - features: { watchProviders: false, ai: false, groups: false }, + features: { watchProviders: true, ai: false, groups: false }, } as const; export type Region = (typeof app.regions)[number]; diff --git a/config/provider-links.ts b/config/provider-links.ts new file mode 100644 index 0000000..77e1118 --- /dev/null +++ b/config/provider-links.ts @@ -0,0 +1,41 @@ +// Provider site-search URLs: tier 2 (PLAN §8.3). Ordinary search links, not JustWatch data. +// Entries with checked: null are never shown. Click-test each from India; re-check quarterly. +// Last full check: 2026-09-28 (Prime Video, Apple TV only). +export interface ProviderLink { + label: string; + url: (query: string) => string; + checked: string | null; +} + +export const PROVIDER_LINKS: Readonly> = { + 119: { + label: 'Prime Video', + url: (q) => `https://www.primevideo.com/search?phrase=${encodeURIComponent(q)}`, + checked: '2026-09-28', + }, + 350: { + label: 'Apple TV', + url: (q) => `https://tv.apple.com/in/search?term=${encodeURIComponent(q)}`, + checked: '2026-09-28', + }, + 8: { + label: 'Netflix', + url: (q) => `https://www.netflix.com/search?q=${encodeURIComponent(q)}`, + checked: null, + }, + 2336: { + label: 'JioHotstar', + url: (q) => `https://www.jiohotstar.com/explore?search_query=${encodeURIComponent(q)}`, + checked: null, + }, + 237: { + label: 'Sony LIV', + url: (q) => `https://www.sonyliv.com/search?searchTerm=${encodeURIComponent(q)}`, + checked: null, + }, + 232: { + label: 'ZEE5', + url: (q) => `https://www.zee5.com/search?q=${encodeURIComponent(q)}`, + checked: null, + }, +}; diff --git a/config/providers.ts b/config/providers.ts new file mode 100644 index 0000000..bd50259 --- /dev/null +++ b/config/providers.ts @@ -0,0 +1,30 @@ +/** Canonical IDs offered in "Your services", in display order. Streaming only: rent/buy stores + * (2, 3, 10, 124, 192) are excluded because /discover evaluates providers and monetization + * independently (docs/phase-2-plan.md §2.4). Last checked against TMDB 2026-09-28. */ +export const PICKER_PROVIDERS: ReadonlyArray<{ id: number; name: string }> = [ + { id: 8, name: 'Netflix' }, + { id: 119, name: 'Prime Video' }, + { id: 2336, name: 'JioHotstar' }, + { id: 232, name: 'ZEE5' }, + { id: 237, name: 'Sony LIV' }, + { id: 350, name: 'Apple TV' }, + { id: 309, name: 'Sun NXT' }, + { id: 532, name: 'aha' }, + { id: 315, name: 'Hoichoi' }, + { id: 482, name: 'ManoramaMAX' }, + { id: 561, name: 'Lionsgate Play' }, + { id: 510, name: 'Discovery+' }, + { id: 11, name: 'MUBI' }, + { id: 283, name: 'Crunchyroll' }, + { id: 437, name: 'Hungama Play' }, + { id: 474, name: 'ShemarooMe' }, + { id: 476, name: 'EPIC ON' }, + { id: 1898, name: 'Amazon MX Player (free)' }, +]; + +/** Variant → canonical. Owning the canonical ID covers the variant. Never alias channels. */ +export const PROVIDER_ALIASES: Readonly> = { + 2100: 119, // Amazon Prime Video with Ads + 175: 8, // Netflix Kids + 515: 1898, // MX Player (pre-2024 brand) → Amazon MX Player +}; diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 73708ff..8b1494b 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -136,4 +136,50 @@ doesn't depend on where the bar is set, only on which titles are being considere were nearly merged into one query keyed on the thresholds too; that would have re-run the external ID lookups on every dropdown change for no reason, so they were split. +## 2026-09-28 · Phase 2: where to watch in India + +Full research and rationale in `docs/phase-2-plan.md`. The load-bearing decisions: + +1. **Availability comes appended to the title detail call, not a separate request.** + `append_to_response=watch/providers` on the same `/movie|tv/{id}` call TMDB already makes for + a title page adds ~2 KB gzip and zero extra round trips, with no second loading state for the + block to handle. +2. **`checked:false` is unknown, never "not available."** A failed or not-yet-attempted lookup is + absent from the UI (the block renders nothing, a filtered rail simply excludes the title, + search puts it under "Couldn't check") — the copy never claims a title *isn't* available when + the honest answer is "we don't know." +3. **"Watchable now" means stream ∪ free ∪ ads intersects your ticked services.** Free/ad-supported + apps count only when the viewer has actually ticked them, so the catalogue filter (client-side + `isWatchableWith`) and `/discover`'s server-side filter agree on the same definition. +4. **The picker only offers services that stream.** Rent/buy stores (Apple TV Store, Google Play, + YouTube, Amazon Video, BookMyShow) are left out of `PICKER_PROVIDERS`, because TMDB's `/discover` + evaluates `with_watch_providers` and `with_watch_monetization_types` independently rather than + per-provider — a store ticked as "owned" would produce false-positive "watchable" matches on + titles that are only rentable there. +5. **Plan variants alias to their parent; channels never do.** `config/providers.ts`'s + `PROVIDER_ALIASES` maps 2100→119 (Prime Video with Ads), 175→8 (Netflix Kids) and 515→1898 + (the old MX Player brand), so owning the parent plan marks the variant as owned too. Add-on + "channels" (e.g. an Apple TV Amazon Channel) are deliberately never aliased — they are separate + subscriptions a person may not have. +6. **Watchable-now is a persisted personal preference, not a URL parameter.** Unlike genre filters, + what a person can watch depends on services only they know about, so `usePreferences(). + watchableOnly` lives in `localStorage`, never in a shareable link. +7. **Search results are partitioned, not filtered.** `/search/multi` has no provider parameter, so + hiding "not on your services" results would require guessing; instead, each visible result gets + its own `/watch/providers` lookup (≤20 per page, cached) and the same page is split into "On + your services," "Couldn't check" and "Not on your services" sections, in that order, nothing + hidden. +8. **Prices and tier-2 search links are hidden by default, shown only once verified.** A cost line + needs `verified` set and less than `priceStaleAfterDays` (120) old; a provider search link needs + a non-null `checked` date in `config/provider-links.ts`. Both default to hidden rather than + risking a stale or unconfirmed claim. +9. **The region switcher lives inside the availability block, independent of the header's region + select.** The header's existing selector means "which Popular list," a pre-existing and + unrelated concept; coupling the two would silently change one control's meaning when the other + changes. +10. **JustWatch attribution sits inside every availability block, and next to the Watchable-now + toggle when it's on, not only in the footer.** TMDB's own guidance for this data is "a + reference or logo on each media item," so the line travels with the data everywhere it + appears, with a single footer mention besides. + diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index f4ca29c..9996512 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -12,6 +12,12 @@ PLAN.md §12, trimmed to what exists in Phase 1. Extend it as phases land. - Re-read TMDB's API terms. The attribution requirements are the ones that get keys revoked. - Confirm the footer still shows the TMDB logo and notice. +- Re-verify every entry in `public/providers-in.json` against its `source` URL and bump + `verified` to today (ZEE5 ships unverified — check it first). Never backdate `verified`. +- Click every `config/provider-links.ts` URL from a browser in India; set `checked` to today or + to `null` if it no longer works. +- Confirm the JustWatch attribution line is still present inside the availability block and in + the footer. ## Things that will break @@ -24,6 +30,10 @@ PLAN.md §12, trimmed to what exists in Phase 1. Extend it as phases land. | Every page says TMDB rejected the token | Build ran without `TMDB_READ_TOKEN`, or the v3 key was used | Set the repository variable to the v4 read token and redeploy | | Deep links 404 on GitHub Pages | The build ran without `SPA_404=true` | It is set in `deploy-pages.yml`; check nobody removed it | | TMDB 429s | Something is looping | Look for new code that fetches outside TanStack Query | +| Where to watch missing on every title | TMDB watch-providers outage or a revoked token | Confirm the block is absent, not "unavailable" (that's correct behaviour); check the "Watch providers" step summary for the run | +| Watchable now empty on home with services picked | The providers step failed last night | Check the "Watch providers" summary; rerun Enrich data | +| Prices vanished from the Stream group | Entries older than `priceStaleAfterDays` (120) | Re-verify `public/providers-in.json` and bump `verified` | +| A service disappears from the picker's logos | TMDB renamed or re-ID'd it (Hotstar 122 → JioHotstar 2336 already happened once) | Update `config/providers.ts` with the new ID/name | ## Knobs for the nightly job @@ -36,3 +46,4 @@ Environment variables read by `scripts/build-*.ts`. Change them in `enrich-data. | `STALE_AFTER_DAYS` | 30 | Age at which a record is refreshed | | `OMDB_PACING_MS` | 300 | Delay between OMDb calls | | `BACKLOG_PAGES` | 10 | Pages per backlog list per night (20 titles each) | +| `PROVIDERS_RPS` | 7 | Requests/second for the watch-providers nightly step | diff --git a/e2e/fixtures/data/catalog/popular-in.json b/e2e/fixtures/data/catalog/popular-in.json index 5acf73f..1203390 100644 --- a/e2e/fixtures/data/catalog/popular-in.json +++ b/e2e/fixtures/data/catalog/popular-in.json @@ -13,7 +13,17 @@ "genres": [35, 18], "lang": "hi", "imdb": "tt1187043", - "scores": { "i": 8.4, "rt": 100 } + "scores": { "i": 8.4, "rt": 100 }, + "watch": { + "checked": true, + "region": "IN", + "link": "https://www.themoviedb.org/movie/20453/watch?locale=IN", + "stream": [], + "free": [], + "ads": [], + "rent": [3, 192], + "buy": [3, 192] + } }, { "id": 19404, @@ -26,7 +36,17 @@ "genres": [35, 18, 10749], "lang": "hi", "imdb": "tt0112870", - "scores": { "i": 8, "rt": 92 } + "scores": { "i": 8, "rt": 92 }, + "watch": { + "checked": true, + "region": "IN", + "link": "https://www.themoviedb.org/movie/19404/watch?locale=IN", + "stream": [8], + "free": [], + "ads": [], + "rent": [], + "buy": [] + } }, { "id": 577922, @@ -39,7 +59,17 @@ "genres": [28, 53, 878], "lang": "en", "imdb": "tt6723592", - "scores": { "i": 7.3, "rt": 69 } + "scores": { "i": 7.3, "rt": 69 }, + "watch": { + "checked": true, + "region": "IN", + "link": "https://www.themoviedb.org/movie/577922/watch?locale=IN", + "stream": [8, 119, 2100], + "free": [], + "ads": [], + "rent": [], + "buy": [] + } } ] } diff --git a/e2e/fixtures/data/catalog/trending.json b/e2e/fixtures/data/catalog/trending.json index 53779be..709962d 100644 --- a/e2e/fixtures/data/catalog/trending.json +++ b/e2e/fixtures/data/catalog/trending.json @@ -16,7 +16,17 @@ "genres": [35, 18, 10749], "lang": "hi", "imdb": "tt0112870", - "scores": { "i": 8, "rt": 92 } + "scores": { "i": 8, "rt": 92 }, + "watch": { + "checked": true, + "region": "IN", + "link": "https://www.themoviedb.org/movie/19404/watch?locale=IN", + "stream": [8], + "free": [], + "ads": [], + "rent": [], + "buy": [] + } }, { "id": 577922, @@ -31,7 +41,17 @@ "genres": [28, 53, 878], "lang": "en", "imdb": "tt6723592", - "scores": { "i": 7.3, "rt": 69 } + "scores": { "i": 7.3, "rt": 69 }, + "watch": { + "checked": true, + "region": "IN", + "link": "https://www.themoviedb.org/movie/577922/watch?locale=IN", + "stream": [8, 119, 2100], + "free": [], + "ads": [], + "rent": [], + "buy": [] + } }, { "id": 9001, @@ -45,7 +65,17 @@ "votes": 300, "genres": [35, 18], "lang": "hi", - "imdb": null + "imdb": null, + "watch": { + "checked": true, + "region": "IN", + "link": "https://www.themoviedb.org/tv/9001/watch?locale=IN", + "stream": [119, 2100], + "free": [], + "ads": [], + "rent": [], + "buy": [] + } }, { "id": 20453, @@ -60,7 +90,17 @@ "genres": [35, 18], "lang": "hi", "imdb": "tt1187043", - "scores": { "i": 8.4, "rt": 100 } + "scores": { "i": 8.4, "rt": 100 }, + "watch": { + "checked": true, + "region": "IN", + "link": "https://www.themoviedb.org/movie/20453/watch?locale=IN", + "stream": [], + "free": [], + "ads": [], + "rent": [3, 192], + "buy": [3, 192] + } }, { "id": 9002, @@ -74,7 +114,8 @@ "votes": 180, "genres": [53, 18], "lang": "ml", - "imdb": null + "imdb": null, + "watch": { "checked": false } }, { "id": 9003, diff --git a/e2e/fixtures/data/providers-tmdb-in.json b/e2e/fixtures/data/providers-tmdb-in.json new file mode 100644 index 0000000..56b1f73 --- /dev/null +++ b/e2e/fixtures/data/providers-tmdb-in.json @@ -0,0 +1,8 @@ +[ + { "id": 8, "name": "Netflix", "logo": "/netflix.png", "priority": 0 }, + { "id": 119, "name": "Amazon Prime Video", "logo": "/prime.png", "priority": 1 }, + { "id": 350, "name": "Apple TV", "logo": "/apple.png", "priority": 2 }, + { "id": 2336, "name": "JioHotstar", "logo": "/jiohotstar.png", "priority": 3 }, + { "id": 232, "name": "Zee5", "logo": "/zee5.png", "priority": 7 }, + { "id": 237, "name": "Sony Liv", "logo": "/sonyliv.png", "priority": 10 } +] diff --git a/e2e/fixtures/tmdb.ts b/e2e/fixtures/tmdb.ts index aacc71c..9f57491 100644 --- a/e2e/fixtures/tmdb.ts +++ b/e2e/fixtures/tmdb.ts @@ -73,6 +73,113 @@ export const ddljDetail = { ], }, external_ids: { imdb_id: 'tt0112870' }, + 'watch/providers': { + results: { + IN: { + link: 'https://www.themoviedb.org/movie/19404/watch?locale=IN', + flatrate: [ + { + provider_id: 8, + provider_name: 'Netflix', + logo_path: '/netflix.png', + display_priority: 0, + }, + ], + rent: [ + { + provider_id: 2, + provider_name: 'Apple TV Store', + logo_path: '/apple.png', + display_priority: 5, + }, + { + provider_id: 3, + provider_name: 'Google Play Movies', + logo_path: '/google.png', + display_priority: 8, + }, + { + provider_id: 192, + provider_name: 'YouTube', + logo_path: '/youtube.png', + display_priority: 11, + }, + ], + buy: [ + { + provider_id: 2, + provider_name: 'Apple TV Store', + logo_path: '/apple.png', + display_priority: 5, + }, + { + provider_id: 3, + provider_name: 'Google Play Movies', + logo_path: '/google.png', + display_priority: 8, + }, + { + provider_id: 192, + provider_name: 'YouTube', + logo_path: '/youtube.png', + display_priority: 11, + }, + ], + }, + // A second region with listings, so the region select appears. + GB: { + link: 'https://www.themoviedb.org/movie/19404/watch?locale=GB', + flatrate: [ + { + provider_id: 8, + provider_name: 'Netflix', + logo_path: '/netflix.png', + display_priority: 0, + }, + ], + }, + }, + }, +}; + +/** The standalone `/movie/{id}/watch/providers` response — same data as the append above, used + * by search's per-result lookups (docs/phase-2-plan.md §3.5). */ +export const ddljProvidersOnly = { + id: 19404, + results: ddljDetail['watch/providers'].results, +}; + +/** Panchayat (tv 9001 in the catalog fixtures): Prime Video appears in both `flatrate` and its + * "with Ads" variant, per the real response documented in docs/phase-2-plan.md §2.1. */ +export const panchayatProviders = { + id: 9001, + results: { + IN: { + link: 'https://www.themoviedb.org/tv/9001/watch?locale=IN', + flatrate: [ + { + provider_id: 119, + provider_name: 'Amazon Prime Video', + logo_path: '/prime.png', + display_priority: 1, + }, + { + provider_id: 2100, + provider_name: 'Amazon Prime Video with Ads', + logo_path: '/prime.png', + display_priority: 71, + }, + ], + free: [ + { + provider_id: 119, + provider_name: 'Amazon Prime Video', + logo_path: '/prime.png', + display_priority: 1, + }, + ], + }, + }, }; export const tenetSearch = { diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index f0e8d3f..27d6cf1 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -1,5 +1,12 @@ import { expect, type Page, test } from '@playwright/test'; -import { comedyDiscover, ddljDetail, emptyPage, tenetSearch } from './fixtures/tmdb'; +import { + comedyDiscover, + ddljDetail, + ddljProvidersOnly, + emptyPage, + panchayatProviders, + tenetSearch, +} from './fixtures/tmdb'; const CORS = { 'access-control-allow-origin': '*', @@ -19,6 +26,9 @@ async function mockTmdb(page: Page) { const url = new URL(request.url()); let body: unknown = emptyPage; if (url.pathname === '/3/movie/19404') body = ddljDetail; + else if (url.pathname === '/3/movie/19404/watch/providers') body = ddljProvidersOnly; + else if (url.pathname === '/3/tv/9001/watch/providers') body = panchayatProviders; + else if (url.pathname.endsWith('/watch/providers')) body = { results: {} }; else if (url.pathname === '/3/search/multi') { body = /ten/i.test(url.searchParams.get('query') ?? '') ? tenetSearch : emptyPage; } else if (url.pathname === '/3/discover/movie') body = comedyDiscover; @@ -42,8 +52,11 @@ test('home renders populated rails and the TMDB notice', async ({ page }) => { await expect(popular.getByRole('link')).toHaveCount(3); await expect(page.getByRole('link', { name: 'See details' })).toBeVisible(); await expect( - page.getByText('This product uses the TMDB API but is not endorsed or certified by TMDB.'), + page.getByText( + 'This website uses TMDB and the TMDB APIs but is not endorsed, certified, or otherwise approved by TMDB.', + ), ).toBeVisible(); + await expect(page.getByText('Where-to-watch listings: availability data by')).toBeVisible(); }); test('search from the command palette returns results', async ({ page }) => { @@ -82,6 +95,14 @@ test('a title page shows the scorecard, with an em dash for a missing score', as 'href', 'https://www.youtube.com/watch?v=trailer-key', ); + + const watch = page.getByRole('region', { name: 'Where to watch' }); + await expect(watch).toContainText('Netflix'); + await expect(watch).toContainText('Availability data by JustWatch.'); + await expect(watch.getByRole('link', { name: 'See every option on TMDB' })).toHaveAttribute( + 'href', + 'https://www.themoviedb.org/movie/19404/watch?locale=IN', + ); }); test('deep links load directly through the 404.html fallback', async ({ page }) => { @@ -96,3 +117,31 @@ test('deep links load directly through the 404.html fallback', async ({ page }) await expect(page.getByLabel('Minimum rating')).toHaveValue('7'); await expect(page.getByRole('link', { name: /^Andaz Apna Apna/ })).toBeVisible(); }); + +test('services and Watchable now filters rails to what you can stream', async ({ page }) => { + await page.goto('./'); + + await page.getByRole('button', { name: /Your services/ }).click(); + const dialog = page.getByRole('dialog', { name: 'Your streaming services' }); + await dialog.getByRole('checkbox', { name: 'Netflix' }).check(); + await dialog.getByRole('button', { name: 'Done' }).click(); + + await page + .getByRole('region', { name: "Everyone's already seen this" }) + .getByRole('link', { name: /Dilwale Dulhania Le Jayenge/ }) + .click(); + await expect(page.getByText('You have this')).toBeVisible(); + await expect(page.getByText('Availability data by JustWatch.')).toBeVisible(); + + await page.goto('./'); + await page.getByRole('switch', { name: 'Watchable now' }).click(); + const trending = page.getByRole('region', { name: "Everyone's already seen this" }); + await expect(trending.getByRole('link')).toHaveCount(2); + await expect(trending.getByRole('link', { name: /Dilwale Dulhania Le Jayenge/ })).toBeVisible(); + await expect(trending.getByRole('link', { name: /^Tenet/ })).toBeVisible(); + await expect(page.getByText('not available', { exact: false })).toHaveCount(0); + + await page.reload(); + await expect(page.getByRole('switch', { name: 'Watchable now' })).toBeChecked(); + await expect(trending.getByRole('link')).toHaveCount(2); +}); diff --git a/package.json b/package.json index b1c975c..436586d 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "e2e": "playwright test", "check:bundle": "tsx scripts/check-bundle.ts", "data:catalog": "tsx scripts/build-catalog.ts", + "data:providers": "tsx scripts/build-providers.ts", "data:ratings": "tsx scripts/build-ratings.ts", "data:pull": "sh scripts/pull-data.sh" }, diff --git a/public/providers-in.json b/public/providers-in.json new file mode 100644 index 0000000..d9fbdfb --- /dev/null +++ b/public/providers-in.json @@ -0,0 +1,88 @@ +{ + "version": 1, + "region": "IN", + "providers": [ + { + "provider_id": 8, + "name": "Netflix", + "plans": [ + { + "name": "Mobile", + "inr": 149, + "per": "month", + "ads": false, + "note": "Phone or tablet only" + }, + { "name": "Basic", "inr": 199, "per": "month", "ads": false }, + { "name": "Standard", "inr": 499, "per": "month", "ads": false }, + { "name": "Premium", "inr": 649, "per": "month", "ads": false } + ], + "note": "Included with some Jio and Airtel plans", + "source": "https://help.netflix.com/en/node/24926/in", + "verified": "2026-09-28" + }, + { + "provider_id": 119, + "name": "Prime Video", + "plans": [ + { "name": "Prime", "inr": 299, "per": "month", "ads": true }, + { "name": "Prime", "inr": 599, "per": "quarter", "ads": true }, + { "name": "Prime", "inr": 1499, "per": "year", "ads": true }, + { "name": "Prime Lite", "inr": 799, "per": "year", "ads": true, "note": "One device, HD" } + ], + "note": "Ad-free is ₹129 a month extra. Prime also includes shopping benefits", + "source": "https://www.amazon.in/gp/help/customer/display.html?nodeId=G34EUPKVMYFW8N2U", + "verified": "2026-09-28" + }, + { + "provider_id": 2336, + "name": "JioHotstar", + "plans": [ + { + "name": "Mobile", + "inr": 79, + "per": "month", + "ads": true, + "note": "One phone; Hollywood titles need a ₹49 add-on" + }, + { "name": "Super", "inr": 149, "per": "month", "ads": true }, + { "name": "Premium", "inr": 299, "per": "month", "ads": false }, + { "name": "Premium", "inr": 2199, "per": "year", "ads": false } + ], + "note": "Often bundled with Jio and Airtel plans", + "source": "https://techcrunch.com/2026/09/01/reliances-jiohotstar-takes-its-streaming-empire-global-without-sports/", + "verified": "2026-09-28" + }, + { + "provider_id": 237, + "name": "Sony LIV", + "plans": [ + { "name": "Premium", "inr": 399, "per": "month", "ads": false }, + { "name": "Premium", "inr": 1499, "per": "year", "ads": false }, + { "name": "Mobile Only", "inr": 699, "per": "year", "ads": false } + ], + "note": "Sport and live shows still carry ads", + "source": "https://helpdev.sonyliv.com/categories/cat-subscription/articles/what-are-the-types-of-subscription-available-on-liv-how-much-does-sony-liv-cost-1", + "verified": "2026-09-28" + }, + { + "provider_id": 350, + "name": "Apple TV", + "plans": [{ "name": "iCloud+ 50 GB", "inr": 75, "per": "month", "ads": false }], + "note": "No longer sold on its own in India; comes with every iCloud+ plan", + "source": "https://support.apple.com/en-in/108047", + "verified": "2026-09-28" + }, + { + "provider_id": 232, + "name": "ZEE5", + "plans": [ + { "name": "All languages", "inr": 299, "per": "month", "ads": true }, + { "name": "Hindi pack", "inr": 199, "per": "month", "ads": true } + ], + "note": "Single-language packs are cheaper", + "source": "https://www.zee5.com/global/blog/zee5-annual-vs-monthly-ott-subscriptions-which-is-better-for-indian-language-viewers/", + "verified": null + } + ] +} diff --git a/scripts/build-providers.ts b/scripts/build-providers.ts new file mode 100644 index 0000000..32dedf5 --- /dev/null +++ b/scripts/build-providers.ts @@ -0,0 +1,181 @@ +/** + * Nightly step (PLAN.md §7.3, docs/phase-2-plan.md §6): fetch the India watch-provider + * catalogue, look up availability for every title on show, and fold `watch` (IN `Availability`) + * into every catalogue rail. Runs between the catalogue and ratings steps: a bug here must never + * stop tonight's catalogue from publishing (`continue-on-error: true` in the workflow), and it + * runs regardless of `app.config.ts`'s `features.watchProviders` flag so data is ready before + * the UI flips it on. + */ +import { readdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import type { CatalogRail, DataMeta } from '../src/lib/catalog-format'; +import { type MediaType, titleKey } from '../src/lib/model'; +import type { Availability } from '../src/lib/providers-format'; +import { toAvailability, toProviderCatalog } from '../src/lib/providers-format'; +import type { TmdbProviderCatalogEntry, TmdbWatchProviders } from '../src/lib/tmdb-types'; +import { + type AvailabilityCache, + foldIntoRails, + isOutage, + pruneCache, + resolveAvailability, +} from './lib/availability'; +import { DATA_DIR, env, envInt, stepSummary, todayUtc } from './lib/env'; +import { readJson, writeJson } from './lib/files'; +import { HttpError, mapLimit } from './lib/http'; +import { statePaths } from './lib/state'; +import { createTmdbClient } from './lib/tmdb'; + +const REGION = 'IN'; +const PROVIDER_CATALOG_FILE = 'providers-tmdb-in.json'; + +interface TitleRef { + type: MediaType; + id: number; +} + +interface RailFile { + path: string; + rail: CatalogRail; +} + +interface ProviderListResponse { + results: TmdbProviderCatalogEntry[]; +} + +async function readRailFiles(dataDir: string): Promise { + const dir = join(dataDir, 'catalog'); + const files = (await readdir(dir).catch(() => [])).filter((f) => f.endsWith('.json')); + const railFiles: RailFile[] = []; + for (const file of files) { + const path = join(dir, file); + const rail = await readJson(path, null); + if (rail) railFiles.push({ path, rail }); + } + return railFiles; +} + +function uniqueTitles(railFiles: RailFile[]): TitleRef[] { + const byKey = new Map(); + for (const { rail } of railFiles) { + for (const item of rail.items) { + byKey.set(titleKey(item.type, item.id), { type: item.type, id: item.id }); + } + } + return [...byKey.values()]; +} + +async function main() { + const token = env('TMDB_READ_TOKEN') ?? env('VITE_TMDB_READ_TOKEN'); + if (!token) { + console.warn( + '::warning::Missing TMDB_READ_TOKEN (or VITE_TMDB_READ_TOKEN); skipping watch providers.', + ); + process.exit(0); + } + + const tmdb = createTmdbClient(token, envInt('PROVIDERS_RPS', 7)); + const today = todayUtc(); + + // 1. Provider catalogue. A failed fetch keeps last night's file untouched. + let providerCatalogCount = 0; + let providerCatalogOk = false; + try { + const [movies, tv] = await Promise.all([ + tmdb.get('/watch/providers/movie', { watch_region: REGION }), + tmdb.get('/watch/providers/tv', { watch_region: REGION }), + ]); + const catalog = toProviderCatalog([movies.results, tv.results], REGION); + await writeJson(join(DATA_DIR, PROVIDER_CATALOG_FILE), catalog); + providerCatalogCount = catalog.length; + providerCatalogOk = true; + } catch (error) { + console.warn(`::warning::Provider catalogue fetch failed: ${String(error)}`); + } + + // 2. Titles: every unique {type,id} across every rail file (~306 in production). + const railFiles = await readRailFiles(DATA_DIR); + const titles = uniqueTitles(railFiles); + + // 3. Lookups. Tonight's cache only gets genuine checked availability, never a guess. + const cachePath = statePaths(DATA_DIR).availability; + const cache = await readJson(cachePath, {}); + const byKey = new Map(); + const failedKeys: string[] = []; + + await mapLimit(titles, 4, async (title) => { + const key = titleKey(title.type, title.id); + try { + const raw = await tmdb.get(`/${title.type}/${title.id}/watch/providers`); + const availability = toAvailability(raw, REGION); + if (availability.checked) cache[key] = { a: availability, u: today }; + byKey.set(key, availability); + } catch (error) { + if (error instanceof HttpError && error.status === 401) { + console.error('::error::TMDB rejected the token (401) fetching watch providers.'); + process.exit(1); + } + failedKeys.push(key); + } + }); + + // 4. Outage guard: widen the fallback window rather than publishing mass "unknown". + const outage = isOutage(failedKeys.length, titles.length); + if (outage) console.warn('::warning::TMDB watch providers looks down'); + const fallbackDays = outage ? 30 : 7; + for (const key of failedKeys) { + byKey.set(key, resolveAvailability(null, cache[key], today, fallbackDays)); + } + + // 5. Fold availability into every rail and write it back. + const foldedRails = foldIntoRails( + railFiles.map((rf) => rf.rail), + byKey, + ); + await Promise.all( + railFiles.map((rf, index) => writeJson(rf.path, foldedRails[index] ?? rf.rail)), + ); + + // 6. Prune the fallback cache to titles seen in the last 30 days. + const seenKeys = new Set(titles.map((t) => titleKey(t.type, t.id))); + const prunedCache = pruneCache(cache, seenKeys, today, 30); + await writeJson(cachePath, prunedCache); + + // 7. Meta and summary. + let checkedCount = 0; + for (const availability of byKey.values()) { + if (availability.checked) checkedCount++; + } + const fromCache = failedKeys.filter((key) => byKey.get(key)?.checked).length; + const uncheckedCount = titles.length - checkedCount; + + const metaPath = join(DATA_DIR, 'meta.json'); + const meta = await readJson(metaPath, { generated: new Date().toISOString() }); + meta.generated = new Date().toISOString(); + meta.providers = { + titles: titles.length, + checked: checkedCount, + fromCache, + unchecked: uncheckedCount, + tmdbRequests: tmdb.requests, + catalog: providerCatalogCount, + }; + await writeJson(metaPath, meta); + + const lines = [ + `Provider catalogue: ${providerCatalogCount} entries` + + (providerCatalogOk ? '' : ' (fetch failed; kept last night’s file)'), + `Titles: ${titles.length}, checked ${checkedCount} (${fromCache} from cache), ` + + `unchecked ${uncheckedCount}`, + `TMDB requests: ${tmdb.requests}` + + (failedKeys.length ? `, ${failedKeys.length} lookups failed` : '') + + (outage ? ' — outage mode (30-day fallback)' : ''), + ]; + console.log(lines.join('\n')); + await stepSummary(`### Watch providers\n\n${lines.map((l) => `- ${l}`).join('\n')}\n`); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/scripts/lib/availability.test.ts b/scripts/lib/availability.test.ts new file mode 100644 index 0000000..b71a540 --- /dev/null +++ b/scripts/lib/availability.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from 'vitest'; +import type { CatalogRail } from '../../src/lib/catalog-format'; +import type { CardScores, TitleSummary } from '../../src/lib/model'; +import type { CheckedAvailability } from '../../src/lib/providers-format'; +import { UNCHECKED } from '../../src/lib/providers-format'; +import { + type AvailabilityCache, + foldIntoRails, + isOutage, + pruneCache, + resolveAvailability, +} from './availability'; + +const TODAY = '2026-09-28'; + +function daysBefore(isoDate: string, days: number): string { + const date = new Date(`${isoDate}T00:00:00Z`); + date.setUTCDate(date.getUTCDate() - days); + return date.toISOString().slice(0, 10); +} + +function checked(stream: number[] = [8]): CheckedAvailability { + return { + checked: true, + region: 'IN', + link: null, + stream, + free: [], + ads: [], + rent: [], + buy: [], + }; +} + +describe('resolveAvailability', () => { + it('a fresh lookup wins over the cache', () => { + const fresh = checked([119]); + const cached = { a: checked([8]), u: TODAY }; + expect(resolveAvailability(fresh, cached, TODAY, 7)).toBe(fresh); + }); + + it('a failed lookup with a 3-day-old cache entry falls back to the cache (within 7 days)', () => { + const cached = { a: checked([8]), u: daysBefore(TODAY, 3) }; + expect(resolveAvailability(null, cached, TODAY, 7)).toEqual(cached.a); + }); + + it('a failed lookup with a 10-day-old cache entry is unknown (past the 7-day window)', () => { + const cached = { a: checked([8]), u: daysBefore(TODAY, 10) }; + expect(resolveAvailability(null, cached, TODAY, 7)).toEqual(UNCHECKED); + }); + + it('outage mode (fallbackDays 30) still reuses a 10-day-old cache entry', () => { + const cached = { a: checked([8]), u: daysBefore(TODAY, 10) }; + expect(resolveAvailability(null, cached, TODAY, 30)).toEqual(cached.a); + }); + + it('no cache at all is unknown', () => { + expect(resolveAvailability(null, undefined, TODAY, 7)).toEqual(UNCHECKED); + }); +}); + +describe('isOutage', () => { + it('is true only once more than half of tonight’s lookups failed', () => { + expect(isOutage(51, 100)).toBe(true); + expect(isOutage(50, 100)).toBe(false); + expect(isOutage(0, 0)).toBe(false); + }); +}); + +describe('foldIntoRails', () => { + it('sets watch from byKey and preserves scores and every other field', () => { + const scores: CardScores = { i: 8.1, rt: 91 }; + const item: TitleSummary = { + id: 19404, + type: 'movie', + title: 'Dilwale Dulhania Le Jayenge', + year: 1995, + poster: '/poster.png', + vote: 8.7, + votes: 4200, + genres: [35, 18], + lang: 'hi', + imdb: 'tt0112870', + scores, + }; + const rail: CatalogRail = { + id: 'trending', + generated: '2026-09-28T00:00:00.000Z', + items: [item], + }; + const availability = checked([8]); + const byKey = new Map([['movie:19404', availability]]); + + const [folded] = foldIntoRails([rail], byKey); + expect(folded?.items).toEqual([{ ...item, watch: availability }]); + }); + + it('falls back to UNCHECKED for a title missing from byKey', () => { + const item: TitleSummary = { + id: 1, + type: 'movie', + title: 'Unknown', + year: null, + poster: null, + vote: 0, + votes: 0, + genres: [], + lang: 'en', + }; + const rail: CatalogRail = { id: 'trending', generated: '', items: [item] }; + const [folded] = foldIntoRails([rail], new Map()); + expect(folded?.items[0]?.watch).toEqual(UNCHECKED); + }); +}); + +describe('pruneCache', () => { + it('drops entries older than maxAgeDays that were not seen tonight', () => { + const cache: AvailabilityCache = { + 'movie:1': { a: checked([8]), u: daysBefore(TODAY, 31) }, // unseen, too old: dropped + 'movie:2': { a: checked([8]), u: daysBefore(TODAY, 29) }, // unseen, within window: kept + 'movie:3': { a: checked([8]), u: daysBefore(TODAY, 40) }, // seen tonight: kept regardless + }; + const seenKeys = new Set(['movie:3']); + const pruned = pruneCache(cache, seenKeys, TODAY, 30); + expect(Object.keys(pruned).sort()).toEqual(['movie:2', 'movie:3']); + }); +}); diff --git a/scripts/lib/availability.ts b/scripts/lib/availability.ts new file mode 100644 index 0000000..6f39253 --- /dev/null +++ b/scripts/lib/availability.ts @@ -0,0 +1,73 @@ +/** + * Pure pipeline helpers for the nightly watch-providers step (docs/phase-2-plan.md §5.1, §6.2, + * §8.1). No network or filesystem access here: everything is importable and unit-testable on + * its own, and `scripts/build-providers.ts` is the only caller. + */ +import type { CatalogRail } from '../../src/lib/catalog-format'; +import { titleKey } from '../../src/lib/model'; +import type { Availability, CheckedAvailability } from '../../src/lib/providers-format'; +import { UNCHECKED } from '../../src/lib/providers-format'; + +/** "movie:19404" → last successful lookup. Fallback only; tonight's lookup always wins. */ +export type AvailabilityCache = Record; + +function daysBetween(from: string, to: string): number { + const fromMs = Date.parse(`${from}T00:00:00Z`); + const toMs = Date.parse(`${to}T00:00:00Z`); + return Math.floor((toMs - fromMs) / 86_400_000); +} + +/** + * Tonight's lookup always wins when present. On failure (`fresh: null`), reuse the cached + * availability while it is at most `fallbackDays` old; older or missing cache degrades to + * `{checked:false}` rather than guessing. + */ +export function resolveAvailability( + fresh: CheckedAvailability | null, + cached: { a: CheckedAvailability; u: string } | undefined, + today: string, + fallbackDays: number, +): Availability { + if (fresh) return fresh; + if (cached && daysBetween(cached.u, today) <= fallbackDays) return cached.a; + return UNCHECKED; +} + +/** Sets every item's `watch` from `byKey` (keyed by `titleKey`), leaving every other field as-is. */ +export function foldIntoRails( + rails: CatalogRail[], + byKey: Map, +): CatalogRail[] { + return rails.map((rail) => ({ + ...rail, + items: rail.items.map((item) => ({ + ...item, + watch: byKey.get(titleKey(item.type, item.id)) ?? UNCHECKED, + })), + })); +} + +/** + * Drops cache entries for titles that are both absent from tonight's catalogue (`seenKeys`) and + * older than `maxAgeDays`. Entries still on show are kept however old, so a title that briefly + * fails lookups keeps its fallback. + */ +export function pruneCache( + cache: AvailabilityCache, + seenKeys: ReadonlySet, + today: string, + maxAgeDays: number, +): AvailabilityCache { + const pruned: AvailabilityCache = {}; + for (const [key, entry] of Object.entries(cache)) { + if (seenKeys.has(key) || daysBetween(entry.u, today) <= maxAgeDays) { + pruned[key] = entry; + } + } + return pruned; +} + +/** True once more than half of tonight's per-title lookups failed: treat TMDB as down tonight. */ +export function isOutage(failures: number, total: number): boolean { + return failures > total / 2; +} diff --git a/scripts/lib/state.ts b/scripts/lib/state.ts index 51e6b7d..3d3ba61 100644 --- a/scripts/lib/state.ts +++ b/scripts/lib/state.ts @@ -24,5 +24,6 @@ export function statePaths(dataDir: string) { idmap: join(dir, 'idmap.json'), backlog: join(dir, 'backlog.json'), seed: join(dir, 'seed.json'), + availability: join(dir, 'availability.json'), }; } diff --git a/src/app/Footer.tsx b/src/app/Footer.tsx index 37799e9..4450ada 100644 --- a/src/app/Footer.tsx +++ b/src/app/Footer.tsx @@ -29,8 +29,24 @@ export function Footer() { -

This product uses the TMDB API but is not endorsed or certified by TMDB.

+

+ This website uses TMDB and the TMDB APIs but is not endorsed, certified, or otherwise + approved by TMDB. +

+ {app.features.watchProviders && ( +

+ Where-to-watch listings: availability data by{' '} + + JustWatch + + , via TMDB. +

+ )}

IMDb, Rotten Tomatoes and Metacritic scores come from the{' '} + {app.features.watchProviders && } import('../features/search/CommandPalette'); const CommandPalette = lazy(loadPalette); const ShortcutSheet = lazy(() => import('./ShortcutSheet')); +const loadServices = () => import('../features/watch/ServicesDialog'); +const ServicesDialog = lazy(loadServices); /** Warms the palette chunk on hover/focus so ⌘K opens instantly without bloating first load. */ export function preloadPalette(): void { void loadPalette(); } +/** Same idea for the services picker's chunk. */ +export function preloadServices(): void { + void loadServices(); +} + export function Overlays() { const overlay = useUi((s) => s.overlay); const paletteLoaded = useUi((s) => s.paletteLoaded); + const servicesLoaded = useUi((s) => s.servicesLoaded); useEffect(() => { const timer = window.setTimeout(preloadPalette, 4000); @@ -23,6 +32,7 @@ export function Overlays() { {paletteLoaded && } {overlay === 'shortcuts' && } + {app.features.watchProviders && servicesLoaded && } ); } diff --git a/src/app/queryClient.ts b/src/app/queryClient.ts index 8d82356..9986450 100644 --- a/src/app/queryClient.ts +++ b/src/app/queryClient.ts @@ -35,7 +35,7 @@ export const persistOptions: Omit = { retry: removeOldestQuery, }), maxAge: DAY, - buster: 'v1', + buster: 'v2', dehydrateOptions: { shouldDehydrateQuery: (query) => query.state.status === 'success' && query.queryKey[0] === 'tmdb', diff --git a/src/features/browse/GenrePage.tsx b/src/features/browse/GenrePage.tsx index 8398a29..e370548 100644 --- a/src/features/browse/GenrePage.tsx +++ b/src/features/browse/GenrePage.tsx @@ -7,13 +7,16 @@ import { formatCount, languageName } from '../../lib/format'; import { type Genre, genreBySlug } from '../../lib/genres'; import { useDocumentTitle } from '../../lib/hooks'; import type { MediaType } from '../../lib/model'; +import { useOwnedSet } from '../../lib/providers'; import { useDiscover } from '../../lib/queries'; +import { usePreferences } from '../../store/preferences'; import { Button } from '../../ui/Button'; import { Notice } from '../../ui/Notice'; import { Pagination } from '../../ui/Pagination'; import { PosterGrid, PosterGridSkeleton } from '../../ui/PosterGrid'; import { QueryError } from '../../ui/QueryError'; import { Select } from '../../ui/Select'; +import { WatchableToggle } from '../watch/WatchableToggle'; import { defaultType, filtersToSearch, @@ -123,9 +126,19 @@ function GenreView({ genre }: { genre: Genre }) { const today = now.toISOString().slice(0, 10); const filters = parseFilters(params, genre, currentYear); + const ownedIds = usePreferences((s) => s.ownedProviders); + const owned = useOwnedSet(ownedIds); + const watchableOnly = usePreferences((s) => s.watchableOnly); + const watchActive = app.features.watchProviders && watchableOnly && ownedIds.length > 0; const query = useDiscover( filters.type, - toDiscoverParams(filters, genre, today, app.minVoteCount), + toDiscoverParams( + filters, + genre, + today, + app.minVoteCount, + watchActive ? { owned, region: app.defaultRegion } : undefined, + ), ); const noun = filters.type === 'movie' ? 'films' : 'series'; useDocumentTitle(`${genre.name} ${noun}`); @@ -219,11 +232,16 @@ function GenreView({ genre }: { genre: Genre }) { Clear filters )} + {app.features.watchProviders && ( +

+ )}

{data && !query.isPlaceholderData - ? `${formatCount(data.totalResults)} ${noun}${filters.page > 1 ? `, page ${filters.page}` : ''}` + ? `${formatCount(data.totalResults)} ${noun}${watchActive ? ' on your services' : ''}${filters.page > 1 ? `, page ${filters.page}` : ''}` : ''}

diff --git a/src/features/browse/HomePage.tsx b/src/features/browse/HomePage.tsx index f64361a..ed0dda3 100644 --- a/src/features/browse/HomePage.tsx +++ b/src/features/browse/HomePage.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import { Link } from 'react-router'; import { app } from '../../../config/app.config'; import { accentHoverClass } from '../../lib/accents'; @@ -7,10 +7,13 @@ import { cx } from '../../lib/cx'; import { regionName } from '../../lib/format'; import { GENRES } from '../../lib/genres'; import { useDocumentTitle } from '../../lib/hooks'; +import { useOwnedSet } from '../../lib/providers'; +import { isWatchableWith } from '../../lib/providers-format'; import { useRail } from '../../lib/queries'; import { usePreferences } from '../../store/preferences'; import { Notice } from '../../ui/Notice'; import { Rail } from '../../ui/Rail'; +import { WatchableToggle } from '../watch/WatchableToggle'; import { DiscoverBar } from './DiscoverBar'; import { Hero } from './Hero'; @@ -20,16 +23,34 @@ function CatalogRail({ moreHref, eagerCount, limit, + watchActive, + owned, + onEmptyChange, }: { id: string; title: string; moreHref?: string; eagerCount?: number; - /** Home rails show a curated slice, not the full stored list — the page is a taster, not a wall. */ + /** Home rails show a curated slice, not the full stored list — the page is a taster, not a wall. + * Skipped while the Watchable-now lens is active, since matches are already sparse. */ limit?: number; + watchActive: boolean; + owned: ReadonlySet; + onEmptyChange: (id: string, empty: boolean) => void; }) { const { data, isPending } = useRail(id); - const items = limit ? data?.items.slice(0, limit) : data?.items; + const items = useMemo(() => { + if (!data) return undefined; + const source = watchActive + ? data.items.filter((item) => isWatchableWith(item.watch, owned)) + : data.items; + return limit && !watchActive ? source.slice(0, limit) : source; + }, [data, watchActive, owned, limit]); + + useEffect(() => { + onEmptyChange(id, watchActive && items !== undefined && items.length === 0); + }, [id, watchActive, items, onEmptyChange]); + return ( s.ownedProviders); + const owned = useOwnedSet(ownedIds); + const watchableOnly = usePreferences((s) => s.watchableOnly); + const watchActive = app.features.watchProviders && watchableOnly && ownedIds.length > 0; + + const railIds = useMemo( + () => [ + RAIL.trending, + popularRailId(region), + RAIL.newThisMonth, + RAIL.indiaMovies, + RAIL.indiaSeries, + RAIL.topMovies, + ], + [region], + ); + const [emptyRails, setEmptyRails] = useState>({}); + const onEmptyChange = useCallback((id: string, empty: boolean) => { + setEmptyRails((prev) => (prev[id] === empty ? prev : { ...prev, [id]: empty })); + }, []); + const allRailsEmpty = watchActive && railIds.every((id) => emptyRails[id] === true); + return ( <>

@@ -94,29 +137,71 @@ export function HomePage() {

{catalogueMissing ? : } - {!discoverActive && ( - <> - - - - - - - + {app.features.watchProviders && ( +
+ +
)} + {!discoverActive && + (allRailsEmpty ? ( +
+ + Genre pages search the whole catalogue: try one below. + +
+ ) : ( + <> + + + + + + + + ))} ); diff --git a/src/features/browse/filters.test.ts b/src/features/browse/filters.test.ts index 1936fb6..e46ba02 100644 --- a/src/features/browse/filters.test.ts +++ b/src/features/browse/filters.test.ts @@ -99,4 +99,24 @@ describe('toDiscoverParams', () => { 'vote_count.gte': 10, }); }); + + it('is unchanged when no watch filter is given', () => { + expect(toDiscoverParams(parse(''), comedy, TODAY, 200)).toEqual({ + with_genres: 35, + sort_by: 'popularity.desc', + page: 1, + }); + }); + + it('merges exactly the three watch params when given', () => { + const params = toDiscoverParams(parse(''), comedy, TODAY, 200, { + owned: new Set([119, 8]), + region: 'IN', + }); + expect(params).toMatchObject({ + watch_region: 'IN', + with_watch_providers: '8|119', + with_watch_monetization_types: 'flatrate|free|ads', + }); + }); }); diff --git a/src/features/browse/filters.ts b/src/features/browse/filters.ts index 1f543c2..4a6912e 100644 --- a/src/features/browse/filters.ts +++ b/src/features/browse/filters.ts @@ -1,5 +1,6 @@ import type { Genre } from '../../lib/genres'; import type { MediaType } from '../../lib/model'; +import { discoverWatchParams } from '../../lib/providers-format'; import { TMDB_MAX_PAGE } from '../../lib/tmdb'; /** @@ -109,12 +110,14 @@ export function hasActiveFilters(filters: GenreFilters): boolean { ); } -/** Maps URL filters onto TMDB `/discover` parameters. */ +/** Maps URL filters onto TMDB `/discover` parameters. `watch`, when given, merges + * `discoverWatchParams` so "Watchable now" narrows the same query server-side. */ export function toDiscoverParams( filters: GenreFilters, genre: Genre, today: string, minVoteCount: number, + watch?: { owned: ReadonlySet; region: string }, ): Record { const genreId = genre[filters.type]; const dateField = filters.type === 'movie' ? 'primary_release_date' : 'first_air_date'; @@ -149,5 +152,6 @@ export function toDiscoverParams( params[`${dateField}.lte`] = upper; } if (filters.lang) params.with_original_language = filters.lang; + if (watch) Object.assign(params, discoverWatchParams(watch.owned, watch.region)); return params; } diff --git a/src/features/search/CommandPalette.tsx b/src/features/search/CommandPalette.tsx index 6e9a9a7..10e515c 100644 --- a/src/features/search/CommandPalette.tsx +++ b/src/features/search/CommandPalette.tsx @@ -27,7 +27,7 @@ function matches(text: string, query: string): boolean { export default function CommandPalette() { const open = useUi((s) => s.overlay === 'palette'); const close = useUi((s) => s.close); - const showShortcuts = useUi((s) => s.open); + const openOverlay = useUi((s) => s.open); const region = usePreferences((s) => s.region); const setRegion = usePreferences((s) => s.setRegion); const navigate = useNavigate(); @@ -59,7 +59,10 @@ export default function CommandPalette() { const pages = [ { label: 'Home', run: () => go('/') }, { label: 'Watchlist', run: () => go('/watchlist') }, - { label: 'Keyboard shortcuts', run: () => showShortcuts('shortcuts') }, + { label: 'Keyboard shortcuts', run: () => openOverlay('shortcuts') }, + ...(app.features.watchProviders + ? [{ label: 'Your streaming services', run: () => openOverlay('services') }] + : []), ].filter((p) => matches(p.label, needle)); return ( diff --git a/src/features/search/SearchPage.tsx b/src/features/search/SearchPage.tsx index 156df81..4c78f33 100644 --- a/src/features/search/SearchPage.tsx +++ b/src/features/search/SearchPage.tsx @@ -1,8 +1,12 @@ import { type ReactNode, useEffect, useRef, useState } from 'react'; import { useSearchParams } from 'react-router'; +import { app } from '../../../config/app.config'; import { cx } from '../../lib/cx'; import { formatCount } from '../../lib/format'; import { useDocumentTitle } from '../../lib/hooks'; +import { type TitleSummary, titleKey } from '../../lib/model'; +import { useOwnedSet, useWatchLookups } from '../../lib/providers'; +import { watchableState } from '../../lib/providers-format'; import { useSearch } from '../../lib/queries'; import { TMDB_MAX_PAGE } from '../../lib/tmdb'; import { usePreferences } from '../../store/preferences'; @@ -11,12 +15,72 @@ import { Notice } from '../../ui/Notice'; import { Pagination } from '../../ui/Pagination'; import { PosterGrid, PosterGridSkeleton } from '../../ui/PosterGrid'; import { QueryError } from '../../ui/QueryError'; +import { WatchableToggle } from '../watch/WatchableToggle'; +import { partitionByWatchable } from './partition'; function pageFrom(value: string | null): number { const page = Number(value); return Number.isInteger(page) && page >= 1 ? Math.min(page, TMDB_MAX_PAGE) : 1; } +/** Partitioned when the Watchable-now lens is on and services are set; otherwise a plain grid. + * Nothing is ever hidden — partitioning only relabels the same results (docs/phase-2-plan.md §3.5). */ +function ResultsGrid({ items }: { items: TitleSummary[] }) { + const ownedIds = usePreferences((s) => s.ownedProviders); + const owned = useOwnedSet(ownedIds); + const watchableOnly = usePreferences((s) => s.watchableOnly); + const lensOn = app.features.watchProviders && watchableOnly && ownedIds.length > 0; + const lookups = useWatchLookups(items, app.defaultRegion, lensOn); + + if (!lensOn || lookups.pending) return ; + + const states = new Map( + items.map((item) => { + const key = titleKey(item.type, item.id); + return [key, watchableState(lookups.byKey.get(key), owned)] as const; + }), + ); + const { yes, unknown, no } = partitionByWatchable(items, states); + + return ( +
+ {yes.length > 0 && ( +
+

+ On your services +

+ +
+ )} + {unknown.length > 0 && ( +
+

+ Couldn’t check +

+ +
+ )} + {no.length > 0 && ( +
+

+ Not on your services +

+ +
+ )} +
+ ); +} + export default function SearchPage() { const [params, setParams] = useSearchParams(); const q = params.get('q') ?? ''; @@ -83,7 +147,7 @@ export default function SearchPage() { .

)} - + -

- {hasQuery && data && !search.isPlaceholderData - ? `${formatCount(data.totalResults)} results` - : ''} +

+ + {hasQuery && data && !search.isPlaceholderData + ? `${formatCount(data.totalResults)} results` + : ''} + + {app.features.watchProviders && hasQuery && }

{body}
diff --git a/src/features/search/partition.test.ts b/src/features/search/partition.test.ts new file mode 100644 index 0000000..8c17d3c --- /dev/null +++ b/src/features/search/partition.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; +import type { TitleSummary } from '../../lib/model'; +import { partitionByWatchable } from './partition'; + +function title(id: number): TitleSummary { + return { + id, + type: 'movie', + title: `Title ${id}`, + year: 2020, + poster: null, + vote: 7, + votes: 100, + genres: [], + lang: 'en', + }; +} + +describe('partitionByWatchable', () => { + it('preserves order within each group', () => { + const items = [title(1), title(2), title(3), title(4)]; + const states = new Map([ + ['movie:1', 'no'], + ['movie:2', 'yes'], + ['movie:3', 'no'], + ['movie:4', 'yes'], + ]); + const result = partitionByWatchable(items, states); + expect(result.yes.map((t) => t.id)).toEqual([2, 4]); + expect(result.no.map((t) => t.id)).toEqual([1, 3]); + }); + + it('treats a missing lookup as unknown, never as "no"', () => { + const items = [title(1)]; + const result = partitionByWatchable(items, new Map()); + expect(result.unknown.map((t) => t.id)).toEqual([1]); + expect(result.no).toEqual([]); + }); +}); diff --git a/src/features/search/partition.ts b/src/features/search/partition.ts new file mode 100644 index 0000000..1fa5c60 --- /dev/null +++ b/src/features/search/partition.ts @@ -0,0 +1,28 @@ +import { type TitleSummary, titleKey } from '../../lib/model'; + +export interface Partitioned { + yes: TitleSummary[]; + unknown: TitleSummary[]; + no: TitleSummary[]; +} + +/** + * Splits a page of search results by watchability without hiding anything (docs/phase-2-plan.md + * §3.5). Order is preserved within each group. A title with no entry in `states` (lookup still + * pending, or never requested) is treated as unknown, never as "not on your services". + */ +export function partitionByWatchable( + items: readonly TitleSummary[], + states: ReadonlyMap, +): Partitioned { + const yes: TitleSummary[] = []; + const unknown: TitleSummary[] = []; + const no: TitleSummary[] = []; + for (const item of items) { + const state = states.get(titleKey(item.type, item.id)) ?? 'unknown'; + if (state === 'yes') yes.push(item); + else if (state === 'no') no.push(item); + else unknown.push(item); + } + return { yes, unknown, no }; +} diff --git a/src/features/title/TitlePage.tsx b/src/features/title/TitlePage.tsx index b005293..50bc6a5 100644 --- a/src/features/title/TitlePage.tsx +++ b/src/features/title/TitlePage.tsx @@ -1,5 +1,6 @@ import { type ReactNode, useState } from 'react'; import { Link, useLocation, useNavigate, useParams } from 'react-router'; +import { app } from '../../../config/app.config'; import { NotFound } from '../../app/NotFound'; import { accentHoverClass } from '../../lib/accents'; import { cx } from '../../lib/cx'; @@ -8,6 +9,7 @@ import { genreForId } from '../../lib/genres'; import { useDocumentTitle } from '../../lib/hooks'; import { tmdbImage } from '../../lib/images'; import type { MediaType, TitleDetail } from '../../lib/model'; +import { usePrices } from '../../lib/providers'; import { useTitle } from '../../lib/queries'; import { useRatings } from '../../lib/ratings'; import { toCardScores } from '../../lib/ratings-format'; @@ -20,6 +22,7 @@ import { PosterImage } from '../../ui/PosterImage'; import { QueryError } from '../../ui/QueryError'; import { Rail } from '../../ui/Rail'; import { Scorecard } from '../../ui/Scorecard'; +import { WatchBlock } from '../watch/WatchBlock'; import { WatchlistButton } from '../watchlist/WatchlistButton'; const COLUMNS = @@ -162,6 +165,8 @@ function TitleContent({ detail }: { detail: TitleDetail }) { )} + {app.features.watchProviders && } + {detail.tagline && (

{detail.tagline}

)} @@ -272,6 +277,7 @@ function TitleSkeleton() { function TitleView({ type, id }: { type: MediaType; id: number }) { const query = useTitle(type, id); + usePrices(); // Started here so it downloads in parallel with the detail call, not after it. const detail = query.data; useDocumentTitle(detail ? `${detail.title}${detail.year ? ` (${detail.year})` : ''}` : null); diff --git a/src/features/watch/CostLine.tsx b/src/features/watch/CostLine.tsx new file mode 100644 index 0000000..ec7a4a9 --- /dev/null +++ b/src/features/watch/CostLine.tsx @@ -0,0 +1,28 @@ +import { formatDate } from '../../lib/format'; +import { cheapestPlan, type PriceEntry } from '../../lib/providers-format'; + +const PERIOD_LABEL: Record<'month' | 'quarter' | 'year', string> = { + month: 'a month', + quarter: 'a quarter', + year: 'a year', +}; + +function formatInr(value: number): string { + return `₹${new Intl.NumberFormat('en-IN').format(value)}`; +} + +/** One cost line inside the Stream group (docs/phase-2-plan.md §3.6), e.g. + * "JioHotstar: from ₹79 a month, with ads. Often bundled with Jio and Airtel plans. Checked 28 September 2026." */ +export function CostLine({ entry }: { entry: PriceEntry }) { + const plan = cheapestPlan(entry); + if (!plan) return null; + const checked = entry.verified ? formatDate(entry.verified) : null; + + return ( +

+ {entry.name}: from {formatInr(plan.inr)} {PERIOD_LABEL[plan.per]} + {plan.ads ? ', with ads' : ''}. {entry.note ? `${entry.note}. ` : ''} + {checked ? `Checked ${checked}.` : ''} +

+ ); +} diff --git a/src/features/watch/ProviderChip.tsx b/src/features/watch/ProviderChip.tsx new file mode 100644 index 0000000..dddfe64 --- /dev/null +++ b/src/features/watch/ProviderChip.tsx @@ -0,0 +1,67 @@ +import { useState } from 'react'; +import { cx } from '../../lib/cx'; +import { tmdbImage } from '../../lib/images'; +import { CheckIcon } from '../../ui/icons'; + +/** + * One provider entry inside a WatchBlock group. Every chip in a region links to the same + * tier-1 TMDB `/watch` URL — TMDB's watch/providers response gives one link per region, not + * one per provider (docs/phase-2-plan.md §2.1). + */ +export function ProviderChip({ + name, + logo, + owned, + href, +}: { + name: string; + logo: string | null; + owned: boolean; + href: string | null; +}) { + const [logoFailed, setLogoFailed] = useState(false); + const src = logo && !logoFailed ? tmdbImage(logo, 'w92') : null; + + const inner = ( + <> + {src ? ( + setLogoFailed(true)} + className="size-8 shrink-0 rounded-sm object-contain" + /> + ) : ( +
+ {inner} + (opens TMDB) + + ); +} diff --git a/src/features/watch/ServicesButton.tsx b/src/features/watch/ServicesButton.tsx new file mode 100644 index 0000000..3c12f20 --- /dev/null +++ b/src/features/watch/ServicesButton.tsx @@ -0,0 +1,27 @@ +import { preloadServices } from '../../app/overlays'; +import { usePreferences } from '../../store/preferences'; +import { useUi } from '../../store/ui'; +import { TvIcon } from '../../ui/icons'; + +/** Header trigger for the services picker (docs/phase-2-plan.md §5.1). Icon-only below `sm` so + * the header still fits at 360px; text (with a count) once there's room. */ +export function ServicesButton() { + const open = useUi((s) => s.open); + const count = usePreferences((s) => s.ownedProviders.length); + const label = count > 0 ? `Your services (${count} selected)` : 'Your services'; + + return ( + + ); +} diff --git a/src/features/watch/ServicesDialog.tsx b/src/features/watch/ServicesDialog.tsx new file mode 100644 index 0000000..89a9085 --- /dev/null +++ b/src/features/watch/ServicesDialog.tsx @@ -0,0 +1,121 @@ +import { useState } from 'react'; +import { PICKER_PROVIDERS } from '../../../config/providers'; +import { cx } from '../../lib/cx'; +import { tmdbImage } from '../../lib/images'; +import { useProviderCatalog } from '../../lib/providers'; +import { usePreferences } from '../../store/preferences'; +import { useUi } from '../../store/ui'; +import { buttonClass } from '../../ui/Button'; +import { Dialog } from '../../ui/Dialog'; +import { CheckIcon } from '../../ui/icons'; + +function ServiceOption({ + id, + name, + logo, + checked, + onToggle, +}: { + id: number; + name: string; + logo: string | null; + checked: boolean; + onToggle: (id: number) => void; +}) { + const [logoFailed, setLogoFailed] = useState(false); + const src = logo && !logoFailed ? tmdbImage(logo, 'w92') : null; + + return ( + + ); +} + +/** + * "Your services" picker (docs/phase-2-plan.md §3.4, §5.1). Changes apply instantly — there is + * no separate save step, so "Done" only closes the dialog. + */ +export default function ServicesDialog() { + const open = useUi((s) => s.overlay === 'services'); + const close = useUi((s) => s.close); + const owned = usePreferences((s) => s.ownedProviders); + const toggle = usePreferences((s) => s.toggleOwnedProvider); + const setOwned = usePreferences((s) => s.setOwnedProviders); + const catalog = useProviderCatalog(); + + const logoFor = (id: number): string | null => + catalog.data?.find((p) => p.id === id)?.logo ?? null; + + return ( + !next && close()} + title="Your streaming services" + className="p-5" + > +

+ Tick what you pay for. These sort first on title pages and power Watchable now. Saved in + this browser only. +

+ +
    + {PICKER_PROVIDERS.map((provider) => ( +
  • + +
  • + ))} +
+ +
+ {owned.length > 0 ? ( + + ) : ( + + )} + +
+
+ ); +} diff --git a/src/features/watch/WatchBlock.tsx b/src/features/watch/WatchBlock.tsx new file mode 100644 index 0000000..1ae5d9d --- /dev/null +++ b/src/features/watch/WatchBlock.tsx @@ -0,0 +1,181 @@ +import { Fragment, useMemo, useState } from 'react'; +import { app } from '../../../config/app.config'; +import { PROVIDER_LINKS } from '../../../config/provider-links'; +import { PROVIDER_ALIASES } from '../../../config/providers'; +import { regionName } from '../../lib/format'; +import type { TitleDetail } from '../../lib/model'; +import { useOwnedSet, usePrices } from '../../lib/providers'; +import { + type Availability, + type CheckedAvailability, + collapseAliases, + isPriceFresh, + orderForUser, + regionsWithListings, +} from '../../lib/providers-format'; +import { usePreferences } from '../../store/preferences'; +import { buttonClass } from '../../ui/Button'; +import { ExternalIcon } from '../../ui/icons'; +import { Select } from '../../ui/Select'; +import { CostLine } from './CostLine'; +import { ProviderChip } from './ProviderChip'; + +interface Group { + key: 'stream' | 'free' | 'rent' | 'buy'; + label: string; + ids: number[]; + adsOnly: ReadonlySet; +} + +/** Stream / Free (`free` ∪ `ads`) / Rent / Buy, aliases collapsed for display, Free never + * repeats a provider already shown in Stream (docs/phase-2-plan.md §3.1 point 3). */ +function buildGroups(a: CheckedAvailability): Group[] { + const stream = collapseAliases(a.stream, PROVIDER_ALIASES); + const adsOnly = new Set(a.ads.filter((id) => !a.free.includes(id))); + const freeUnion = collapseAliases([...new Set([...a.free, ...a.ads])], PROVIDER_ALIASES); + const free = freeUnion.filter((id) => !stream.includes(id)); + const rent = collapseAliases(a.rent, PROVIDER_ALIASES); + const buy = collapseAliases(a.buy, PROVIDER_ALIASES); + + const groups: Group[] = [ + { key: 'stream', label: 'Stream', ids: stream, adsOnly: new Set() }, + { key: 'free', label: 'Free', ids: free, adsOnly }, + { key: 'rent', label: 'Rent', ids: rent, adsOnly: new Set() }, + { key: 'buy', label: 'Buy', ids: buy, adsOnly: new Set() }, + ]; + return groups.filter((g) => g.ids.length > 0); +} + +/** + * Availability block for a title page (docs/phase-2-plan.md §3.1, §5.3). Renders nothing when + * `detail.watch.checked` is false — an unchecked or failed lookup is never shown as "unavailable". + */ +export function WatchBlock({ detail }: { detail: TitleDetail }) { + const [region, setRegion] = useState(app.defaultRegion); + const owned = useOwnedSet(usePreferences((s) => s.ownedProviders)); + const prices = usePrices(); + + const showRegionSelect = regionsWithListings(detail.watchByRegion).length >= 2; + const availability: Availability = detail.watchByRegion[region] ?? { checked: false }; + const groups = useMemo( + () => (availability.checked ? buildGroups(availability) : []), + [availability], + ); + + if (!detail.watch.checked) return null; + + const link = availability.checked ? availability.link : null; + const streamGroup = groups.find((g) => g.key === 'stream'); + const freeGroup = groups.find((g) => g.key === 'free'); + const ownsAStream = streamGroup ? streamGroup.ids.some((id) => owned.has(id)) : false; + + const today = new Date().toISOString().slice(0, 10); + const priceLines = + streamGroup && !ownsAStream && prices.data + ? streamGroup.ids + .flatMap((id) => prices.data?.providers.filter((p) => p.provider_id === id) ?? []) + .filter((entry) => isPriceFresh(entry.verified, today, app.priceStaleAfterDays)) + .slice(0, 3) + : []; + + const tierTwoIds = + region === 'IN' + ? orderForUser( + [...new Set([...(streamGroup?.ids ?? []), ...(freeGroup?.ids ?? [])])], + owned, + ).filter((id) => PROVIDER_LINKS[id]?.checked) + : []; + + return ( +
+
+

+ Where to watch +

+ {showRegionSelect && ( + + )} +
+ +
+ {groups.length === 0 ? ( +

+ Nothing to stream, rent or buy in {regionName(region)} right now. +

+ ) : ( +
+ {groups.map((group) => ( + +
{group.label}
+
+ {orderForUser(group.ids, owned).map((id) => { + const meta = detail.providerInfo[id]; + const suffix = group.adsOnly.has(id) ? ' · with ads' : ''; + return ( + + ); + })} +
+
+ ))} + {priceLines.length > 0 && ( + +
+
+ {priceLines.map((entry) => ( + + ))} +
+
+ )} +
+ )} +
+ +
+ {link && ( + + See every option on TMDB + + (opens TMDB) + + )} + {tierTwoIds.map((id) => { + const linkInfo = PROVIDER_LINKS[id]; + if (!linkInfo?.checked) return null; + return ( + + Search on {linkInfo.label} + (opens {linkInfo.label}) + + ); + })} +
+ +

Availability data by JustWatch.

+
+ ); +} diff --git a/src/features/watch/WatchableToggle.tsx b/src/features/watch/WatchableToggle.tsx new file mode 100644 index 0000000..16402ac --- /dev/null +++ b/src/features/watch/WatchableToggle.tsx @@ -0,0 +1,60 @@ +import { preloadServices } from '../../app/overlays'; +import { cx } from '../../lib/cx'; +import { usePreferences } from '../../store/preferences'; +import { useUi } from '../../store/ui'; + +/** + * The "Watchable now" lens (docs/phase-2-plan.md §3.5). With no services picked, the control is + * replaced by a button into the picker — there is nothing to filter by otherwise. + */ +export function WatchableToggle() { + const owned = usePreferences((s) => s.ownedProviders); + const on = usePreferences((s) => s.watchableOnly); + const setOn = usePreferences((s) => s.setWatchableOnly); + const open = useUi((s) => s.open); + + if (owned.length === 0) { + return ( + + ); + } + + return ( +
+ + {on && Availability data by JustWatch.} +
+ ); +} diff --git a/src/lib/catalog-format.ts b/src/lib/catalog-format.ts index d09be40..6e8844c 100644 --- a/src/lib/catalog-format.ts +++ b/src/lib/catalog-format.ts @@ -38,4 +38,12 @@ export interface DataMeta { omdbRequests: number; updated: string; }; + providers?: { + titles: number; + checked: number; + fromCache: number; + unchecked: number; + tmdbRequests: number; + catalog: number; + }; } diff --git a/src/lib/data.ts b/src/lib/data.ts index 0e1134e..03e31fe 100644 --- a/src/lib/data.ts +++ b/src/lib/data.ts @@ -4,6 +4,11 @@ export function dataUrl(path: string): string { return `${import.meta.env.BASE_URL}data/${path}?v=${encodeURIComponent(DATA_VERSION)}`; } +/** A committed, hand-maintained file at the site root (not under `/data/`), e.g. `providers-in.json`. */ +export function publicUrl(path: string): string { + return `${import.meta.env.BASE_URL}${path}?v=${encodeURIComponent(DATA_VERSION)}`; +} + /** * Fetches a prebuilt JSON file from `/data`. Returns null when the file does not exist yet — * a catalogue that has not been built is a normal state, not an error. diff --git a/src/lib/model.test.ts b/src/lib/model.test.ts index 3772cbf..4bd547d 100644 --- a/src/lib/model.test.ts +++ b/src/lib/model.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { movieDetailToModel, pickTrailer, toSummary, truncate, tvDetailToModel } from './model'; -import type { TmdbMovieDetail, TmdbTvDetail, TmdbVideo } from './tmdb-types'; +import type { TmdbMovieDetail, TmdbTvDetail, TmdbVideo, TmdbWatchProviders } from './tmdb-types'; const base = { poster_path: '/p.jpg', @@ -160,4 +160,79 @@ describe('detail mappers', () => { endYear: null, }); }); + + const watchProviders: TmdbWatchProviders = { + results: { + IN: { + link: 'https://x', + flatrate: [ + { provider_id: 8, provider_name: 'Netflix', logo_path: null, display_priority: 0 }, + ], + }, + US: { + link: 'https://y', + flatrate: [ + { provider_id: 15, provider_name: 'Hulu', logo_path: null, display_priority: 0 }, + ], + }, + }, + }; + + it("sets watch from the 'watch/providers' append, limited to the requested regions", () => { + const raw: TmdbMovieDetail = { + ...base, + id: 19404, + title: 'Dilwale Dulhania Le Jayenge', + original_title: 'Dilwale Dulhania Le Jayenge', + release_date: '1995-10-20', + genres: [], + runtime: 190, + tagline: '', + status: 'Released', + imdb_id: 'tt0112870', + 'watch/providers': watchProviders, + }; + const detail = movieDetailToModel(raw, ['IN']); + expect(detail.watch).toEqual({ + checked: true, + region: 'IN', + link: 'https://x', + stream: [8], + free: [], + ads: [], + rent: [], + buy: [], + }); + expect(detail.watchByRegion).toEqual({ + IN: { + checked: true, + region: 'IN', + link: 'https://x', + stream: [8], + free: [], + ads: [], + rent: [], + buy: [], + }, + }); + }); + + it("marks watch as unchecked when 'watch/providers' is absent", () => { + const raw: TmdbMovieDetail = { + ...base, + id: 19404, + title: 'Dilwale Dulhania Le Jayenge', + original_title: 'Dilwale Dulhania Le Jayenge', + release_date: '1995-10-20', + genres: [], + runtime: 190, + tagline: '', + status: 'Released', + imdb_id: 'tt0112870', + }; + const detail = movieDetailToModel(raw); + expect(detail.watch).toEqual({ checked: false }); + expect(detail.watchByRegion).toEqual({}); + expect(detail.providerInfo).toEqual({}); + }); }); diff --git a/src/lib/model.ts b/src/lib/model.ts index b828a04..076a5e9 100644 --- a/src/lib/model.ts +++ b/src/lib/model.ts @@ -1,3 +1,5 @@ +import type { Availability, CheckedAvailability, ProviderMeta } from './providers-format'; +import { toWatchInfo, UNCHECKED } from './providers-format'; import type { TmdbCredits, TmdbMovieDetail, @@ -31,6 +33,8 @@ export interface TitleSummary { lang: string; imdb?: string | null; scores?: CardScores; + /** Default region (IN) availability. Catalogue entries get it nightly; live results do not. */ + watch?: Availability; } export interface Person { @@ -58,6 +62,9 @@ export interface TitleDetail extends TitleSummary { trailer: { key: string; name: string } | null; recommendations: TitleSummary[]; imdb: string | null; + watch: Availability; + watchByRegion: Record; + providerInfo: Record; } export function titleKey(type: MediaType, id: number): string { @@ -153,8 +160,12 @@ function uniquePeople(people: Person[]): Person[] { }); } -export function movieDetailToModel(raw: TmdbMovieDetail): TitleDetail { +export function movieDetailToModel( + raw: TmdbMovieDetail, + regions: readonly string[] = ['IN'], +): TitleDetail { const imdb = raw.imdb_id || raw.external_ids?.imdb_id || null; + const info = toWatchInfo(raw['watch/providers'], regions); return { ...toSummary({ ...raw, genre_ids: raw.genres.map((g) => g.id) }, 'movie'), overview: raw.overview, @@ -178,11 +189,18 @@ export function movieDetailToModel(raw: TmdbMovieDetail): TitleDetail { .slice(0, 20) .map((r) => toSummary(r, 'movie')), imdb, + watch: info?.byRegion.IN ?? UNCHECKED, + watchByRegion: info?.byRegion ?? {}, + providerInfo: info?.providers ?? {}, }; } -export function tvDetailToModel(raw: TmdbTvDetail): TitleDetail { +export function tvDetailToModel( + raw: TmdbTvDetail, + regions: readonly string[] = ['IN'], +): TitleDetail { const runtime = raw.episode_run_time[0] ?? raw.last_episode_to_air?.runtime ?? null; + const info = toWatchInfo(raw['watch/providers'], regions); return { ...toSummary({ ...raw, genre_ids: raw.genres.map((g) => g.id) }, 'tv'), overview: raw.overview, @@ -202,5 +220,8 @@ export function tvDetailToModel(raw: TmdbTvDetail): TitleDetail { .slice(0, 20) .map((r) => toSummary(r, 'tv')), imdb: raw.external_ids?.imdb_id || null, + watch: info?.byRegion.IN ?? UNCHECKED, + watchByRegion: info?.byRegion ?? {}, + providerInfo: info?.providers ?? {}, }; } diff --git a/src/lib/providers-format.test.ts b/src/lib/providers-format.test.ts new file mode 100644 index 0000000..08f4868 --- /dev/null +++ b/src/lib/providers-format.test.ts @@ -0,0 +1,320 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { PICKER_PROVIDERS } from '../../config/providers'; +import { + cheapestPlan, + collapseAliases, + discoverWatchParams, + expandOwned, + hasListings, + isPriceFresh, + isWatchableWith, + orderForUser, + type PriceEntry, + parsePriceFile, + toAvailability, + toProviderCatalog, + toWatchInfo, + UNCHECKED, + watchableState, +} from './providers-format'; +import type { TmdbProviderCatalogEntry, TmdbWatchProviders } from './tmdb-types'; + +const netflix = { + provider_id: 8, + provider_name: 'Netflix', + logo_path: '/netflix.png', + display_priority: 0, +}; +const appleStore = { + provider_id: 2, + provider_name: 'Apple TV Store', + logo_path: '/apple.png', + display_priority: 5, +}; +const googlePlay = { + provider_id: 3, + provider_name: 'Google Play Movies', + logo_path: '/google.png', + display_priority: 8, +}; +const youtube = { + provider_id: 192, + provider_name: 'YouTube', + logo_path: '/yt.png', + display_priority: 11, +}; +const primeVideo = { + provider_id: 119, + provider_name: 'Amazon Prime Video', + logo_path: '/prime.png', + display_priority: 1, +}; + +/** Trimmed from the real /movie/19404/watch/providers response (docs/phase-2-plan.md §2.1). */ +const ddljProviders: TmdbWatchProviders = { + id: 19404, + results: { + IN: { + link: 'https://www.themoviedb.org/movie/19404/watch?locale=IN', + flatrate: [netflix], + rent: [appleStore, googlePlay, youtube], + buy: [appleStore, googlePlay, youtube], + }, + US: { link: 'https://www.themoviedb.org/movie/19404/watch?locale=US', flatrate: [netflix] }, + }, +}; + +/** Panchayat: the same provider appears in both `flatrate` and `free` (docs/phase-2-plan.md §2.1). */ +const panchayatProviders: TmdbWatchProviders = { + id: 101352, + results: { + IN: { + link: 'https://www.themoviedb.org/tv/101352/watch?locale=IN', + flatrate: [primeVideo], + free: [primeVideo], + }, + }, +}; + +describe('toAvailability', () => { + it('maps the DDLJ fixture', () => { + expect(toAvailability(ddljProviders, 'IN')).toEqual({ + checked: true, + region: 'IN', + link: 'https://www.themoviedb.org/movie/19404/watch?locale=IN', + stream: [8], + free: [], + ads: [], + rent: [2, 3, 192], + buy: [2, 3, 192], + }); + }); + + it('sorts unsorted input by priority then ID and collapses duplicate IDs within a list', () => { + const raw: TmdbWatchProviders = { + results: { + IN: { + link: 'https://x', + flatrate: [ + { ...youtube, display_priority: 2 }, + { ...netflix, display_priority: 1 }, + { ...netflix, display_priority: 1 }, + ], + }, + }, + }; + expect(toAvailability(raw, 'IN')).toMatchObject({ stream: [8, 192] }); + }); + + it('keeps a provider in both stream and free (Panchayat)', () => { + expect(toAvailability(panchayatProviders, 'IN')).toMatchObject({ + stream: [119], + free: [119], + }); + }); + + it('returns checked with empty lists and a null link when the region is absent', () => { + expect(toAvailability(ddljProviders, 'FR')).toEqual({ + checked: true, + region: 'FR', + link: null, + stream: [], + free: [], + ads: [], + rent: [], + buy: [], + }); + }); + + it('is never "not available" for a missing or malformed response', () => { + expect(toAvailability(undefined, 'IN')).toEqual(UNCHECKED); + expect(toAvailability(null, 'IN')).toEqual(UNCHECKED); + expect(toAvailability({} as TmdbWatchProviders, 'IN')).toEqual(UNCHECKED); + expect(toAvailability({ results: 'x' } as unknown as TmdbWatchProviders, 'IN')).toEqual( + UNCHECKED, + ); + }); +}); + +describe('checked:false is never "not available"', () => { + const owned = new Set([8]); + + it('isWatchableWith(UNCHECKED) is false but watchableState is "unknown"', () => { + expect(isWatchableWith(UNCHECKED, owned)).toBe(false); + expect(watchableState(UNCHECKED, owned)).toBe('unknown'); + expect(watchableState(undefined, owned)).toBe('unknown'); + }); + + it('hasListings(UNCHECKED) is false', () => { + expect(hasListings(UNCHECKED)).toBe(false); + }); + + it('empty checked availability is "no", not "unknown"', () => { + const empty = toAvailability(ddljProviders, 'FR'); + expect(watchableState(empty, owned)).toBe('no'); + }); +}); + +describe('toWatchInfo', () => { + it('keeps only the requested regions and collects provider names/logos from every list', () => { + const info = toWatchInfo(ddljProviders, ['IN']); + expect(info?.byRegion.IN).toBeDefined(); + expect(info?.byRegion.US).toBeUndefined(); + expect(info?.providers[8]).toEqual({ name: 'Netflix', logo: '/netflix.png' }); + expect(info?.providers[192]).toEqual({ name: 'YouTube', logo: '/yt.png' }); + }); + + it('returns null for a missing response', () => { + expect(toWatchInfo(undefined, ['IN'])).toBeNull(); + }); +}); + +describe('toProviderCatalog', () => { + const movieList: TmdbProviderCatalogEntry[] = [ + { ...googlePlay, display_priority: 2, display_priorities: { IN: 8 } }, + { ...netflix, display_priority: 0, display_priorities: { IN: 0 } }, + ]; + const tvList: TmdbProviderCatalogEntry[] = [ + { ...netflix, display_priority: 0, display_priorities: { IN: 0 } }, + { ...primeVideo, display_priority: 3, display_priorities: { IN: 1 } }, + ]; + + it('uses display_priorities.IN over the top-level priority', () => { + const catalog = toProviderCatalog([movieList], 'IN'); + expect(catalog.find((p) => p.id === 3)?.priority).toBe(8); + }); + + it('unions movie and tv lists without duplicates, sorted by priority', () => { + const catalog = toProviderCatalog([movieList, tvList], 'IN'); + expect(catalog.map((p) => p.id)).toEqual([8, 119, 3]); + }); +}); + +describe('alias helpers', () => { + const aliases = { 2100: 119, 175: 8 }; + + it('expandOwned adds the variant when the canonical is owned, never a channel', () => { + expect(expandOwned([119], aliases).has(2100)).toBe(true); + expect(expandOwned([8], aliases).has(175)).toBe(true); + expect(expandOwned([119], aliases).has(2243)).toBe(false); + }); + + it('collapseAliases drops a variant only when its canonical is present too', () => { + expect(collapseAliases([119, 2100], aliases)).toEqual([119]); + expect(collapseAliases([2100], aliases)).toEqual([2100]); + }); + + it('orderForUser puts owned providers first, stably', () => { + expect(orderForUser([8, 119, 2336], new Set([2336]))).toEqual([2336, 8, 119]); + }); +}); + +describe('isWatchableWith', () => { + it('is true when owned intersects stream, free or ads; false for rent/buy only', () => { + const streamOnly = toAvailability(ddljProviders, 'IN'); + expect(isWatchableWith(streamOnly, new Set([8]))).toBe(true); + expect(isWatchableWith(streamOnly, new Set([2]))).toBe(false); + }); +}); + +describe('discoverWatchParams', () => { + it('sorts IDs ascending, always includes watch_region and the monetization filter', () => { + expect(discoverWatchParams(new Set([2336, 8, 119]), 'IN')).toEqual({ + watch_region: 'IN', + with_watch_providers: '8|119|2336', + with_watch_monetization_types: 'flatrate|free|ads', + }); + }); + + it('is empty when nothing is owned', () => { + expect(discoverWatchParams(new Set(), 'IN')).toEqual({}); + }); +}); + +describe('price helpers', () => { + it('isPriceFresh treats today and 120 days ago as fresh, 121 days as stale', () => { + expect(isPriceFresh('2026-09-28', '2026-09-28', 120)).toBe(true); + expect(isPriceFresh('2026-05-31', '2026-09-28', 120)).toBe(true); + expect(isPriceFresh('2026-05-30', '2026-09-28', 120)).toBe(false); + expect(isPriceFresh(null, '2026-09-28', 120)).toBe(false); + }); + + it('cheapestPlan prefers monthly plans, else the lowest overall', () => { + const jioHotstar: PriceEntry = { + provider_id: 2336, + name: 'JioHotstar', + verified: '2026-09-28', + plans: [ + { name: 'Mobile', inr: 79, per: 'month', ads: true }, + { name: 'Super', inr: 149, per: 'month', ads: true }, + { name: 'Premium', inr: 2199, per: 'year', ads: false }, + ], + }; + expect(cheapestPlan(jioHotstar)?.inr).toBe(79); + + const yearlyOnly: PriceEntry = { + provider_id: 237, + name: 'Sony LIV', + verified: '2026-09-28', + plans: [ + { name: 'Premium', inr: 1499, per: 'year', ads: false }, + { name: 'Mobile Only', inr: 699, per: 'year', ads: false }, + ], + }; + expect(cheapestPlan(yearlyOnly)).toEqual({ + name: 'Mobile Only', + inr: 699, + per: 'year', + ads: false, + }); + }); + + it('parsePriceFile drops malformed plans and dates but keeps the rest of the entry', () => { + const file = parsePriceFile({ + version: 1, + region: 'IN', + providers: [ + { + provider_id: 8, + name: 'Netflix', + verified: 'not-a-date', + plans: [ + { name: 'Mobile', inr: '149', per: 'month', ads: false }, + { name: 'Basic', inr: 199, per: 'decade', ads: false }, + { name: 'Standard', inr: 499, per: 'month', ads: false }, + ], + }, + ], + }); + expect(file.providers).toHaveLength(1); + expect(file.providers[0]?.verified).toBeNull(); + expect(file.providers[0]?.plans).toEqual([ + { name: 'Standard', inr: 499, per: 'month', ads: false }, + ]); + }); + + it('never throws on garbage input', () => { + expect(parsePriceFile(undefined)).toEqual({ version: 1, region: 'IN', providers: [] }); + expect(parsePriceFile('nonsense')).toEqual({ version: 1, region: 'IN', providers: [] }); + expect(parsePriceFile({ providers: 'nope' })).toEqual({ + version: 1, + region: 'IN', + providers: [], + }); + }); +}); + +describe('committed seed validation', () => { + it('public/providers-in.json keeps every hand-edited entry and only names picker providers', () => { + const path = fileURLToPath(new URL('../../public/providers-in.json', import.meta.url)); + const raw = JSON.parse(readFileSync(path, 'utf8')); + const file = parsePriceFile(raw); + expect(file.providers).toHaveLength(raw.providers.length); + const pickerIds = new Set(PICKER_PROVIDERS.map((p) => p.id)); + for (const entry of file.providers) { + expect(pickerIds.has(entry.provider_id)).toBe(true); + } + }); +}); diff --git a/src/lib/providers-format.ts b/src/lib/providers-format.ts new file mode 100644 index 0000000..ed20953 --- /dev/null +++ b/src/lib/providers-format.ts @@ -0,0 +1,306 @@ +import type { TmdbProviderCatalogEntry, TmdbWatchProvider, TmdbWatchProviders } from './tmdb-types'; + +/** PLAN §8.2: `checked:false` = lookup failed or unknown. Never render or filter it as "not available". */ +export type Availability = + | { checked: false } + | { + checked: true; + region: string; + link: string | null; + /** TMDB provider IDs, ordered by TMDB display priority, de-duplicated per list. */ + stream: number[]; + free: number[]; + ads: number[]; + rent: number[]; + buy: number[]; + }; + +export type CheckedAvailability = Extract; + +export const UNCHECKED: Availability = { checked: false }; + +export interface ProviderMeta { + name: string; + logo: string | null; +} + +/** One row of data/providers-tmdb-in.json. */ +export interface ProviderCatalogItem { + id: number; + name: string; + logo: string | null; + priority: number; +} + +export interface WatchInfo { + byRegion: Record; + providers: Record; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +/** Sorted by `display_priority` then `provider_id`; duplicate IDs within a list collapse. */ +function idsFrom(list: TmdbWatchProvider[] | undefined): number[] { + if (!Array.isArray(list)) return []; + const seen = new Set(); + return list + .slice() + .sort((a, b) => a.display_priority - b.display_priority || a.provider_id - b.provider_id) + .map((p) => p.provider_id) + .filter((id) => { + if (seen.has(id)) return false; + seen.add(id); + return true; + }); +} + +/** Contract mapper. Missing response → UNCHECKED; response without the region → checked, all empty, link null. */ +export function toAvailability( + raw: TmdbWatchProviders | null | undefined, + region: string, +): Availability { + if (!raw || !isRecord(raw.results)) return UNCHECKED; + const entry = raw.results[region]; + if (!isRecord(entry)) { + return { checked: true, region, link: null, stream: [], free: [], ads: [], rent: [], buy: [] }; + } + return { + checked: true, + region, + link: typeof entry.link === 'string' ? entry.link : null, + stream: idsFrom(entry.flatrate as TmdbWatchProvider[] | undefined), + free: idsFrom(entry.free as TmdbWatchProvider[] | undefined), + ads: idsFrom(entry.ads as TmdbWatchProvider[] | undefined), + rent: idsFrom(entry.rent as TmdbWatchProvider[] | undefined), + buy: idsFrom(entry.buy as TmdbWatchProvider[] | undefined), + }; +} + +/** Same mapping for several regions at once, plus provider names/logos seen in the response. */ +export function toWatchInfo( + raw: TmdbWatchProviders | null | undefined, + regions: readonly string[], +): WatchInfo | null { + if (!raw || !isRecord(raw.results)) return null; + + const byRegion: Record = {}; + for (const region of regions) { + const availability = toAvailability(raw, region); + if (availability.checked) byRegion[region] = availability; + } + + const providers: Record = {}; + for (const entry of Object.values(raw.results)) { + if (!isRecord(entry)) continue; + const lists = [entry.flatrate, entry.free, entry.ads, entry.rent, entry.buy]; + for (const list of lists) { + if (!Array.isArray(list)) continue; + for (const provider of list as TmdbWatchProvider[]) { + if (!providers[provider.provider_id]) { + providers[provider.provider_id] = { + name: provider.provider_name, + logo: provider.logo_path ?? null, + }; + } + } + } + } + + return { byRegion, providers }; +} + +/** Union of movie + tv catalogue entries for a region, priority from display_priorities[region]. */ +export function toProviderCatalog( + lists: TmdbProviderCatalogEntry[][], + region: string, +): ProviderCatalogItem[] { + const byId = new Map(); + for (const list of lists) { + for (const entry of list) { + if (byId.has(entry.provider_id)) continue; + byId.set(entry.provider_id, { + id: entry.provider_id, + name: entry.provider_name, + logo: entry.logo_path ?? null, + priority: entry.display_priorities?.[region] ?? entry.display_priority, + }); + } + } + return [...byId.values()].sort((a, b) => a.priority - b.priority || a.id - b.id); +} + +export function hasListings(a: Availability | undefined): boolean { + if (!a?.checked) return false; + return ( + a.stream.length > 0 || + a.free.length > 0 || + a.ads.length > 0 || + a.rent.length > 0 || + a.buy.length > 0 + ); +} + +export function regionsWithListings(byRegion: Record): string[] { + return Object.keys(byRegion).filter((region) => hasListings(byRegion[region])); +} + +/** `aliases` maps variant → canonical (config/providers.ts PROVIDER_ALIASES). Owning the canonical + * ID covers every variant that points at it; channels are never in `aliases`, so they never alias. */ +export function expandOwned( + owned: readonly number[], + aliases: Readonly>, +): Set { + const variantsOf = new Map(); + for (const [variant, canonical] of Object.entries(aliases)) { + const list = variantsOf.get(canonical) ?? []; + list.push(Number(variant)); + variantsOf.set(canonical, list); + } + const result = new Set(owned); + for (const id of owned) { + for (const variant of variantsOf.get(id) ?? []) result.add(variant); + } + return result; +} + +/** For display: drops a variant only when its canonical is also present in the same list. A + * variant on its own (no canonical alongside) is left as-is, since that is genuinely what's listed. */ +export function collapseAliases( + ids: readonly number[], + aliases: Readonly>, +): number[] { + const set = new Set(ids); + return ids.filter((id) => { + const canonical = aliases[id]; + return canonical === undefined || !set.has(canonical); + }); +} + +/** Owned providers first, stable order otherwise. */ +export function orderForUser(ids: readonly number[], owned: ReadonlySet): number[] { + return [...ids.filter((id) => owned.has(id)), ...ids.filter((id) => !owned.has(id))]; +} + +/** true only for checked availability whose stream ∪ free ∪ ads meets `owned`. Unknown → false (excluded, not "unavailable"). */ +export function isWatchableWith(a: Availability | undefined, owned: ReadonlySet): boolean { + if (!a?.checked) return false; + return [...a.stream, ...a.free, ...a.ads].some((id) => owned.has(id)); +} + +/** Tri-state for search partitioning: 'yes' | 'no' | 'unknown' ('unknown' for checked:false/undefined). */ +export function watchableState( + a: Availability | undefined, + owned: ReadonlySet, +): 'yes' | 'no' | 'unknown' { + if (!a?.checked) return 'unknown'; + return isWatchableWith(a, owned) ? 'yes' : 'no'; +} + +/** Params for /discover. Empty object when `owned` is empty (caller should not enable the lens then). */ +export function discoverWatchParams( + owned: ReadonlySet, + region: string, +): Record { + if (owned.size === 0) return {}; + return { + watch_region: region, + with_watch_providers: [...owned].sort((a, b) => a - b).join('|'), + with_watch_monetization_types: 'flatrate|free|ads', + }; +} + +export interface PricePlan { + name: string; + inr: number; + per: 'month' | 'quarter' | 'year'; + ads: boolean; + note?: string; +} + +export interface PriceEntry { + provider_id: number; + name: string; + plans: PricePlan[]; + note?: string; + source?: string; + verified: string | null; +} + +export interface PriceFile { + version: 1; + region: string; + providers: PriceEntry[]; +} + +const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; +const PLAN_PERIODS: ReadonlySet = new Set(['month', 'quarter', 'year']); + +function isFiniteNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value); +} + +export function isPriceFresh( + verified: string | null, + today: string, + staleAfterDays: number, +): boolean { + if (verified === null || !ISO_DATE.test(verified) || !ISO_DATE.test(today)) return false; + const verifiedMs = Date.parse(`${verified}T00:00:00Z`); + const todayMs = Date.parse(`${today}T00:00:00Z`); + if (Number.isNaN(verifiedMs) || Number.isNaN(todayMs)) return false; + const ageDays = Math.floor((todayMs - verifiedMs) / 86_400_000); + return ageDays >= 0 && ageDays <= staleAfterDays; +} + +/** Monthly plans first, else the lowest price overall. */ +export function cheapestPlan(entry: PriceEntry): PricePlan | null { + if (entry.plans.length === 0) return null; + const monthly = entry.plans.filter((p) => p.per === 'month'); + const pool = monthly.length > 0 ? monthly : entry.plans; + return pool.reduce((min, plan) => (plan.inr < min.inr ? plan : min)); +} + +function parsePlan(raw: unknown): PricePlan | null { + if (!isRecord(raw)) return null; + if (typeof raw.name !== 'string' || !isFiniteNumber(raw.inr)) return null; + if (typeof raw.per !== 'string' || !PLAN_PERIODS.has(raw.per)) return null; + if (typeof raw.ads !== 'boolean') return null; + const plan: PricePlan = { + name: raw.name, + inr: raw.inr, + per: raw.per as PricePlan['per'], + ads: raw.ads, + }; + if (typeof raw.note === 'string') plan.note = raw.note; + return plan; +} + +function parseEntry(raw: unknown): PriceEntry | null { + if (!isRecord(raw)) return null; + if ( + !isFiniteNumber(raw.provider_id) || + typeof raw.name !== 'string' || + !Array.isArray(raw.plans) + ) { + return null; + } + const plans = raw.plans.map(parsePlan).filter((p): p is PricePlan => p !== null); + const verified = + typeof raw.verified === 'string' && ISO_DATE.test(raw.verified) ? raw.verified : null; + const entry: PriceEntry = { provider_id: raw.provider_id, name: raw.name, plans, verified }; + if (typeof raw.note === 'string') entry.note = raw.note; + if (typeof raw.source === 'string') entry.source = raw.source; + return entry; +} + +/** Never throws: a hand-edited file with a typo keeps every other entry instead of failing closed. */ +export function parsePriceFile(raw: unknown): PriceFile { + const fallback: PriceFile = { version: 1, region: 'IN', providers: [] }; + if (!isRecord(raw)) return fallback; + const region = typeof raw.region === 'string' ? raw.region : 'IN'; + const providersRaw = Array.isArray(raw.providers) ? raw.providers : []; + const providers = providersRaw.map(parseEntry).filter((p): p is PriceEntry => p !== null); + return { version: 1, region, providers }; +} diff --git a/src/lib/providers.ts b/src/lib/providers.ts new file mode 100644 index 0000000..ddfcfe7 --- /dev/null +++ b/src/lib/providers.ts @@ -0,0 +1,91 @@ +import { useQueries, useQuery } from '@tanstack/react-query'; +import { useMemo } from 'react'; +import { app } from '../../config/app.config'; +import { PROVIDER_ALIASES } from '../../config/providers'; +import { DATA_VERSION, fetchData, publicUrl } from './data'; +import { type TitleSummary, titleKey } from './model'; +import { + type Availability, + expandOwned, + type PriceFile, + type ProviderCatalogItem, + parsePriceFile, +} from './providers-format'; +import { queryKeys } from './queries'; +import { getWatchProviders } from './tmdb'; + +const DAY = 24 * 60 * 60 * 1000; + +/** `data/providers-tmdb-in.json`, folded nightly (docs/phase-2-plan.md §3.2, §4.6). Only the + * picker needs it; when absent (catalogue not built yet), the picker falls back to names from + * `config/providers.ts` with no logos. */ +export function useProviderCatalog() { + return useQuery({ + queryKey: ['catalog', 'providers-in', DATA_VERSION], + queryFn: ({ signal }) => fetchData('providers-tmdb-in.json', signal), + staleTime: Number.POSITIVE_INFINITY, + }); +} + +/** Memoised `expandOwned(ownedProviders, PROVIDER_ALIASES)` — owning a canonical ID also covers + * its plan variants (e.g. owning Prime Video also matches "Prime Video with Ads"). */ +export function useOwnedSet(owned: readonly number[]): ReadonlySet { + return useMemo(() => expandOwned(owned, PROVIDER_ALIASES), [owned]); +} + +/** The hand-maintained price file (docs/phase-2-plan.md §3.6, §4.5). Gated on the feature flag so + * a title page never spends a request on it while the block is dark. */ +export function usePrices() { + return useQuery({ + queryKey: ['prices', 'providers-in', DATA_VERSION], + queryFn: async ({ signal }): Promise => { + const res = await fetch(publicUrl('providers-in.json'), { signal }); + if (res.status === 404) return null; + if (!res.ok) throw new Error(`providers-in.json returned ${res.status}`); + return parsePriceFile(await res.json()); + }, + enabled: app.features.watchProviders, + staleTime: Number.POSITIVE_INFINITY, + }); +} + +export interface WatchLookups { + /** Resolved availability per title (titleKey), region already selected. Missing = still + * pending or failed — callers treat that as "unknown", never as "not on your services". */ + byKey: ReadonlyMap; + pending: boolean; +} + +/** + * Per-result availability lookups for a visible page of live search results (docs/phase-2-plan.md + * §3.5) — `/search/multi` cannot filter by provider, so each card on the page gets its own + * `/watch/providers` call instead. Cached like other TMDB queries (`queryKeys.watch`), 1-day gc. + */ +export function useWatchLookups( + items: readonly TitleSummary[], + region: string, + enabled: boolean, +): WatchLookups { + const results = useQueries({ + queries: items.map((item) => ({ + queryKey: queryKeys.watch(item.type, item.id), + queryFn: ({ signal }: { signal?: AbortSignal }) => + getWatchProviders(item.type, item.id, signal), + enabled, + gcTime: DAY, + })), + }); + + return useMemo(() => { + const byKey = new Map(); + let pending = false; + items.forEach((item, index) => { + const result = results[index]; + if (!result) return; + if (result.isPending) pending = true; + const availability = result.data?.byRegion[region]; + if (availability) byKey.set(titleKey(item.type, item.id), availability); + }); + return { byKey, pending: enabled && pending }; + }, [items, results, region, enabled]); +} diff --git a/src/lib/queries.ts b/src/lib/queries.ts index ae36f65..e70ada3 100644 --- a/src/lib/queries.ts +++ b/src/lib/queries.ts @@ -2,7 +2,13 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query'; import type { CatalogRail } from './catalog-format'; import { DATA_VERSION, fetchData } from './data'; import type { MediaType } from './model'; -import { discoverTitles, discoverTitlesPages, getTitle, searchTitles } from './tmdb'; +import { + discoverTitles, + discoverTitlesPages, + getTitle, + getWatchProviders, + searchTitles, +} from './tmdb'; /** * Every TMDB query key starts with 'tmdb'. Only those are persisted to localStorage; catalogue @@ -15,6 +21,7 @@ export const queryKeys = { discover: (type: MediaType, params: Record) => ['tmdb', 'discover', type, params] as const, rail: (id: string) => ['catalog', id, DATA_VERSION] as const, + watch: (type: MediaType, id: number) => ['tmdb', 'watch', type, id] as const, }; export function useTitle(type: MediaType, id: number) { @@ -24,6 +31,14 @@ export function useTitle(type: MediaType, id: number) { }); } +export function useWatchProviders(type: MediaType, id: number, enabled: boolean) { + return useQuery({ + queryKey: queryKeys.watch(type, id), + queryFn: ({ signal }) => getWatchProviders(type, id, signal), + enabled, + }); +} + export function useSearch(query: string, page: number, region: string) { const trimmed = query.trim(); return useQuery({ diff --git a/src/lib/tmdb-types.ts b/src/lib/tmdb-types.ts index c688472..d4301f7 100644 --- a/src/lib/tmdb-types.ts +++ b/src/lib/tmdb-types.ts @@ -86,11 +86,39 @@ export interface TmdbExternalIds { imdb_id: string | null; } +export interface TmdbWatchProvider { + provider_id: number; + provider_name: string; + logo_path: string | null; + display_priority: number; +} + +export interface TmdbWatchRegion { + link?: string; + flatrate?: TmdbWatchProvider[]; + free?: TmdbWatchProvider[]; + ads?: TmdbWatchProvider[]; + rent?: TmdbWatchProvider[]; + buy?: TmdbWatchProvider[]; +} + +/** `/movie|tv/{id}/watch/providers`; also the appended `'watch/providers'` key (no `id`). */ +export interface TmdbWatchProviders { + id?: number; + results: Record; +} + +/** `/watch/providers/{movie|tv}?watch_region=IN` entries. */ +export interface TmdbProviderCatalogEntry extends TmdbWatchProvider { + display_priorities?: Record; +} + interface TmdbDetailAppends { credits?: TmdbCredits; videos?: { results: TmdbVideo[] }; recommendations?: TmdbPage; external_ids?: TmdbExternalIds; + 'watch/providers'?: TmdbWatchProviders; } export interface TmdbMovieDetail diff --git a/src/lib/tmdb.ts b/src/lib/tmdb.ts index 5ff6cbd..9ad8fb7 100644 --- a/src/lib/tmdb.ts +++ b/src/lib/tmdb.ts @@ -1,3 +1,4 @@ +import { app } from '../../config/app.config'; import { type MediaType, movieDetailToModel, @@ -7,6 +8,7 @@ import { toSummary, tvDetailToModel, } from './model'; +import { toWatchInfo, type WatchInfo } from './providers-format'; import type { TmdbExternalIds, TmdbMovieDetail, @@ -14,6 +16,7 @@ import type { TmdbPage, TmdbTitleResult, TmdbTvDetail, + TmdbWatchProviders, } from './tmdb-types'; const API_BASE = 'https://api.themoviedb.org/3'; @@ -123,7 +126,11 @@ export async function searchTitles( }; } -const DETAIL_APPENDS = 'credits,videos,recommendations,external_ids'; +const BASE_DETAIL_APPENDS = 'credits,videos,recommendations,external_ids'; +/** Kept off the wire (~2 KB) until `app.features.watchProviders` is on; see M8. */ +const DETAIL_APPENDS = app.features.watchProviders + ? `${BASE_DETAIL_APPENDS},watch/providers` + : BASE_DETAIL_APPENDS; /** One request per title page: `append_to_response` folds four endpoints into one. */ export async function getTitle( @@ -137,14 +144,24 @@ export async function getTitle( { append_to_response: DETAIL_APPENDS }, signal, ); - return movieDetailToModel(raw); + return movieDetailToModel(raw, app.regions); } const raw = await tmdbGet( `/tv/${id}`, { append_to_response: DETAIL_APPENDS }, signal, ); - return tvDetailToModel(raw); + return tvDetailToModel(raw, app.regions); +} + +/** Standalone endpoint (no `append_to_response`): used by search lookups and the nightly job. */ +export async function getWatchProviders( + type: MediaType, + id: number, + signal?: AbortSignal, +): Promise { + const raw = await tmdbGet(`/${type}/${id}/watch/providers`, {}, signal); + return toWatchInfo(raw, app.regions) ?? { byRegion: {}, providers: {} }; } export interface DiscoverResults { diff --git a/src/store/preferences.test.ts b/src/store/preferences.test.ts new file mode 100644 index 0000000..e3ac418 --- /dev/null +++ b/src/store/preferences.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { sanitizeOwned } from './preferences'; + +describe('sanitizeOwned', () => { + it('drops non-integers, non-positive numbers and duplicates', () => { + expect(sanitizeOwned([8, 8, -1, 'x', 1.5, 119])).toEqual([8, 119]); + }); + + it('caps the list at 50 entries', () => { + const many = Array.from({ length: 60 }, (_, n) => n + 1); + expect(sanitizeOwned(many)).toHaveLength(50); + }); + + it('returns an empty list for anything that is not an array', () => { + expect(sanitizeOwned(undefined)).toEqual([]); + expect(sanitizeOwned('nope')).toEqual([]); + }); +}); diff --git a/src/store/preferences.ts b/src/store/preferences.ts index e4edb6a..850e518 100644 --- a/src/store/preferences.ts +++ b/src/store/preferences.ts @@ -5,25 +5,69 @@ import { app, type Region } from '../../config/app.config'; interface PreferencesState { region: Region; setRegion: (region: Region) => void; + /** Canonical TMDB provider IDs (e.g. 119, not 2100) the viewer says they pay for. */ + ownedProviders: number[]; + setOwnedProviders: (ids: number[]) => void; + toggleOwnedProvider: (id: number) => void; + /** "Watchable now" lens: personal, so it is never a URL parameter (docs/phase-2-plan.md §3.5). */ + watchableOnly: boolean; + setWatchableOnly: (on: boolean) => void; } export function isRegion(value: unknown): value is Region { return typeof value === 'string' && (app.regions as readonly string[]).includes(value); } +/** Unique positive integers, capped at 50 — a hand-edited or corrupted localStorage value should + * never crash the picker or blow up a discover query string. */ +export function sanitizeOwned(value: unknown): number[] { + if (!Array.isArray(value)) return []; + const seen = new Set(); + for (const item of value) { + if (typeof item !== 'number' || !Number.isInteger(item) || item <= 0) continue; + seen.add(item); + if (seen.size >= 50) break; + } + return [...seen]; +} + +const STORAGE_KEY = 'interval-prefs'; + export const usePreferences = create()( persist( (set) => ({ region: app.defaultRegion, setRegion: (region) => set({ region }), + ownedProviders: [], + setOwnedProviders: (ids) => set({ ownedProviders: sanitizeOwned(ids) }), + toggleOwnedProvider: (id) => + set((state) => + state.ownedProviders.includes(id) + ? { ownedProviders: state.ownedProviders.filter((p) => p !== id) } + : { ownedProviders: sanitizeOwned([...state.ownedProviders, id]) }, + ), + watchableOnly: false, + setWatchableOnly: (watchableOnly) => set({ watchableOnly }), }), { - name: 'interval-prefs', + name: STORAGE_KEY, version: 1, merge: (persisted, current) => { - const region = (persisted as Partial | undefined)?.region; - return { ...current, region: isRegion(region) ? region : app.defaultRegion }; + const p = persisted as Partial | undefined; + return { + ...current, + region: isRegion(p?.region) ? p.region : app.defaultRegion, + ownedProviders: sanitizeOwned(p?.ownedProviders), + watchableOnly: typeof p?.watchableOnly === 'boolean' ? p.watchableOnly : false, + }; }, }, ), ); + +/** Keeps two open tabs in agreement (mirrors src/store/watchlist.ts). */ +if (typeof window !== 'undefined') { + window.addEventListener('storage', (event) => { + if (event.key === STORAGE_KEY) void usePreferences.persist.rehydrate(); + }); +} diff --git a/src/store/ui.ts b/src/store/ui.ts index fedcc30..5b0f209 100644 --- a/src/store/ui.ts +++ b/src/store/ui.ts @@ -1,11 +1,13 @@ import { create } from 'zustand'; -type Overlay = 'palette' | 'shortcuts' | null; +type Overlay = 'palette' | 'shortcuts' | 'services' | null; interface UiState { overlay: Overlay; /** Set once the palette has been opened, so its code is only loaded on first use. */ paletteLoaded: boolean; + /** Same idea for the services picker (docs/phase-2-plan.md §3.4). */ + servicesLoaded: boolean; open: (overlay: Exclude) => void; close: () => void; togglePalette: () => void; @@ -14,8 +16,13 @@ interface UiState { export const useUi = create()((set) => ({ overlay: null, paletteLoaded: false, + servicesLoaded: false, open: (overlay) => - set((s) => ({ overlay, paletteLoaded: s.paletteLoaded || overlay === 'palette' })), + set((s) => ({ + overlay, + paletteLoaded: s.paletteLoaded || overlay === 'palette', + servicesLoaded: s.servicesLoaded || overlay === 'services', + })), close: () => set({ overlay: null }), togglePalette: () => set((s) => diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index 8895481..e08ac93 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -101,3 +101,12 @@ export function ExternalIcon(props: IconProps) { ); } + +export function TvIcon(props: IconProps) { + return ( + + + + + ); +}