Download tasks/imdb/solution/site/implementation/clone/app.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 111 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/imdb/solution/site/implementation/clone/app.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/imdb/solution/site/implementation/clone/app.py
-
curl -L -o app.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/imdb/solution/site/implementation/clone/app.py
111 kB
| """IMDb offline clone — persistent backend (stage: backend). | |
| Local-only FastAPI + Jinja2 app backed by a stdlib sqlite3 database (WAL) | |
| that lives under WEBSITEBENCH_DATA_DIR (default materials/imdb/data, outside | |
| this candidate tree). Titles, people, accounts, watchlists, ratings, reviews, | |
| and custom lists are ordinary database rows; every rule (rating 1-10, | |
| idempotent watchlist adds, owner scoping, anonymous redirect-to-signin) | |
| applies generically to any title and any account. Nothing here ever | |
| contacts IMDb or its GraphQL API; seeded aggregates are dated facts from | |
| the source capture and remain immutable while a local account rating is | |
| stored and displayed separately. | |
| """ | |
| from __future__ import annotations | |
| import hmac | |
| import html | |
| import json | |
| import mimetypes | |
| import os | |
| import re | |
| import sqlite3 | |
| import sys | |
| from contextlib import asynccontextmanager, closing | |
| from pathlib import Path | |
| from urllib.parse import parse_qs, quote | |
| import uvicorn | |
| from fastapi import BackgroundTasks, FastAPI, Request | |
| from fastapi.responses import ( | |
| FileResponse, | |
| HTMLResponse, | |
| JSONResponse, | |
| RedirectResponse, | |
| Response, | |
| ) | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| ROOT = Path(__file__).resolve().parent | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from backend import ( # noqa: E402 | |
| ADMIN_TOKEN_HEADER, | |
| CAPTURE_DATE, | |
| CSRF_VALUE, | |
| DEFAULT_PORT, | |
| FIXTURE_ID, | |
| FROZEN_CLOCK, | |
| LOCAL_RATING_DISCLOSURE, | |
| LEGACY_ADMIN_TOKEN_HEADER, | |
| PRIMARY_SESSION_COOKIE, | |
| SEED_AUTH_ACCOUNTS, | |
| SESSION_COOKIE, | |
| SITE_ID, | |
| STAGE, | |
| VERSION, | |
| admin_token, | |
| ) | |
| from backend import db # noqa: E402 | |
| from backend.discovery import STREAMING_SERVICES, services_for_title # noqa: E402 | |
| from backend.media_catalog import load_media_catalog # noqa: E402 | |
| from backend.site_backend_integration import ( # noqa: E402 | |
| auth_mail_worker_token, | |
| open_site_services, | |
| ) | |
| from websitebench.local_clone_auth import ( # noqa: E402 | |
| AuthConflict, | |
| AuthError, | |
| AuthRateLimited, | |
| AuthRejected, | |
| AuthValidationError, | |
| LocalAuthStore, | |
| MAIL_SMTP_PENDING, | |
| ) | |
| from websitebench.public_clone_auth import ( # noqa: E402 | |
| VerificationUnavailable, | |
| load_public_clone_registration_verification, | |
| ) | |
| from websitebench.public_clone_auth.fastapi import ( # noqa: E402 | |
| consume_registration_ticket, | |
| registration_script_response, | |
| send_registration_code, | |
| verify_registration_code, | |
| ) | |
| from websitebench.site_backend import AuthMailDelivery, AuthMailDeliveryError # noqa: E402 | |
| ASSETS_BASE = db.ASSETS_BASE | |
| PUBLIC_REGISTRATION_VERIFICATION = load_public_clone_registration_verification() | |
| FOREIGN_LIST_ID = db.FOREIGN_LIST_ID | |
| TITLE_EDITORIAL = { | |
| "tt0468569": { | |
| "asset_group": "title-dark-knight", | |
| "video_count": "42", | |
| "photo_count": "808", | |
| "user_review_count": "9.3K", | |
| "critic_review_count": "316", | |
| "award": "Won 2 Oscars · 164 wins & 165 nominations total", | |
| "cast": [ | |
| ("Christian Bale", "Bruce Wayne"), | |
| ("Heath Ledger", "Joker"), | |
| ("Aaron Eckhart", "Harvey Dent"), | |
| ("Michael Caine", "Alfred"), | |
| ], | |
| "review_author": "harrybhangu", | |
| "review_title": "Perfect combo", | |
| "review_body": ( | |
| "Best movie ever. Heath Ledger's work is phenomenal. The mature, " | |
| "intelligent script and the extraordinary performances make this " | |
| "a superhero story with real depth." | |
| ), | |
| "trivia": ( | |
| "Michael Caine said Heath Ledger's Joker took a completely " | |
| "different and frightening direction; Ledger's first entrance " | |
| "was so convincing that Caine forgot his lines." | |
| ), | |
| "quote": ( | |
| "The Joker: If you're good at something, never do it for free." | |
| ), | |
| "details": [ | |
| ("Release date", "July 18, 2008 (United States)"), | |
| ("Countries of origin", "United States · United Kingdom"), | |
| ("Languages", "English · Mandarin"), | |
| ("Filming locations", "Chicago, Illinois, USA"), | |
| ("Production companies", "Warner Bros. · Legendary Pictures · DC Comics"), | |
| ], | |
| "box_office": [ | |
| ("Budget", "$185,000,000 (estimated)"), | |
| ("Gross US & Canada", "$534,987,076"), | |
| ("Opening weekend US & Canada", "$158,411,483"), | |
| ("Gross worldwide", "$1,008,480,203"), | |
| ], | |
| }, | |
| "tt0816692": { | |
| "asset_group": "title-interstellar", | |
| "video_count": "31", | |
| "photo_count": "674", | |
| "user_review_count": "7.3K", | |
| "critic_review_count": "466", | |
| "award": "Won 1 Oscar · 45 wins & 148 nominations total", | |
| "cast": [ | |
| ("Matthew McConaughey", "Cooper"), | |
| ("Anne Hathaway", "Brand"), | |
| ("Jessica Chastain", "Murph"), | |
| ("Ellen Burstyn", "Murph (older)"), | |
| ], | |
| "review_author": "e-jackson1985", | |
| "review_title": "Masterpiece", | |
| "review_body": ( | |
| "The story, acting, cinematography, effects, sound, and production " | |
| "are remarkable. Hans Zimmer's score gives the film its immense " | |
| "emotional scale." | |
| ), | |
| "trivia": ( | |
| "Physicist Kip Thorne required that the story respect established " | |
| "physical laws and that its speculation grow from science. " | |
| "Christopher Nolan accepted those terms for the production." | |
| ), | |
| "quote": ( | |
| "Cooper: We used to look up at the sky and wonder at our place " | |
| "in the stars. Now we just look down." | |
| ), | |
| "details": [ | |
| ("Release date", "November 7, 2014 (United States)"), | |
| ("Countries of origin", "United States · United Kingdom · Canada"), | |
| ("Languages", "English"), | |
| ("Filming locations", "Alberta, Canada"), | |
| ("Production companies", "Paramount Pictures · Warner Bros. · Legendary Pictures"), | |
| ], | |
| "box_office": [ | |
| ("Budget", "$165,000,000 (estimated)"), | |
| ("Gross US & Canada", "$203,227,367"), | |
| ("Opening weekend US & Canada", "$47,510,360"), | |
| ("Gross worldwide", "$731,122,151"), | |
| ], | |
| }, | |
| "tt0110912": { | |
| "asset_group": "title-pulp-fiction", | |
| "video_count": "35", | |
| "photo_count": "605", | |
| "user_review_count": "3.9K", | |
| "critic_review_count": "283", | |
| "award": "Won 1 Oscar · 69 wins & 73 nominations total", | |
| "cast": [ | |
| ("John Travolta", "Vincent Vega"), | |
| ("Uma Thurman", "Mia Wallace"), | |
| ("Samuel L. Jackson", "Jules Winnfield"), | |
| ("Tim Roth", "Pumpkin"), | |
| ], | |
| "review_author": "tfrizzell", | |
| "review_title": "It's Wild, It's Chaotic, It's Pulp Fiction!", | |
| "review_body": ( | |
| "Quentin Tarantino's nonlinear crime story is original and " | |
| "unforgettable. Its screenplay, direction, dialogue, and ensemble " | |
| "performances helped redefine American independent film." | |
| ), | |
| "trivia": ( | |
| "The movie cost about $8 million, with a large share going to the " | |
| "cast. Its worldwide rights made it profitable before release, and " | |
| "it went on to gross more than $200 million." | |
| ), | |
| "quote": ( | |
| "Mia: Don't you hate uncomfortable silences? That is when you know " | |
| "you have found somebody special." | |
| ), | |
| "details": [ | |
| ("Release date", "October 14, 1994 (United States)"), | |
| ("Country of origin", "United States"), | |
| ("Languages", "English · Spanish · French"), | |
| ("Filming locations", "Los Angeles, California, USA"), | |
| ("Production companies", "Miramax · A Band Apart · Jersey Films"), | |
| ], | |
| "box_office": [ | |
| ("Budget", "$8,000,000 (estimated)"), | |
| ("Gross US & Canada", "$107,928,762"), | |
| ("Opening weekend US & Canada", "$9,311,882"), | |
| ("Gross worldwide", "$213,928,762"), | |
| ], | |
| }, | |
| } | |
| HOME_ASSET_BASE = "/static/assets/source-current/2026-08-11/home" | |
| HOME_HERO = { | |
| "image": f"{HOME_ASSET_BASE}/d53c128723a330fd.jpg", | |
| "poster": f"{HOME_ASSET_BASE}/76a69d3eb4482954.jpg", | |
| "title": "'The Only Living Pickpocket in New York'", | |
| "caption": "Watch the Trailer", | |
| "duration": "2:17", | |
| "href": "/video/vi2243086873/", | |
| } | |
| HOME_UP_NEXT = ( | |
| { | |
| "image": f"{HOME_ASSET_BASE}/a6a8aa818728a221.jpg", | |
| "title": "'Paper Tiger'", | |
| "caption": "Watch the Trailer", | |
| "duration": "1:01", | |
| "href": "/video/vi3065367065/", | |
| }, | |
| { | |
| "image": f"{HOME_ASSET_BASE}/26028eb4ee389cea.jpg", | |
| "title": "Robert Pattinson Stars in 'Primetime'", | |
| "caption": "Watch the Trailer", | |
| "duration": "2:10", | |
| "href": "/video/vi2410859033/", | |
| }, | |
| { | |
| "image": f"{HOME_ASSET_BASE}/a39935ac9568e0cb.jpg", | |
| "title": "'Your Mother Your Mother Your Mother'", | |
| "caption": "Watch Mahershala Ali With a Blade", | |
| "duration": "2:05", | |
| "href": "/video/vi2521811737/", | |
| }, | |
| ) | |
| HOME_FEATURES = ( | |
| { | |
| "image": f"{HOME_ASSET_BASE}/33b8bec848151dcb.jpg", | |
| "eyebrow": "List", | |
| "title": "What to Watch in August", | |
| "cta": "See the August picks", | |
| "href": "/most-anticipated/this-month/", | |
| }, | |
| { | |
| "image": f"{HOME_ASSET_BASE}/5329b96d1b8d1594.jpg", | |
| "eyebrow": "IMDb Interviews", | |
| "title": "The Stars Take Us Behind the Scenes", | |
| "cta": "Watch the interviews", | |
| "href": "/originals/", | |
| }, | |
| { | |
| "image": f"{HOME_ASSET_BASE}/81e3494a9e340a38.jpg", | |
| "eyebrow": "Staff picks", | |
| "title": "Movies and Series We Recommend", | |
| "cta": "See our picks", | |
| "href": "/imdbpicks/staff-picks/", | |
| }, | |
| { | |
| "image": f"{HOME_ASSET_BASE}/8b284a6e74a54171.jpg", | |
| "eyebrow": "Gallery", | |
| "title": "On Set With This Summer's Biggest Casts", | |
| "cta": "See the gallery", | |
| "href": "/gallery/summer-casts/", | |
| }, | |
| ) | |
| HOME_RECOMMENDATIONS = ( | |
| ("Ted Lasso", "8.7", f"{HOME_ASSET_BASE}/8cde5d1eae206ed6.jpg", "/title/tt0816692/"), | |
| ("Sterling Point", "7.3", f"{HOME_ASSET_BASE}/26028eb4ee389cea.jpg", "/what-to-watch/"), | |
| ("The Shards", "5.8", f"{HOME_ASSET_BASE}/a39935ac9568e0cb.jpg", "/what-to-watch/"), | |
| ("Lucky", "6.6", f"{HOME_ASSET_BASE}/cc78d977470ae249.jpg", "/what-to-watch/"), | |
| ("The Odyssey", "8.8", f"{HOME_ASSET_BASE}/33b8bec848151dcb.jpg", "/most-anticipated/this-month/"), | |
| ("Primetime", "7.9", f"{HOME_ASSET_BASE}/26028eb4ee389cea.jpg", "/trailers/"), | |
| ) | |
| CATALOG_PATH = ROOT / "catalog.json" | |
| STATIC_VERSION = "imdb-ui-catalog-2026-08-14.2" | |
| def load_catalog() -> dict[str, list[dict]]: | |
| """Load the frozen, local-only movie catalog captured for this build.""" | |
| if not CATALOG_PATH.is_file(): | |
| return {"top": [], "popular": []} | |
| payload = json.loads(CATALOG_PATH.read_text(encoding="utf-8")) | |
| return { | |
| "top": list(payload.get("top", [])), | |
| "popular": list(payload.get("popular", [])), | |
| } | |
| MOVIE_CATALOG = load_catalog() | |
| TOP_MOVIES = MOVIE_CATALOG["top"] | |
| POPULAR_MOVIES = MOVIE_CATALOG["popular"] | |
| CATALOG_BY_ID: dict[str, dict] = {} | |
| for catalog_movie in [*TOP_MOVIES, *POPULAR_MOVIES]: | |
| existing = CATALOG_BY_ID.get(catalog_movie["id"], {}) | |
| CATALOG_BY_ID[catalog_movie["id"]] = {**catalog_movie, **existing} | |
| MEDIA_CATALOG = load_media_catalog( | |
| db.ALL_TITLES, | |
| tuple(item["id"] for item in db.SEED_TITLES), | |
| tuple(item[0] for item in db.SEED_PEOPLE), | |
| ) | |
| VIDEO_BY_ID = {item["id"]: item for item in MEDIA_CATALOG["videos"]} | |
| LEGACY_VIDEO_ALIASES = { | |
| "vi2243086873": "local-feature-01", | |
| "vi3065367065": "local-feature-02", | |
| "vi2410859033": "local-feature-03", | |
| "vi2521811737": "local-feature-04", | |
| } | |
| def compact_count(value: int | None) -> str: | |
| if value is None: | |
| return "" | |
| if value >= 1_000_000: | |
| return f"{value / 1_000_000:.1f}M".replace(".0M", "M") | |
| if value >= 1_000: | |
| return f"{value / 1_000:.1f}K".replace(".0K", "K") | |
| return str(value) | |
| def catalog_search(query: str, limit: int = 50) -> list[dict]: | |
| folded = query.casefold().strip() | |
| if not folded: | |
| return [] | |
| matches = [ | |
| movie for movie in CATALOG_BY_ID.values() | |
| if folded in movie["title"].casefold() | |
| or folded in str(movie.get("credit", "")).casefold() | |
| ] | |
| matches.sort( | |
| key=lambda movie: ( | |
| movie["title"].casefold() != folded, | |
| int(movie.get("rank") or 9999), | |
| movie["title"].casefold(), | |
| ) | |
| ) | |
| return [ | |
| { | |
| "title": movie["title"], | |
| "local_id": movie["id"], | |
| "year": str(movie.get("year") or ""), | |
| "runtime": "Movie", | |
| "cert": "", | |
| "metascore": None, | |
| "rating": movie.get("rating") or "—", | |
| "votes": compact_count(movie.get("votes")), | |
| "thumb": movie["poster"], | |
| } | |
| for movie in matches[:limit] | |
| ] | |
| MENU_GROUPS = ( | |
| ( | |
| "Movies", | |
| ( | |
| ("Release calendar", "/calendar/"), | |
| ("Top 250 movies", "/chart/top/"), | |
| ("Most popular movies", "/chart/moviemeter/"), | |
| ("Browse movies by genre", "/interest/all/"), | |
| ("Top box office", "/chart/boxoffice/"), | |
| ("Showtimes & tickets", "/showtimes/"), | |
| ("Movie news", "/news/movie/"), | |
| ("India movie spotlight", "/india/top-rated-indian-movies/"), | |
| ), | |
| ), | |
| ( | |
| "TV Shows", | |
| ( | |
| ("What's on TV & streaming", "/whats-on-tv/"), | |
| ("Top 250 TV shows", "/chart/toptv/"), | |
| ("Most popular TV shows", "/chart/tvmeter/"), | |
| ("Browse TV shows by genre", "/interest/all/"), | |
| ("TV news", "/news/tv/"), | |
| ), | |
| ), | |
| ( | |
| "Watch", | |
| ( | |
| ("What to watch", "/what-to-watch/"), | |
| ("Latest trailers", "/trailers/"), | |
| ("IMDb Originals", "/originals/"), | |
| ("IMDb Picks", "/imdbpicks/"), | |
| ("IMDb Spotlight", "/spotlight/"), | |
| ("Family entertainment guide", "/family-entertainment-guide/"), | |
| ("IMDb Podcasts", "/search/title/?title_type=podcastSeries"), | |
| ), | |
| ), | |
| ( | |
| "Awards & Events", | |
| ( | |
| ("Oscars", "/oscars/"), | |
| ("Primetime Emmys", "/emmys/"), | |
| ("San Diego Comic-Con", "/comic-con/"), | |
| ("Summer Watch Guide", "/imdbpicks/summer-watch-guide/"), | |
| ("Most Anticipated This Month", "/most-anticipated/this-month/"), | |
| ("IMDb Labs", "/labs/"), | |
| ("STARmeter Awards", "/starmeterawards/"), | |
| ("Awards Central", "/awards-central/"), | |
| ("Festival Central", "/festival-central/"), | |
| ("All events", "/event/all/"), | |
| ), | |
| ), | |
| ( | |
| "Celebs", | |
| ( | |
| ("Born today", "/feature/bornondate/"), | |
| ("Trending people", "/chart/starmeter/"), | |
| ("Celebrity news", "/news/celebrity/"), | |
| ), | |
| ), | |
| ) | |
| BROWSE_PAGES = { | |
| "/calendar/": ("Release calendar", "Browse included movie releases by their recorded year."), | |
| "/chart/top/": ("IMDb Top 250 Movies", "The highest-rated movies from IMDb users."), | |
| "/chart/moviemeter/": ("Most Popular Movies", "The movies people are watching right now."), | |
| "/interest/all/": ("Browse by Genre", "Find movies and TV shows for every mood."), | |
| "/chart/boxoffice/": ("Top Box Office", "This week's top-grossing movies."), | |
| "/showtimes/": ("Showtimes & Tickets", "Discover movies playing near you."), | |
| "/news/movie/": ("Movie News", "The latest movie headlines and interviews."), | |
| "/india/top-rated-indian-movies/": ("India Movie Spotlight", "Four Indian films represented in the included movie directory."), | |
| "/whats-on-tv/": ("What's on TV & Streaming", "Current and upcoming shows across popular services."), | |
| "/chart/toptv/": ("IMDb Top 250 TV Shows", "The highest-rated series from IMDb users."), | |
| "/chart/tvmeter/": ("Most Popular TV Shows", "The series people are watching right now."), | |
| "/news/tv/": ("TV News", "The latest television and streaming headlines."), | |
| "/what-to-watch/": ("What to Watch", "Personalized ideas for your next movie night."), | |
| "/trailers/": ("Latest Trailers", "Watch the newest movie and television trailers."), | |
| "/originals/": ("IMDb Originals", "Interviews, games, and original video series."), | |
| "/imdbpicks/": ("IMDb Picks", "Fresh recommendations selected by IMDb editors."), | |
| "/imdbpicks/staff-picks/": ("Staff Picks", "Movies and series recommended by IMDb staff."), | |
| "/spotlight/": ("IMDb Spotlight", "Stories and collections worth discovering."), | |
| "/family-entertainment-guide/": ("Family Entertainment Guide", "Movies and shows for the whole family."), | |
| "/search/title/": ("IMDb Podcasts", "Discover podcast series and audio entertainment."), | |
| "/most-anticipated/this-month/": ("Most Anticipated This Month", "The upcoming titles fans cannot wait to see."), | |
| "/imdbpicks/summer-watch-guide/": ("Summer Watch Guide", "Movies and series made for summer viewing."), | |
| "/labs/": ("IMDb Labs", "Explore experimental IMDb features and ideas."), | |
| "/starmeterawards/": ("STARmeter Awards", "Celebrating the stars fans search for most."), | |
| "/oscars/": ("Oscars", "Awards coverage, nominees, winners, and memorable moments."), | |
| "/emmys/": ("Primetime Emmys", "The latest nominees, winners, and television highlights."), | |
| "/comic-con/": ("San Diego Comic-Con", "Trailers, panels, and news from Comic-Con."), | |
| "/awards-central/": ("Awards Central", "Your guide to entertainment awards season."), | |
| "/festival-central/": ("Festival Central", "News and highlights from film festivals worldwide."), | |
| "/event/all/": ("All Events", "Explore entertainment awards and events."), | |
| "/feature/bornondate/": ("Born Today", "Popular actors, directors, and creators born today."), | |
| "/chart/starmeter/": ("Trending People", "The stars generating the most interest this week."), | |
| "/news/celebrity/": ("Celebrity News", "The latest stories about actors and creators."), | |
| "/poll/": ("IMDb Polls", "Explore a question and open one of the included titles."), | |
| "/site-index/": ("IMDb Site Index", "Browse the main destinations available on IMDb."), | |
| "/preferences/preferredservices/": ("Preferred Services", "Choose the streaming services you use most."), | |
| "/gallery/summer-casts/": ("Summer Casts", "Behind-the-scenes photos from this season's biggest titles."), | |
| "/availability/imdbpro/": ("IMDbPro", "IMDbPro is an external service and is unavailable in this offline clone."), | |
| "/availability/help/": ("IMDb Help", "The external IMDb help center is unavailable in this offline clone."), | |
| "/availability/contributor/": ("Contributor Zone", "External contribution tools are unavailable in this offline clone."), | |
| "/availability/social/": ("IMDb Social", "External social publishing is unavailable in this offline clone."), | |
| "/availability/app/": ("IMDb App", "The external mobile app download is unavailable in this offline clone."), | |
| "/availability/box-office/": ("Box Office Mojo", "External box-office data is unavailable in this offline clone."), | |
| "/availability/data/": ("License IMDb Data", "External data licensing is unavailable in this offline clone."), | |
| "/availability/conditions/": ("Conditions of Use", "The production legal document is outside this clone's frozen scope."), | |
| "/availability/privacy/": ("Privacy Policy", "The production privacy document is outside this clone's frozen scope."), | |
| "/availability/ads-privacy/": ("Ads Privacy Choices", "Production advertising preferences are unavailable in this offline clone."), | |
| } | |
| BOUNDARY_PAGES = { | |
| "/showtimes/": ( | |
| "showtimes-ticketing", "Showtimes & Tickets", | |
| "Live theater schedules, locations, ticket inventory, and purchasing require an external provider and are not available here.", | |
| ), | |
| "/availability/streaming/": ( | |
| "external-streaming", "Streaming provider", | |
| "Playback subscriptions and provider availability are external services. Browse the included title directory instead.", | |
| ), | |
| "/availability/ticketing/": ( | |
| "ticketing", "Ticketing provider", | |
| "Ticket inventory and purchases are external services and are not available here.", | |
| ), | |
| "/availability/imdbpro/": ( | |
| "imdbpro", "IMDbPro", | |
| "Professional membership, contacts, and industry tools are not included here.", | |
| ), | |
| "/availability/contributor/": ( | |
| "contributor", "Contributor Zone", | |
| "Production contribution and data-submission tools are not included here.", | |
| ), | |
| "/availability/social/": ( | |
| "social", "IMDb on social", | |
| "Social publishing and external social profiles are not available here.", | |
| ), | |
| "/availability/ads-privacy/": ( | |
| "advertising", "Advertising choices", | |
| "Production advertising and ad-personalization controls are not active here.", | |
| ), | |
| "/availability/advertising/": ( | |
| "advertising", "Advertising", | |
| "Advertising campaigns and production ad services are not available here.", | |
| ), | |
| "/availability/payment/": ( | |
| "payment", "Payments", | |
| "Payment, order, and checkout capabilities are not present in this edition.", | |
| ), | |
| "/availability/help/": ( | |
| "external-help", "IMDb Help", | |
| "The external help center is outside the included site. Use the local navigation to continue browsing.", | |
| ), | |
| "/availability/app/": ( | |
| "external-app", "IMDb App", | |
| "App-store downloads and mobile installation are external capabilities and are not available here.", | |
| ), | |
| "/availability/box-office/": ( | |
| "external-data", "Box Office Mojo", | |
| "The external Box Office Mojo service and its live business data are not included here.", | |
| ), | |
| "/availability/data/": ( | |
| "external-data", "License IMDb Data", | |
| "Data licensing and commercial data delivery are external services and are not available here.", | |
| ), | |
| "/availability/conditions/": ( | |
| "external-legal", "Conditions of Use", | |
| "The production legal document is outside the included site.", | |
| ), | |
| "/availability/privacy/": ( | |
| "external-legal", "Privacy Policy", | |
| "The production privacy document is outside the included site.", | |
| ), | |
| } | |
| DISCOVERY_PAGE_TYPES = { | |
| "/calendar/": "calendar", | |
| "/interest/all/": "genres", | |
| "/news/movie/": "news", | |
| "/news/tv/": "news", | |
| "/news/celebrity/": "news", | |
| "/originals/": "originals", | |
| "/imdbpicks/": "editorial-picks", | |
| "/imdbpicks/staff-picks/": "editorial-picks", | |
| "/imdbpicks/summer-watch-guide/": "editorial-picks", | |
| "/spotlight/": "editorial-picks", | |
| "/most-anticipated/this-month/": "editorial-picks", | |
| "/awards-central/": "awards", | |
| "/starmeterawards/": "awards", | |
| "/oscars/": "awards", | |
| "/emmys/": "awards", | |
| "/festival-central/": "events", | |
| "/event/all/": "events", | |
| "/comic-con/": "events", | |
| "/chart/starmeter/": "people-chart", | |
| "/feature/bornondate/": "people-chart", | |
| "/gallery/summer-casts/": "gallery", | |
| "/whats-on-tv/": "tv-discovery", | |
| "/india/top-rated-indian-movies/": "movie-discovery", | |
| "/family-entertainment-guide/": "editorial-picks", | |
| "/search/title/": "title-search", | |
| "/labs/": "product-discovery", | |
| "/poll/": "polls", | |
| "/site-index/": "site-index", | |
| } | |
| DISCOVERY_COLLECTION_IDS = { | |
| "/imdbpicks/": ("tt0111161", "tt0068646", "tt0468569", "tt0816692", "tt0110912", "tt15398776"), | |
| "/imdbpicks/staff-picks/": ("tt0816692", "tt15398776", "tt15239678", "tt0245429", "tt2582802", "tt6751668"), | |
| "/imdbpicks/summer-watch-guide/": ("tt33764258", "tt32897959", "tt12042730", "tt21357150"), | |
| "/spotlight/": ("tt0048473", "tt0986264", "tt1187043", "tt5074352"), | |
| "/most-anticipated/this-month/": ("tt33764258", "tt32897959", "tt12042730", "tt21357150"), | |
| "/family-entertainment-guide/": ("tt0110357", "tt0245429", "tt0435761", "tt2096673"), | |
| "/awards-central/": ("tt15398776", "tt6710474", "tt6751668", "tt0172495", "tt0110912", "tt0245429"), | |
| "/oscars/": ("tt15398776", "tt6710474", "tt6751668", "tt0172495"), | |
| "/emmys/": ("tt0903747", "tt7366338", "tt0944947", "tt4574334"), | |
| "/starmeterawards/": ("tt15239678", "tt15398776", "tt0816692", "tt0468569"), | |
| "/festival-central/": ("tt6751668", "tt0245429", "tt0048473", "tt6710474"), | |
| "/comic-con/": ("tt0468569", "tt15239678", "tt4574334", "tt0944947"), | |
| "/event/all/": ("tt15398776", "tt6751668", "tt15239678", "tt0903747"), | |
| "/india/top-rated-indian-movies/": ("tt0048473", "tt0986264", "tt1187043", "tt5074352"), | |
| } | |
| DISCOVERY_ROUTE_LINKS = { | |
| "awards": ( | |
| ("Oscars", "/oscars/"), ("Primetime Emmys", "/emmys/"), | |
| ("STARmeter Awards", "/starmeterawards/"), ("Awards Central", "/awards-central/"), | |
| ), | |
| "events": ( | |
| ("San Diego Comic-Con", "/comic-con/"), ("Festival Central", "/festival-central/"), | |
| ("Awards Central", "/awards-central/"), ("All events", "/event/all/"), | |
| ), | |
| } | |
| DISCOVERY_NEWS = { | |
| "/news/movie/": ( | |
| ("Movie directory desk", "Explore The Odyssey and other films drawing attention in the included catalog.", "/title/tt33764258/", "tt33764258"), | |
| ("Behind the camera", "Browse Christopher Nolan's linked directing credits.", "/name/nm0634240/", "tt15398776"), | |
| ("Movie trailers", "Watch the included local trailer collection.", "/trailers/", "tt0468569"), | |
| ), | |
| "/news/tv/": ( | |
| ("TV directory desk", "Explore the four series represented in the included directory.", "/chart/tvmeter/", "tt0903747"), | |
| ("Episode spotlight", "Open Ozymandias and its linked series entry.", "/title/tt2301451/", "tt2301451"), | |
| ("TV ratings chart", "Compare the included top-rated series.", "/chart/toptv/", "tt7366338"), | |
| ), | |
| "/news/celebrity/": ( | |
| ("People directory desk", "See the people generating interest across the included directory.", "/chart/starmeter/", None), | |
| ("Christopher Nolan", "Explore directing and writing credits linked in the directory.", "/name/nm0634240/", "tt15398776"), | |
| ("Zendaya", "Explore Zendaya's linked title credits.", "/name/nm3918035/", "tt15239678"), | |
| ), | |
| } | |
| templates = Jinja2Templates(directory=str(ROOT / "frontend" / "templates")) | |
| templates.env.globals["public_registration_enabled"] = ( | |
| PUBLIC_REGISTRATION_VERIFICATION is not None | |
| ) | |
| _SITE_BACKEND = None | |
| _AUTH_STORE: LocalAuthStore | None = None | |
| def auth_store() -> LocalAuthStore: | |
| """Return the runtime-bound, site-isolated canonical auth store.""" | |
| global _SITE_BACKEND, _AUTH_STORE | |
| selected = db.db_path().resolve() | |
| if _AUTH_STORE is None or Path(_AUTH_STORE.database_path).resolve() != selected: | |
| _SITE_BACKEND, _AUTH_STORE = open_site_services(database_path=selected) | |
| return _AUTH_STORE | |
| def dispatch_auth_mail(session_token: str, purpose: str) -> None: | |
| """Deliver one committed auth message through the configured local gateway.""" | |
| store = auth_store() | |
| if _SITE_BACKEND is None or store.mail_mode != MAIL_SMTP_PENDING: | |
| return | |
| try: | |
| AuthMailDelivery( | |
| _SITE_BACKEND, | |
| store, | |
| worker_token=auth_mail_worker_token(), | |
| ).deliver_for_session(session_token, purpose=purpose) | |
| except AuthMailDeliveryError: | |
| return | |
| def seed_auth_accounts() -> None: | |
| store = auth_store() | |
| store.ensure_schema() | |
| for account in SEED_AUTH_ACCOUNTS: | |
| store.seed_account(**account) | |
| async def persistent_backend_lifespan(_: FastAPI): | |
| """Migrate + seed the persistent database on startup (idempotent).""" | |
| auth_store() | |
| seed_auth_accounts() | |
| yield | |
| app = FastAPI( | |
| title="IMDb full-stack candidate", | |
| docs_url=None, | |
| redoc_url=None, | |
| openapi_url=None, | |
| lifespan=persistent_backend_lifespan, | |
| ) | |
| async def public_registration_verification_script(): | |
| return registration_script_response(PUBLIC_REGISTRATION_VERIFICATION) | |
| app.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static") | |
| async def runtime_headers(request: Request, call_next): | |
| original_token = request.cookies.get(PRIMARY_SESSION_COOKIE) or request.cookies.get( | |
| SESSION_COOKIE | |
| ) | |
| if ( | |
| request.url.path.startswith("/static/") | |
| or request.url.path.startswith("/media-assets/") | |
| or request.url.path.startswith("/generated-media/") | |
| or request.url.path == "/healthz" | |
| ): | |
| session_token = original_token | |
| session = ( | |
| auth_store().resolve_session(session_token) | |
| if session_token is not None | |
| else None | |
| ) | |
| else: | |
| session_token, session = auth_store().ensure_session(original_token) | |
| request.state.auth_session_token = session_token | |
| request.state.auth_session = session | |
| request.state.auth_cookie_replaced = False | |
| response = await call_next(request) | |
| if ( | |
| session_token is not None | |
| and session_token != original_token | |
| and not request.state.auth_cookie_replaced | |
| ): | |
| set_session_cookie(response, session_token) | |
| response.headers["Content-Security-Policy"] = ( | |
| "default-src 'self'; img-src 'self' data:; style-src 'self'; " | |
| "script-src 'self'; connect-src 'self'; font-src 'self'; media-src 'self'; " | |
| "object-src 'none'; frame-ancestors 'none'; base-uri 'self'" | |
| ) | |
| response.headers["Referrer-Policy"] = "no-referrer" | |
| response.headers["X-Content-Type-Options"] = "nosniff" | |
| response.headers["X-ClawBench-Site"] = SITE_ID | |
| response.headers["X-ClawBench-Version"] = VERSION | |
| response.headers["X-WebsiteBench-Site"] = SITE_ID | |
| response.headers["X-WebsiteBench-Version"] = VERSION | |
| return response | |
| def current_account(request: Request, conn) -> dict | None: | |
| """Resolve the opaque server session to its business subject.""" | |
| session = getattr(request.state, "auth_session", None) | |
| if not session or not session.get("authenticated"): | |
| return None | |
| subject_id = session["account"]["subject_id"] | |
| return db.account_by_key(conn, subject_id) | |
| def set_session_cookie(response, token: str) -> None: | |
| response.set_cookie( | |
| PRIMARY_SESSION_COOKIE, | |
| token, | |
| httponly=True, | |
| samesite="lax", | |
| secure=True, | |
| path="/", | |
| max_age=60 * 60 * 24 * 14, | |
| ) | |
| # Historical benchmark tasks still read the original loopback cookie. | |
| response.set_cookie( | |
| SESSION_COOKIE, | |
| token, | |
| httponly=True, | |
| samesite="lax", | |
| secure=False, | |
| path="/", | |
| max_age=60 * 60 * 24 * 14, | |
| ) | |
| def replace_session_cookie(request: Request, response, token: str) -> None: | |
| request.state.auth_cookie_replaced = True | |
| set_session_cookie(response, token) | |
| def request_session_token(request: Request) -> str: | |
| token = getattr(request.state, "auth_session_token", None) | |
| if not isinstance(token, str): | |
| raise AuthRejected("session is invalid or expired") | |
| return token | |
| def safe_local_path(value: str | None, fallback: str = "/") -> str: | |
| if value and value.startswith("/") and not value.startswith("//"): | |
| return value | |
| return fallback | |
| def signin_url(next_path: str) -> str: | |
| return "/registration/signin/?u=" + quote(next_path, safe="") | |
| def fixture_context( | |
| request: Request, conn, account: dict | None, **values: object | |
| ) -> dict[str, object]: | |
| context: dict[str, object] = { | |
| "request": request, | |
| "site_id": SITE_ID, | |
| "version": VERSION, | |
| "static_version": STATIC_VERSION, | |
| "fixture_id": FIXTURE_ID, | |
| "frozen_clock": FROZEN_CLOCK, | |
| "capture_date": CAPTURE_DATE, | |
| "assets_base": ASSETS_BASE, | |
| "csrf": CSRF_VALUE, | |
| "signed_in": account is not None, | |
| "account_key": account["key"] if account else None, | |
| "account": account, | |
| "local_rating_disclosure": LOCAL_RATING_DISCLOSURE, | |
| "current_path": request.url.path, | |
| "signin_here": signin_url( | |
| request.url.path | |
| + (f"?{request.url.query}" if request.url.query else "") | |
| ), | |
| "menu_groups": MENU_GROUPS, | |
| } | |
| context.update(values) | |
| return context | |
| def render( | |
| request: Request, | |
| conn, | |
| account: dict | None, | |
| template: str, | |
| *, | |
| status_code: int = 200, | |
| **values: object, | |
| ) -> HTMLResponse: | |
| return templates.TemplateResponse( | |
| request=request, | |
| name=template, | |
| context=fixture_context(request, conn, account, **values), | |
| status_code=status_code, | |
| ) | |
| async def urlencoded_form(request: Request) -> dict[str, str]: | |
| content_type = request.headers.get("content-type", "") | |
| if "application/x-www-form-urlencoded" not in content_type: | |
| return {} | |
| raw = (await request.body()).decode("utf-8", errors="replace") | |
| parsed = parse_qs(raw, keep_blank_values=True, strict_parsing=False) | |
| return {key: values[-1] for key, values in parsed.items() if values} | |
| def stale_form_response( | |
| request: Request, conn, account: dict | None, next_path: str | |
| ) -> HTMLResponse: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="Stale local form", | |
| refusal_kind="stale", | |
| refusal_heading="This local form is stale", | |
| refusal_message=( | |
| "The local form token no longer matches this session. " | |
| "Reload the page and try again; nothing was stored." | |
| ), | |
| back_path=next_path, | |
| status_code=409, | |
| ) | |
| def ownership_refusal( | |
| request: Request, conn, account: dict | None, back_path: str | |
| ) -> HTMLResponse: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="Ownership refusal", | |
| refusal_kind="foreign-owner", | |
| refusal_heading="You do not own this item", | |
| refusal_message=( | |
| "This watchlist or list belongs to a different account. " | |
| "Foreign-owner mutations are refused and nothing was changed." | |
| ), | |
| back_path=back_path, | |
| status_code=403, | |
| ) | |
| def unknown_title_refusal( | |
| request: Request, | |
| conn, | |
| account: dict | None, | |
| back_path: str, | |
| status_code: int, | |
| ) -> HTMLResponse: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="Unknown title", | |
| refusal_kind="unknown-title", | |
| refusal_heading="Unknown title", | |
| refusal_message=( | |
| "We couldn't find a title with that identifier." | |
| ), | |
| back_path=back_path, | |
| status_code=status_code, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Health + admin | |
| # --------------------------------------------------------------------------- | |
| async def healthz() -> JSONResponse: | |
| auth_store() | |
| site_backend = _SITE_BACKEND | |
| seed_auth_accounts() | |
| with closing(db.connect()) as conn: | |
| journal = db.journal_mode(conn) | |
| migrations = db.applied_versions(conn) | |
| catalog_counts = { | |
| "titles": conn.execute("SELECT COUNT(*) FROM titles").fetchone()[0], | |
| "movies": conn.execute( | |
| "SELECT COUNT(*) FROM title_details WHERE title_type='movie'" | |
| ).fetchone()[0], | |
| "series": conn.execute( | |
| "SELECT COUNT(*) FROM title_details WHERE title_type='series'" | |
| ).fetchone()[0], | |
| "episodes": conn.execute( | |
| "SELECT COUNT(*) FROM title_details WHERE title_type='episode'" | |
| ).fetchone()[0], | |
| "people": conn.execute("SELECT COUNT(*) FROM people").fetchone()[0], | |
| } | |
| auth = auth_store() | |
| auth_migrations = auth.applied_migrations() | |
| return JSONResponse( | |
| { | |
| "status": "ok", | |
| "ok": True, | |
| "site_id": SITE_ID, | |
| "stage": STAGE, | |
| "version": VERSION, | |
| "fixture_id": FIXTURE_ID, | |
| "frozen_clock": FROZEN_CLOCK, | |
| "persistent_backend": True, | |
| "opaque_server_sessions": True, | |
| "verified_registration": True, | |
| "catalog": catalog_counts, | |
| "runtime": { | |
| "site_id": site_backend.config.site_id if site_backend else SITE_ID, | |
| "database": str(db.db_path()), | |
| "deployment_profile": getattr( | |
| site_backend, "deployment_profile_name", "offline-harbor" | |
| ), | |
| "payment_enabled": False, | |
| }, | |
| "db": { | |
| "journal_mode": journal, | |
| "migrations": migrations, | |
| "auth_migrations": auth_migrations[:3], | |
| "auth_migrations_current": auth_migrations, | |
| }, | |
| }, | |
| headers={ | |
| "X-WebsiteBench-Container-Build-ID": os.environ.get( | |
| "DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", "") | |
| ) | |
| }, | |
| ) | |
| async def admin_reset(request: Request) -> JSONResponse: | |
| supplied = request.headers.get(ADMIN_TOKEN_HEADER, "") or request.headers.get( | |
| LEGACY_ADMIN_TOKEN_HEADER, "" | |
| ) | |
| if not supplied or not hmac.compare_digest(supplied, admin_token()): | |
| return JSONResponse( | |
| {"status": "forbidden", "detail": "invalid admin token"}, | |
| status_code=403, | |
| ) | |
| removed = db.reset_database() | |
| seed_auth_accounts() | |
| return JSONResponse( | |
| { | |
| "status": "ok", | |
| "reset": True, | |
| "removed": removed, | |
| "auth_counts": auth_store().counts(), | |
| "frozen_clock": FROZEN_CLOCK, | |
| "version": VERSION, | |
| } | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Public read routes (all DB-backed) | |
| # --------------------------------------------------------------------------- | |
| async def home(request: Request) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| hero_items = db.home_carousel(conn, "hero") | |
| hero_routes = ( | |
| "/video/vi2243086873/", | |
| "/video/vi3065367065/", | |
| "/video/vi2410859033/", | |
| "/video/vi2521811737/", | |
| ) | |
| hero_items = [ | |
| {**item, "href": hero_routes[index % len(hero_routes)]} | |
| for index, item in enumerate(hero_items) | |
| ] | |
| home_people = db.all_people(conn)[:10] | |
| home_watchlist_ids = ( | |
| set(db.watchlist_title_ids(conn, account["key"])) if account else set() | |
| ) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "home.html", | |
| page_title="IMDb", | |
| hero_items=hero_items, | |
| fanpicks=db.home_carousel(conn, "fanpick"), | |
| fan_favorites=db.home_rail_titles(conn, "fan-favorites"), | |
| top_movies=db.chart_titles(conn, "top")[:10], | |
| popular_movies=db.chart_titles(conn, "popular")[:10], | |
| popular_series=db.all_titles(conn, title_type="series"), | |
| episode_spotlight=db.get_title(conn, "tt2301451"), | |
| home_people=home_people, | |
| home_watchlist_ids=home_watchlist_ids, | |
| home_hero=HOME_HERO, | |
| home_up_next=HOME_UP_NEXT, | |
| home_features=HOME_FEATURES, | |
| home_recommendations=TOP_MOVIES[:12], | |
| home_popular=POPULAR_MOVIES[:12], | |
| home_asset_base=HOME_ASSET_BASE, | |
| streaming_services=STREAMING_SERVICES, | |
| ) | |
| async def find_search( | |
| request: Request, q: str = "", state: str = "results" | |
| ) -> HTMLResponse: | |
| normalized = state if state in { | |
| "results", "exact-matches", "loading", "empty", "error" | |
| } else "results" | |
| query = q.strip() | |
| exact_rows: list[dict] = [] | |
| people_rows: list[dict] = [] | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if normalized in {"results", "exact-matches"}: | |
| exact_rows = db.search_titles(conn, query) | |
| existing_ids = { | |
| row["local_id"] for row in exact_rows if row.get("local_id") | |
| } | |
| exact_rows.extend( | |
| row for row in catalog_search(query) | |
| if row["local_id"] not in existing_ids | |
| ) | |
| people_rows = db.search_people(conn, query) | |
| if not exact_rows: | |
| normalized = "empty" | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "find.html", | |
| page_title=f'Find - "{query}"' if query else "Find", | |
| query=query, | |
| state=normalized, | |
| exact_rows=exact_rows, | |
| people_rows=people_rows, | |
| ) | |
| async def find_suggest(request: Request, q: str = "") -> JSONResponse: | |
| """Small same-origin suggestion feed used by the header combobox.""" | |
| query = q.strip() | |
| with closing(db.connect()) as conn: | |
| titles = db.search_titles(conn, query)[:6] | |
| people = db.search_people(conn, query)[:4] | |
| suggestions = [ | |
| { | |
| "id": row["local_id"], | |
| "label": row["title"], | |
| "kind": "title", | |
| "year": row["year"], | |
| "url": ( | |
| f"/title/{row['local_id']}/" | |
| if row["local_id"] | |
| else f"/find/?q={quote(row['title'])}" | |
| ), | |
| } | |
| for row in titles | |
| ] + [ | |
| { | |
| "id": row["id"], | |
| "label": row["name"], | |
| "kind": "person", | |
| "year": "", | |
| "url": f"/name/{row['id']}/", | |
| } | |
| for row in people | |
| ] | |
| return JSONResponse( | |
| { | |
| "query": query, | |
| "suggestions": suggestions, | |
| "empty": bool(query) and not suggestions, | |
| } | |
| ) | |
| def chart_page( | |
| request: Request, | |
| chart_name: str, | |
| state: str = "loaded", | |
| page: int = 1, | |
| ) -> HTMLResponse: | |
| if chart_name == "top": | |
| movies = TOP_MOVIES | |
| chart_title = "IMDb Top 250 Movies" | |
| chart_deck = "250 fan favorites, ranked by the captured IMDb chart." | |
| rank_label = "Top rated" | |
| page_type = "movie-chart" | |
| elif chart_name == "moviemeter": | |
| movies = POPULAR_MOVIES | |
| chart_title = "Most Popular Movies" | |
| chart_deck = "Movies drawing attention in the current catalog capture." | |
| rank_label = "Popular" | |
| page_type = "movie-chart" | |
| else: | |
| with closing(db.connect()) as conn: | |
| title_type = "series" | |
| titles = db.all_titles(conn, title_type=title_type) | |
| movies = [ | |
| { | |
| **title, | |
| "rank": index, | |
| "rating": title["imdb_rating"], | |
| "poster": title["poster"], | |
| "credit": title.get("stars", ""), | |
| } | |
| for index, title in enumerate(titles, start=1) | |
| ] | |
| if chart_name == "toptv": | |
| chart_title = "IMDb Top 250 TV Shows" | |
| chart_deck = "The highest-rated series represented in the included TV directory." | |
| rank_label = "Top rated" | |
| movies.sort(key=lambda item: (-float(item["rating"]), item["title"])) | |
| elif chart_name == "tvmeter": | |
| chart_title = "Most Popular TV Shows" | |
| chart_deck = "Series ordered by the popularity values in the included directory." | |
| rank_label = "Popular" | |
| movies.sort(key=lambda item: int(item.get("popularity") or 9999)) | |
| else: | |
| with closing(db.connect()) as conn: | |
| titles = db.chart_titles(conn, "popular")[:20] | |
| movies = [ | |
| { | |
| **title, | |
| "rank": index, | |
| "rating": title["imdb_rating"], | |
| "poster": title["poster"], | |
| "credit": title.get("catalog_credit") or title.get("stars", ""), | |
| } | |
| for index, title in enumerate(titles, start=1) | |
| ] | |
| chart_title = "Box Office" | |
| chart_deck = "Explore theatrical titles in the included movie directory. Live grosses and ticket sales are not shown." | |
| rank_label = "Directory" | |
| page_type = "tv-chart" if chart_name != "boxoffice" else "movie-chart" | |
| if state == "empty": | |
| movies = [] | |
| per_page = 50 | |
| page_count = max(1, (len(movies) + per_page - 1) // per_page) | |
| current_page = max(1, min(page, page_count)) | |
| start = (current_page - 1) * per_page | |
| with closing(db.connect()) as conn: | |
| return render( | |
| request, | |
| conn, | |
| current_account(request, conn), | |
| "chart.html", | |
| page_title=chart_title, | |
| chart_title=chart_title, | |
| chart_deck=chart_deck, | |
| chart_name=chart_name, | |
| rank_label=rank_label, | |
| movies=movies[start:start + per_page], | |
| current_page=current_page, | |
| page_count=page_count, | |
| total_movies=len(movies), | |
| page_type=page_type, | |
| ) | |
| async def chart_top( | |
| request: Request, state: str = "loaded", page: int = 1 | |
| ) -> HTMLResponse: | |
| return chart_page(request, "top", state, page) | |
| async def chart_moviemeter( | |
| request: Request, state: str = "loaded", page: int = 1 | |
| ) -> HTMLResponse: | |
| return chart_page(request, "moviemeter", state, page) | |
| async def chart_toptv(request: Request, state: str = "loaded", page: int = 1) -> HTMLResponse: | |
| return chart_page(request, "toptv", state, page) | |
| async def chart_tvmeter(request: Request, state: str = "loaded", page: int = 1) -> HTMLResponse: | |
| return chart_page(request, "tvmeter", state, page) | |
| async def chart_boxoffice(request: Request, state: str = "loaded", page: int = 1) -> HTMLResponse: | |
| return chart_page(request, "boxoffice", state, page) | |
| async def person_detail(request: Request, person_id: str) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| person = db.get_person(conn, person_id) | |
| if person is None: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="Person not found", | |
| refusal_kind="not-found", | |
| refusal_heading="Person not found", | |
| refusal_message="No person in the local directory has that identifier.", | |
| back_path="/", | |
| status_code=404, | |
| ) | |
| person["local_portraits"] = MEDIA_CATALOG["portraits_by_person"].get( | |
| person_id, [] | |
| ) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "person.html", | |
| page_title=person["name"], | |
| person=person, | |
| ) | |
| _RANGE_PATTERN = re.compile(r"^bytes=(\d*)-(\d*)$") | |
| _MAX_RANGE_HEADER_LENGTH = 200 | |
| _MAX_RANGE_NUMBER_LENGTH = 32 | |
| _MEDIA_TYPES = { | |
| ".mp4": "video/mp4", | |
| ".vtt": "text/vtt; charset=utf-8", | |
| ".svg": "image/svg+xml", | |
| } | |
| async def media_asset(request: Request, asset_path: str): | |
| """Serve only manifest-bound r7 assets, including one byte range.""" | |
| if asset_path not in MEDIA_CATALOG["manifest_entries"]: | |
| return Response(status_code=404) | |
| root = MEDIA_CATALOG["asset_root"].resolve() | |
| path = (root / asset_path).resolve() | |
| if not path.is_relative_to(root) or not path.is_file(): | |
| return Response(status_code=404) | |
| size = path.stat().st_size | |
| media_type = _MEDIA_TYPES.get(path.suffix.casefold()) or mimetypes.guess_type(path.name)[0] | |
| range_header = request.headers.get("range") | |
| headers = {"Accept-Ranges": "bytes"} | |
| if not range_header: | |
| return FileResponse(path, media_type=media_type, headers=headers) | |
| normalized_range = range_header.strip() | |
| match = ( | |
| _RANGE_PATTERN.fullmatch(normalized_range) | |
| if len(normalized_range) <= _MAX_RANGE_HEADER_LENGTH | |
| else None | |
| ) | |
| if ( | |
| match is None | |
| or (not match.group(1) and not match.group(2)) | |
| or any( | |
| len(component) > _MAX_RANGE_NUMBER_LENGTH | |
| for component in match.groups() | |
| ) | |
| ): | |
| return Response( | |
| status_code=416, | |
| headers={**headers, "Content-Range": f"bytes */{size}"}, | |
| ) | |
| try: | |
| if match.group(1): | |
| start = int(match.group(1)) | |
| end = int(match.group(2)) if match.group(2) else size - 1 | |
| else: | |
| suffix_length = int(match.group(2)) | |
| start = max(0, size - suffix_length) | |
| end = size - 1 | |
| except (ValueError, OverflowError): | |
| return Response( | |
| status_code=416, | |
| headers={**headers, "Content-Range": f"bytes */{size}"}, | |
| ) | |
| if not match.group(1): | |
| if suffix_length <= 0: | |
| return Response( | |
| status_code=416, | |
| headers={**headers, "Content-Range": f"bytes */{size}"}, | |
| ) | |
| if start >= size or end < start: | |
| return Response( | |
| status_code=416, | |
| headers={**headers, "Content-Range": f"bytes */{size}"}, | |
| ) | |
| end = min(end, size - 1) | |
| with path.open("rb") as handle: | |
| handle.seek(start) | |
| body = handle.read(end - start + 1) | |
| return Response( | |
| body, | |
| status_code=206, | |
| media_type=media_type, | |
| headers={ | |
| **headers, | |
| "Content-Range": f"bytes {start}-{end}/{size}", | |
| "Content-Length": str(len(body)), | |
| }, | |
| ) | |
| # A navigable route must answer a miss with its own document. A body-less | |
| # 4xx makes the browser substitute its built-in error page, whose text embeds | |
| # the ephemeral origin and differs between browser stacks, so the refusal | |
| # would stop being observable site behavior. | |
| GENERATED_MEDIA_NOT_FOUND = ( | |
| "<!doctype html>\n" | |
| '<html lang="en-US">\n' | |
| " <head>\n" | |
| ' <meta charset="utf-8">\n' | |
| ' <meta name="viewport" content="width=device-width, initial-scale=1">\n' | |
| " <title>Media not found - IMDb</title>\n" | |
| " </head>\n" | |
| " <body>\n" | |
| ' <main id="main-content">\n' | |
| " <h1>Media not found</h1>\n" | |
| " <p>No local gallery image is declared for that identifier.</p>\n" | |
| " </main>\n" | |
| " </body>\n" | |
| "</html>\n" | |
| ) | |
| async def generated_media_asset(asset_path: str): | |
| """Render only catalog-declared, title-bound supplemental gallery cards.""" | |
| item = MEDIA_CATALOG["generated_images"].get(asset_path) | |
| if item is None: | |
| return HTMLResponse(GENERATED_MEDIA_NOT_FOUND, status_code=404) | |
| caption = html.escape(item["caption"]) | |
| title_id = html.escape(item["title_id"]) | |
| svg = ( | |
| '<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" ' | |
| 'viewBox="0 0 960 540" role="img">' | |
| f"<title>{caption}</title>" | |
| '<rect width="960" height="540" fill="#111827"/>' | |
| '<rect x="42" y="42" width="876" height="456" rx="24" fill="#1f2937" ' | |
| 'stroke="#f5c518" stroke-width="4"/>' | |
| '<path d="M90 420l190-180 130 120 150-150 310 210z" fill="#374151"/>' | |
| '<circle cx="735" cy="155" r="58" fill="#f5c518"/>' | |
| f'<text x="80" y="105" fill="#fff" font-size="34" ' | |
| f'font-family="Arial,sans-serif">{title_id}</text>' | |
| f'<text x="80" y="475" fill="#fff" font-size="26" ' | |
| f'font-family="Arial,sans-serif">{caption}</text>' | |
| "</svg>" | |
| ) | |
| return Response(content=svg, media_type="image/svg+xml") | |
| async def video_detail(request: Request, video_id: str) -> HTMLResponse: | |
| canonical_id = LEGACY_VIDEO_ALIASES.get(video_id, video_id) | |
| video = VIDEO_BY_ID.get(canonical_id) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if video is None: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="Video not found", | |
| refusal_kind="not-found", | |
| refusal_heading="Video not found", | |
| refusal_message="No local video has that identifier.", | |
| back_path="/trailers/", | |
| status_code=404, | |
| ) | |
| title = db.get_title(conn, video["title_id"]) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "video.html", | |
| page_title=video["caption"], | |
| video=video, | |
| title=title, | |
| ) | |
| async def trailers_page(request: Request) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| videos = [ | |
| {**video, "title": db.get_title(conn, video["title_id"])} | |
| for video in MEDIA_CATALOG["videos"] | |
| ] | |
| return render( | |
| request, | |
| conn, | |
| current_account(request, conn), | |
| "trailers.html", | |
| page_title="Latest Trailers", | |
| videos=videos, | |
| ) | |
| def _recommendation_rows(conn, rows: list[dict]) -> list[dict]: | |
| results: list[dict] = [] | |
| for row in rows: | |
| title = db.get_title(conn, row["id"]) | |
| if title is None: | |
| continue | |
| results.append( | |
| { | |
| **title, | |
| "rank": row["rank"], | |
| "services": services_for_title(title["id"]), | |
| } | |
| ) | |
| return results | |
| async def recommendations_page(request: Request) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| watchlist = ( | |
| db.watchlist_title_ids(conn, account["key"]) if account else [] | |
| ) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "recommendations.html", | |
| page_title="What to Watch", | |
| popular_recommendations=_recommendation_rows(conn, POPULAR_MOVIES), | |
| top_recommendations=_recommendation_rows(conn, TOP_MOVIES), | |
| watchlist_title_ids=watchlist, | |
| streaming_services=STREAMING_SERVICES, | |
| ) | |
| async def preferred_services_page(request: Request) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| return render( | |
| request, | |
| conn, | |
| current_account(request, conn), | |
| "preferred_services.html", | |
| page_title="Preferred Services", | |
| streaming_services=STREAMING_SERVICES, | |
| ) | |
| async def title_media(request: Request, title_id: str) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "media.html", | |
| page_title=f"{title['title']} - Media", | |
| title=title, | |
| media=MEDIA_CATALOG["titles"][title_id], | |
| ) | |
| def editorial_for_title(conn, title: dict) -> dict: | |
| captured = TITLE_EDITORIAL.get(title["id"]) | |
| if captured is not None: | |
| result = dict(captured) | |
| result["directory_media"] = False | |
| else: | |
| result = { | |
| "directory_media": True, | |
| "asset_group": title.get("asset_group", "title-interstellar"), | |
| "video_count": "1", | |
| "photo_count": "1", | |
| "user_review_count": "0", | |
| "critic_review_count": "0", | |
| "award": "Awards information is not included in this local directory.", | |
| "cast": [], | |
| "review_author": "", | |
| "review_title": "Be the first to review", | |
| "review_body": "Sign in to write the first local review for this title.", | |
| "trivia": "Additional production notes are outside the frozen directory.", | |
| "quote": "No memorable quote is included in the local directory.", | |
| "details": [ | |
| ("Title type", title.get("title_type", "movie").title()), | |
| ("Year", title["year"]), | |
| ("Certificate", title["cert"]), | |
| ], | |
| "box_office": [("Availability", "External box-office data is unavailable in this edition.")], | |
| } | |
| credits = db.credits_for_title(conn, title["id"]) | |
| if credits and result["directory_media"]: | |
| result["cast"] = [ | |
| ( | |
| credit["name"], | |
| credit["character_name"] or credit["category"], | |
| credit["thumb"], | |
| ) | |
| for credit in credits | |
| if credit["category"] == "Actor" | |
| ][:4] | |
| fallback = ( | |
| [] | |
| if title["stars"] in {"", "Unavailable"} | |
| else title["stars"].split(", ") | |
| ) | |
| while fallback and len(result["cast"]) < 4: | |
| name = fallback[len(result["cast"]) % len(fallback)] | |
| result["cast"].append((name, "Cast", title["poster"])) | |
| local_reviews = db.reviews_for_title(conn, title["id"]) | |
| result["local_review_count"] = len(local_reviews) | |
| return result | |
| def title_page( | |
| request: Request, | |
| conn, | |
| account: dict | None, | |
| title: dict, | |
| *, | |
| status_code: int = 200, | |
| rating_errors: list[str] | None = None, | |
| rating_dialog_state: str | None = None, | |
| ) -> HTMLResponse: | |
| account_key = account["key"] if account else None | |
| in_watchlist = bool( | |
| account_key | |
| and title["id"] in db.watchlist_title_ids(conn, account_key) | |
| ) | |
| user_rating = ( | |
| db.get_rating(conn, account_key, title["id"]) if account_key else None | |
| ) | |
| user_lists = ( | |
| db.lists_for_account(conn, account_key) if account_key else [] | |
| ) | |
| if rating_dialog_state is None: | |
| rating_dialog_state = "rated" if user_rating else "unrated" | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "title.html", | |
| page_title=f"{title['title']} ({title['year']})", | |
| title=title, | |
| editorial=editorial_for_title(conn, title), | |
| assets_base=ASSETS_BASE, | |
| in_watchlist=in_watchlist, | |
| user_rating=user_rating, | |
| user_lists=user_lists, | |
| rating_errors=rating_errors or [], | |
| rating_dialog_state=rating_dialog_state, | |
| watchlist_flash=request.query_params.get("watchlist"), | |
| rating_flash=request.query_params.get("rating"), | |
| status_code=status_code, | |
| ) | |
| async def title_detail(request: Request, title_id: str) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| catalog_movie = CATALOG_BY_ID.get(title_id) | |
| if catalog_movie is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "catalog_title.html", | |
| page_title=f"{catalog_movie['title']} ({catalog_movie.get('year', '')})", | |
| movie=catalog_movie, | |
| vote_display=compact_count(catalog_movie.get("votes")), | |
| ) | |
| return title_page(request, conn, account, title) | |
| def reviews_page( | |
| request: Request, | |
| conn, | |
| account: dict | None, | |
| title: dict, | |
| *, | |
| status_code: int = 200, | |
| form_summary: str = "", | |
| form_body: str = "", | |
| form_spoiler: bool = False, | |
| form_errors: list[str] | None = None, | |
| ) -> HTMLResponse: | |
| reviews = db.reviews_for_title(conn, title["id"]) | |
| own_review = ( | |
| db.review_for_account(conn, account["key"], title["id"]) | |
| if account else None | |
| ) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "reviews.html", | |
| page_title=f"{title['title']} - User reviews", | |
| title=title, | |
| reviews=reviews, | |
| own_review=own_review, | |
| form_summary=form_summary, | |
| form_body=form_body, | |
| form_spoiler=form_spoiler, | |
| form_errors=form_errors or [], | |
| review_flash=request.query_params.get("review"), | |
| status_code=status_code, | |
| ) | |
| async def title_reviews(request: Request, title_id: str) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| return reviews_page(request, conn, account, title) | |
| def validate_review(values: dict[str, str]) -> tuple[str, str, bool, list[str]]: | |
| summary = values.get("summary", "").strip() | |
| body = values.get("body", "").strip() | |
| spoiler = values.get("spoiler") == "1" | |
| errors: list[str] = [] | |
| if not 3 <= len(summary) <= 100: | |
| errors.append("Add a summary between 3 and 100 characters.") | |
| if not 10 <= len(body) <= 10_000: | |
| errors.append("Write a review between 10 and 10000 characters.") | |
| return summary, body, spoiler, errors | |
| async def create_title_review(request: Request, title_id: str): | |
| next_path = f"/title/{title_id}/reviews/" | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| summary, body, spoiler, errors = validate_review(values) | |
| if errors: | |
| return reviews_page( | |
| request, | |
| conn, | |
| account, | |
| title, | |
| status_code=422, | |
| form_summary=summary, | |
| form_body=body, | |
| form_spoiler=spoiler, | |
| form_errors=errors, | |
| ) | |
| conn.execute("BEGIN IMMEDIATE") | |
| if db.review_for_account(conn, account["key"], title_id) is not None: | |
| conn.execute("ROLLBACK") | |
| return reviews_page( | |
| request, | |
| conn, | |
| account, | |
| title, | |
| status_code=422, | |
| form_summary=summary, | |
| form_body=body, | |
| form_spoiler=spoiler, | |
| form_errors=[ | |
| "You already reviewed this title. Edit your existing review." | |
| ], | |
| ) | |
| try: | |
| db.create_review( | |
| conn, | |
| account["key"], | |
| title_id, | |
| summary=summary, | |
| body=body, | |
| spoiler=spoiler, | |
| ) | |
| conn.execute("COMMIT") | |
| except sqlite3.IntegrityError: | |
| conn.execute("ROLLBACK") | |
| return reviews_page( | |
| request, | |
| conn, | |
| account, | |
| title, | |
| status_code=422, | |
| form_summary=summary, | |
| form_body=body, | |
| form_spoiler=spoiler, | |
| form_errors=[ | |
| "You already reviewed this title. Edit your existing review." | |
| ], | |
| ) | |
| return RedirectResponse(f"{next_path}?review=created", status_code=303) | |
| def review_edit_page( | |
| request: Request, | |
| conn, | |
| account: dict, | |
| title: dict, | |
| review: dict, | |
| *, | |
| status_code: int = 200, | |
| errors: list[str] | None = None, | |
| ) -> HTMLResponse: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "review_edit.html", | |
| page_title=f"Edit review - {title['title']}", | |
| title=title, | |
| review=review, | |
| form_errors=errors or [], | |
| status_code=status_code, | |
| ) | |
| async def edit_review_form(request: Request, title_id: str, review_id: int): | |
| next_path = f"/title/{title_id}/reviews/{review_id}/edit/" | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=307) | |
| review = db.get_review(conn, review_id) | |
| if review is None or review["title_id"] != title_id: | |
| return unknown_title_refusal(request, conn, account, f"/title/{title_id}/reviews/", 404) | |
| if review["account_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, f"/title/{title_id}/reviews/") | |
| return review_edit_page(request, conn, account, title, review) | |
| async def edit_review_submit(request: Request, title_id: str, review_id: int): | |
| next_path = f"/title/{title_id}/reviews/" | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| review = db.get_review(conn, review_id) | |
| if review is None or review["title_id"] != title_id: | |
| return unknown_title_refusal(request, conn, account, next_path, 404) | |
| if review["account_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, next_path) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| summary, body, spoiler, errors = validate_review(values) | |
| review.update({"summary": summary, "body": body, "spoiler": int(spoiler)}) | |
| if errors: | |
| return review_edit_page( | |
| request, conn, account, title, review, status_code=422, errors=errors | |
| ) | |
| db.update_review( | |
| conn, | |
| review_id, | |
| summary=summary, | |
| body=body, | |
| spoiler=spoiler, | |
| ) | |
| return RedirectResponse(f"{next_path}?review=updated", status_code=303) | |
| async def delete_review_submit(request: Request, title_id: str, review_id: int): | |
| next_path = f"/title/{title_id}/reviews/" | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| review = db.get_review(conn, review_id) | |
| if review is None or review["title_id"] != title_id: | |
| return unknown_title_refusal(request, conn, account, next_path, 404) | |
| if review["account_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, next_path) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| db.delete_review(conn, review_id) | |
| return RedirectResponse(f"{next_path}?review=deleted", status_code=303) | |
| # --------------------------------------------------------------------------- | |
| # Fixture identity handoff (synthetic accounts; signed persistent session) | |
| # --------------------------------------------------------------------------- | |
| async def signin_boundary(request: Request, u: str = "/") -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "signin.html", | |
| page_title="Sign in", | |
| next_path=safe_local_path(u), | |
| form_email="", | |
| ) | |
| async def sign_in_submit(request: Request): | |
| values = await urlencoded_form(request) | |
| next_path = safe_local_path(values.get("next")) | |
| if values.get("csrf") != CSRF_VALUE: | |
| with closing(db.connect()) as conn: | |
| return render( | |
| request, | |
| conn, | |
| None, | |
| "signin.html", | |
| page_title="Sign in", | |
| next_path=next_path, | |
| form_email=values.get("email", ""), | |
| auth_error="This sign-in request has expired. Please try again.", | |
| status_code=403, | |
| ) | |
| try: | |
| result = auth_store().sign_in( | |
| request_session_token(request), | |
| email=values.get("email", ""), | |
| password=values.get("password", ""), | |
| ) | |
| except (AuthError, ValueError): | |
| with closing(db.connect()) as conn: | |
| return render( | |
| request, | |
| conn, | |
| None, | |
| "signin.html", | |
| page_title="Sign in", | |
| next_path=next_path, | |
| form_email="", | |
| auth_error="Your email or password is incorrect.", | |
| status_code=401, | |
| ) | |
| response = RedirectResponse(next_path, status_code=303) | |
| replace_session_cookie(request, response, result["session_token"]) | |
| return response | |
| async def sign_out(request: Request) -> RedirectResponse: | |
| auth_store().sign_out(request_session_token(request)) | |
| request.state.auth_cookie_replaced = True | |
| response = RedirectResponse("/", status_code=303) | |
| response.delete_cookie(SESSION_COOKIE, path="/") | |
| response.delete_cookie(PRIMARY_SESSION_COOKIE, path="/", secure=True) | |
| return response | |
| async def fixture_session(request: Request): | |
| """Admin-only deterministic login helper; never linked from public UI.""" | |
| with closing(db.connect()) as conn: | |
| supplied = request.headers.get(ADMIN_TOKEN_HEADER, "") or request.headers.get( | |
| LEGACY_ADMIN_TOKEN_HEADER, "" | |
| ) | |
| values = await urlencoded_form(request) | |
| next_path = safe_local_path(values.get("next")) | |
| if ( | |
| not supplied | |
| or not hmac.compare_digest(supplied, admin_token()) | |
| or values.get("csrf") != CSRF_VALUE | |
| ): | |
| return render( | |
| request, | |
| conn, | |
| None, | |
| "signin.html", | |
| page_title="Sign in", | |
| next_path=next_path, | |
| form_email="", | |
| auth_error="This request is not available.", | |
| status_code=403, | |
| ) | |
| account_key = values.get("account", "alex") | |
| if db.account_by_key(conn, account_key) is None: | |
| account_key = "alex" | |
| seeded = next( | |
| item for item in SEED_AUTH_ACCOUNTS if item["subject_id"] == account_key | |
| ) | |
| result = auth_store().sign_in( | |
| request_session_token(request), | |
| email=seeded["email"], | |
| password=seeded["password"], | |
| ) | |
| response = RedirectResponse(next_path, status_code=303) | |
| replace_session_cookie(request, response, result["session_token"]) | |
| return response | |
| async def fixture_sign_out(request: Request) -> RedirectResponse: | |
| return await sign_out(request) | |
| async def opencli_fixture_session(request: Request): | |
| """Create the one public local session declared by the OpenCLI contract. | |
| The route is absent from product navigation, accepts no credentials or | |
| arbitrary account identity, and exists only on the owned loopback clone. | |
| """ | |
| values = await urlencoded_form(request) | |
| if values.get("csrf") != "imdb-opencli-public-fixture": | |
| return JSONResponse( | |
| {"status": "forbidden", "detail": "invalid local fixture"}, | |
| status_code=403, | |
| ) | |
| seeded = next( | |
| item for item in SEED_AUTH_ACCOUNTS if item["subject_id"] == "alex" | |
| ) | |
| result = auth_store().sign_in( | |
| request_session_token(request), | |
| email=seeded["email"], | |
| password=seeded["password"], | |
| ) | |
| response = RedirectResponse("/", status_code=303) | |
| replace_session_cookie(request, response, result["session_token"]) | |
| return response | |
| def auth_form_page( | |
| request: Request, | |
| *, | |
| mode: str, | |
| page_title: str, | |
| status_code: int = 200, | |
| **values: object, | |
| ) -> HTMLResponse: | |
| with closing(db.connect()) as conn: | |
| return render( | |
| request, | |
| conn, | |
| current_account(request, conn), | |
| "auth.html", | |
| mode=mode, | |
| page_title=page_title, | |
| status_code=status_code, | |
| **values, | |
| ) | |
| async def public_registration_send_code(request: Request) -> JSONResponse: | |
| return await send_registration_code( | |
| request, | |
| verification=PUBLIC_REGISTRATION_VERIFICATION, | |
| store=auth_store(), | |
| session_token=request_session_token(request), | |
| ) | |
| async def public_registration_verify_code(request: Request) -> JSONResponse: | |
| return await verify_registration_code( | |
| request, | |
| verification=PUBLIC_REGISTRATION_VERIFICATION, | |
| store=auth_store(), | |
| session_token=request_session_token(request), | |
| ) | |
| async def registration_entry(request: Request) -> HTMLResponse: | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email="", | |
| form_name="", | |
| ) | |
| async def registration_start(request: Request, background_tasks: BackgroundTasks): | |
| values = await urlencoded_form(request) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email=values.get("email", ""), | |
| form_name=values.get("display_name", ""), | |
| auth_error="This form has expired. Please try again.", | |
| status_code=409, | |
| ) | |
| if PUBLIC_REGISTRATION_VERIFICATION is not None: | |
| token = request_session_token(request) | |
| store = auth_store() | |
| try: | |
| store.validate_registration_details( | |
| email=values.get("email", ""), | |
| display_name=values.get("display_name", ""), | |
| password=values.get("password", ""), | |
| ) | |
| ticket = consume_registration_ticket( | |
| verification=PUBLIC_REGISTRATION_VERIFICATION, | |
| store=store, | |
| session_token=token, | |
| email=values.get("email", ""), | |
| ) | |
| if not ticket: | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email=values.get("email", ""), | |
| form_name=values.get("display_name", ""), | |
| auth_error=( | |
| "Verify this email address before creating the account." | |
| ), | |
| status_code=422, | |
| ) | |
| result = store.complete_externally_verified_registration( | |
| token, | |
| email=values.get("email", ""), | |
| display_name=values.get("display_name", ""), | |
| password=values.get("password", ""), | |
| subject_factory=db.create_registered_account, | |
| ) | |
| except VerificationUnavailable: | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email=values.get("email", ""), | |
| form_name=values.get("display_name", ""), | |
| auth_error="Email verification is temporarily unavailable.", | |
| status_code=503, | |
| ) | |
| except AuthError: | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email=values.get("email", ""), | |
| form_name=values.get("display_name", ""), | |
| auth_error="Check your name, email, and password and try again.", | |
| status_code=422, | |
| ) | |
| response = RedirectResponse("/", status_code=303) | |
| replace_session_cookie(request, response, result["session_token"]) | |
| return response | |
| token = request_session_token(request) | |
| try: | |
| auth_store().start_registration( | |
| token, | |
| email=values.get("email", ""), | |
| display_name=values.get("display_name", ""), | |
| password=values.get("password", ""), | |
| ) | |
| except AuthRateLimited as exc: | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email=values.get("email", ""), | |
| form_name=values.get("display_name", ""), | |
| auth_error=f"Please wait {exc.retry_after} seconds before trying again.", | |
| status_code=429, | |
| ) | |
| except AuthConflict: | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email=values.get("email", ""), | |
| form_name=values.get("display_name", ""), | |
| auth_error="An account already uses that email. Sign in or recover it.", | |
| status_code=409, | |
| ) | |
| except (AuthValidationError, AuthRejected): | |
| return auth_form_page( | |
| request, | |
| mode="register", | |
| page_title="Create account", | |
| form_email=values.get("email", ""), | |
| form_name=values.get("display_name", ""), | |
| auth_error="Check your name, email, and password and try again.", | |
| status_code=422, | |
| ) | |
| if auth_store().mail_mode == MAIL_SMTP_PENDING: | |
| background_tasks.add_task(dispatch_auth_mail, token, "registration") | |
| return RedirectResponse("/registration/verify/", status_code=303) | |
| async def registration_verify_entry(request: Request) -> HTMLResponse: | |
| mail = auth_store().local_mail_for_session( | |
| request_session_token(request), purpose="registration" | |
| ) | |
| return auth_form_page( | |
| request, | |
| mode="register-verify", | |
| page_title="Verify your email", | |
| mail=mail, | |
| ) | |
| async def registration_verify_submit(request: Request): | |
| values = await urlencoded_form(request) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return auth_form_page( | |
| request, | |
| mode="register-verify", | |
| page_title="Verify your email", | |
| auth_error="This form has expired. Please try again.", | |
| mail=None, | |
| status_code=409, | |
| ) | |
| token = request_session_token(request) | |
| try: | |
| store = auth_store() | |
| store.verify_registration_code(token, values.get("code", "")) | |
| result = store.complete_registration( | |
| token, subject_factory=db.create_registered_account | |
| ) | |
| except AuthError: | |
| mail = auth_store().local_mail_for_session(token, purpose="registration") | |
| return auth_form_page( | |
| request, | |
| mode="register-verify", | |
| page_title="Verify your email", | |
| auth_error="That verification code is invalid or expired.", | |
| mail=mail, | |
| status_code=422, | |
| ) | |
| response = RedirectResponse("/", status_code=303) | |
| replace_session_cookie(request, response, result["session_token"]) | |
| return response | |
| async def password_reset_entry(request: Request) -> HTMLResponse: | |
| return auth_form_page( | |
| request, | |
| mode="password-request", | |
| page_title="Reset password", | |
| form_email="", | |
| ) | |
| async def password_reset_start(request: Request, background_tasks: BackgroundTasks): | |
| values = await urlencoded_form(request) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return auth_form_page( | |
| request, | |
| mode="password-request", | |
| page_title="Reset password", | |
| form_email=values.get("email", ""), | |
| auth_error="This form has expired. Please try again.", | |
| status_code=409, | |
| ) | |
| token = request_session_token(request) | |
| try: | |
| result = auth_store().start_password_reset( | |
| token, email=values.get("email", "") | |
| ) | |
| except AuthRateLimited as exc: | |
| return auth_form_page( | |
| request, | |
| mode="password-request", | |
| page_title="Reset password", | |
| form_email=values.get("email", ""), | |
| auth_error=f"Please wait {exc.retry_after} seconds before trying again.", | |
| status_code=429, | |
| ) | |
| except AuthValidationError: | |
| return auth_form_page( | |
| request, | |
| mode="password-request", | |
| page_title="Reset password", | |
| form_email=values.get("email", ""), | |
| auth_error="Enter a valid email address.", | |
| status_code=422, | |
| ) | |
| if auth_store().mail_mode == MAIL_SMTP_PENDING: | |
| background_tasks.add_task(dispatch_auth_mail, token, "password-reset") | |
| return RedirectResponse( | |
| "/registration/password-verify/?requested=1", status_code=303 | |
| ) | |
| async def password_verify_entry(request: Request) -> HTMLResponse: | |
| mail = auth_store().local_mail_for_session( | |
| request_session_token(request), purpose="password-reset" | |
| ) | |
| return auth_form_page( | |
| request, | |
| mode="password-verify", | |
| page_title="Check your email", | |
| mail=mail, | |
| generic_message=( | |
| "If an account matches that email, a verification message is ready." | |
| ), | |
| ) | |
| async def password_verify_submit(request: Request): | |
| values = await urlencoded_form(request) | |
| token = request_session_token(request) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return auth_form_page( | |
| request, | |
| mode="password-verify", | |
| page_title="Check your email", | |
| mail=None, | |
| auth_error="This form has expired. Please try again.", | |
| status_code=409, | |
| ) | |
| try: | |
| auth_store().verify_password_reset_code(token, values.get("code", "")) | |
| except AuthError: | |
| return auth_form_page( | |
| request, | |
| mode="password-verify", | |
| page_title="Check your email", | |
| mail=auth_store().local_mail_for_session( | |
| token, purpose="password-reset" | |
| ), | |
| auth_error="That verification code is invalid or expired.", | |
| status_code=422, | |
| ) | |
| return RedirectResponse("/registration/password-new/", status_code=303) | |
| async def password_new_entry(request: Request) -> HTMLResponse: | |
| return auth_form_page( | |
| request, | |
| mode="password-new", | |
| page_title="Choose a new password", | |
| ) | |
| async def password_new_submit(request: Request): | |
| values = await urlencoded_form(request) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return auth_form_page( | |
| request, | |
| mode="password-new", | |
| page_title="Choose a new password", | |
| auth_error="This form has expired. Please try again.", | |
| status_code=409, | |
| ) | |
| try: | |
| token = auth_store().complete_password_reset( | |
| request_session_token(request), | |
| new_password=values.get("password", ""), | |
| ) | |
| except AuthError: | |
| return auth_form_page( | |
| request, | |
| mode="password-new", | |
| page_title="Choose a new password", | |
| auth_error="The reset is invalid or expired. Start again.", | |
| status_code=422, | |
| ) | |
| response = RedirectResponse("/", status_code=303) | |
| replace_session_cookie(request, response, token) | |
| return response | |
| async def local_inbox(request: Request) -> HTMLResponse: | |
| token = request_session_token(request) | |
| messages = [ | |
| item | |
| for item in ( | |
| auth_store().local_mail_for_session(token, purpose="registration"), | |
| auth_store().local_mail_for_session(token, purpose="password-reset"), | |
| ) | |
| if item is not None | |
| ] | |
| return auth_form_page( | |
| request, | |
| mode="inbox", | |
| page_title="Verification inbox", | |
| messages=messages, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Watchlist (account-scoped; anonymous access mirrors the captured | |
| # temporary redirect chain ending at the sign-in boundary) | |
| # --------------------------------------------------------------------------- | |
| async def watchlist_page(request: Request): | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| # Keep the source-shaped redirect temporary so a browser cannot | |
| # cache an anonymous authorization decision across sign-in. | |
| return RedirectResponse( | |
| signin_url("/list/watchlist/"), status_code=307 | |
| ) | |
| entries = db.watchlist_titles(conn, account["key"]) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "watchlist.html", | |
| page_title="Your Watchlist", | |
| entries=entries, | |
| watchlist_flash=request.query_params.get("watchlist"), | |
| ) | |
| async def watchlist_add(request: Request): | |
| values = await urlencoded_form(request) | |
| title_id = values.get("title_id", "") | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| known_title = db.get_title(conn, title_id) is not None | |
| next_path = safe_local_path( | |
| values.get("next"), | |
| f"/title/{title_id}/" if known_title else "/list/watchlist/", | |
| ) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| owner = values.get("owner") | |
| if owner and owner != account["id"]: | |
| return ownership_refusal(request, conn, account, next_path) | |
| if not known_title: | |
| return unknown_title_refusal(request, conn, account, "/", 422) | |
| flash = db.watchlist_add(conn, account["key"], title_id) | |
| separator = "&" if "?" in next_path else "?" | |
| return RedirectResponse( | |
| f"{next_path}{separator}watchlist={flash}", status_code=303 | |
| ) | |
| async def watchlist_remove(request: Request): | |
| values = await urlencoded_form(request) | |
| next_path = safe_local_path(values.get("next"), "/list/watchlist/") | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| owner = values.get("owner") | |
| if owner and owner != account["id"]: | |
| return ownership_refusal(request, conn, account, next_path) | |
| db.watchlist_remove(conn, account["key"], values.get("title_id", "")) | |
| return RedirectResponse( | |
| f"{next_path}?watchlist=removed", status_code=303 | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Ratings (any signed-in account rates any title 1-10; deletable) | |
| # --------------------------------------------------------------------------- | |
| async def rate_title(request: Request, title_id: str): | |
| next_path = f"/title/{title_id}/" | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| raw = values.get("rating", "").strip() | |
| try: | |
| rating = int(raw) | |
| except ValueError: | |
| rating = -1 | |
| if rating < 1 or rating > 10: | |
| return title_page( | |
| request, | |
| conn, | |
| account, | |
| title, | |
| status_code=422, | |
| rating_errors=[ | |
| "Choose a whole-number rating between 1 and 10." | |
| ], | |
| rating_dialog_state="validation", | |
| ) | |
| db.set_rating(conn, account["key"], title_id, rating) | |
| return RedirectResponse(f"{next_path}?rating=saved", status_code=303) | |
| async def remove_rating(request: Request, title_id: str): | |
| next_path = f"/title/{title_id}/" | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| title = db.get_title(conn, title_id) | |
| if title is None: | |
| return unknown_title_refusal(request, conn, account, "/", 404) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| db.delete_rating(conn, account["key"], title_id) | |
| return RedirectResponse(f"{next_path}?rating=removed", status_code=303) | |
| # --------------------------------------------------------------------------- | |
| # Custom lists (owner-scoped membership; idempotent adds) | |
| # --------------------------------------------------------------------------- | |
| async def list_create_form(request: Request) -> HTMLResponse: | |
| # The source rendered this form anonymously; submission needs a session. | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "list_create.html", | |
| page_title="Create a new list", | |
| form_name="", | |
| form_description="", | |
| form_list_type="Titles", | |
| form_privacy="Public", | |
| form_errors=[], | |
| deleted=request.query_params.get("deleted"), | |
| ) | |
| async def list_create_submit(request: Request): | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse( | |
| signin_url("/list/create/"), status_code=303 | |
| ) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, "/list/create/") | |
| name = values.get("name", "").strip() | |
| list_type = values.get("list_type", "Titles") | |
| if list_type not in {"Titles", "People", "Images", "Videos"}: | |
| list_type = "Titles" | |
| privacy = values.get("privacy", "Public") | |
| if privacy not in {"Public", "Private"}: | |
| privacy = "Public" | |
| if not name: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "list_create.html", | |
| page_title="Create a new list", | |
| form_name=name, | |
| form_description=values.get("description", ""), | |
| form_list_type=list_type, | |
| form_privacy=privacy, | |
| form_errors=["Enter a name for your list."], | |
| status_code=422, | |
| ) | |
| description = values.get("description", "").strip() | |
| if len(description) > 10_000: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "list_create.html", | |
| page_title="Create a new list", | |
| form_name=name, | |
| form_description=description[:10_000], | |
| form_list_type=list_type, | |
| form_privacy=privacy, | |
| form_errors=["Keep the description under 10000 characters."], | |
| status_code=422, | |
| ) | |
| conn.execute("BEGIN IMMEDIATE") | |
| existing = db.find_list_by_name(conn, account["key"], name) | |
| if existing is not None: | |
| conn.execute("ROLLBACK") | |
| return RedirectResponse( | |
| f"/list/{existing['id']}/?created=exists", status_code=303 | |
| ) | |
| created = db.create_list( | |
| conn, account["key"], name, list_type, privacy, description | |
| ) | |
| conn.execute("COMMIT") | |
| return RedirectResponse(f"/list/{created['id']}/?created=1", status_code=303) | |
| async def list_detail(request: Request, list_id: str): | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| list_data = db.get_list(conn, list_id) | |
| if list_data is None: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="List not found", | |
| refusal_kind="not-found", | |
| refusal_heading="List not found", | |
| refusal_message="No local list exists with that identifier.", | |
| back_path="/list/create/", | |
| status_code=404, | |
| ) | |
| owner = db.account_by_key(conn, list_data["owner_key"]) | |
| if list_data["privacy"] == "Private" and ( | |
| account is None or account["key"] != list_data["owner_key"] | |
| ): | |
| if account is None: | |
| return RedirectResponse( | |
| signin_url(f"/list/{list_id}/"), status_code=307 | |
| ) | |
| return ownership_refusal(request, conn, account, "/list/create/") | |
| members = db.list_member_titles(conn, list_id) | |
| is_owner = account is not None and account["key"] == list_data["owner_key"] | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "list_detail.html", | |
| page_title=list_data["name"], | |
| list_data=list_data, | |
| owner=owner, | |
| members=members, | |
| is_owner=is_owner, | |
| list_flash=request.query_params.get("added") | |
| or request.query_params.get("created") | |
| or ("updated" if request.query_params.get("updated") else None) | |
| or ("removed" if request.query_params.get("removed") else None), | |
| ) | |
| async def list_edit_form(request: Request, list_id: str): | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse(signin_url(f"/list/{list_id}/edit/"), status_code=307) | |
| list_data = db.get_list(conn, list_id) | |
| if list_data is None: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="List not found", | |
| refusal_kind="not-found", | |
| refusal_heading="List not found", | |
| refusal_message="No local list exists with that identifier.", | |
| back_path="/list/create/", | |
| status_code=404, | |
| ) | |
| if list_data["owner_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, f"/list/{list_id}/") | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "list_edit.html", | |
| page_title=f"Edit {list_data['name']}", | |
| list_data=list_data, | |
| form_errors=[], | |
| ) | |
| async def list_edit_submit(request: Request, list_id: str): | |
| values = await urlencoded_form(request) | |
| next_path = f"/list/{list_id}/" | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| list_data = db.get_list(conn, list_id) | |
| if list_data is None: | |
| return render( | |
| request, conn, account, "refusal.html", page_title="List not found", | |
| refusal_kind="not-found", refusal_heading="List not found", | |
| refusal_message="No local list exists with that identifier.", | |
| back_path="/list/create/", status_code=404, | |
| ) | |
| if list_data["owner_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, next_path) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| name = values.get("name", "").strip() | |
| description = values.get("description", "").strip() | |
| privacy = values.get("privacy", "Public") | |
| errors: list[str] = [] | |
| if not name: | |
| errors.append("Enter a name for your list.") | |
| if len(name) > 255: | |
| errors.append("Keep the list name under 255 characters.") | |
| if len(description) > 10_000: | |
| errors.append("Keep the description under 10000 characters.") | |
| if privacy not in {"Public", "Private"}: | |
| errors.append("Choose Public or Private visibility.") | |
| conn.execute("BEGIN IMMEDIATE") | |
| duplicate = db.find_list_by_name(conn, account["key"], name) | |
| if duplicate is not None and duplicate["id"] != list_id: | |
| errors.append("You already have a list with that name.") | |
| list_data.update( | |
| {"name": name, "description": description, "privacy": privacy} | |
| ) | |
| if errors: | |
| conn.execute("ROLLBACK") | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "list_edit.html", | |
| page_title=f"Edit {list_data['name'] or 'list'}", | |
| list_data=list_data, | |
| form_errors=errors, | |
| status_code=422, | |
| ) | |
| try: | |
| db.update_list( | |
| conn, | |
| list_id, | |
| name=name, | |
| description=description, | |
| privacy=privacy, | |
| ) | |
| conn.execute("COMMIT") | |
| except sqlite3.IntegrityError: | |
| conn.execute("ROLLBACK") | |
| list_data.update( | |
| {"name": name, "description": description, "privacy": privacy} | |
| ) | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "list_edit.html", | |
| page_title=f"Edit {list_data['name'] or 'list'}", | |
| list_data=list_data, | |
| form_errors=["You already have a list with that name."], | |
| status_code=422, | |
| ) | |
| return RedirectResponse(f"{next_path}?updated=1", status_code=303) | |
| async def list_delete_submit(request: Request, list_id: str): | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse(signin_url(f"/list/{list_id}/"), status_code=303) | |
| list_data = db.get_list(conn, list_id) | |
| if list_data is None: | |
| return RedirectResponse("/list/create/?deleted=missing", status_code=303) | |
| if list_data["owner_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, f"/list/{list_id}/") | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, f"/list/{list_id}/") | |
| db.delete_list(conn, list_id) | |
| return RedirectResponse("/list/create/?deleted=1", status_code=303) | |
| async def list_remove_member(request: Request, list_id: str): | |
| values = await urlencoded_form(request) | |
| next_path = f"/list/{list_id}/" | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse(signin_url(next_path), status_code=303) | |
| list_data = db.get_list(conn, list_id) | |
| if list_data is None: | |
| return RedirectResponse("/list/create/", status_code=303) | |
| if list_data["owner_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, next_path) | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response(request, conn, account, next_path) | |
| db.list_remove_member(conn, list_id, values.get("title_id", "")) | |
| return RedirectResponse(f"{next_path}?removed=1", status_code=303) | |
| async def list_add_member(request: Request, list_id: str): | |
| values = await urlencoded_form(request) | |
| with closing(db.connect()) as conn: | |
| account = current_account(request, conn) | |
| if account is None: | |
| return RedirectResponse( | |
| signin_url(f"/list/{list_id}/"), status_code=303 | |
| ) | |
| list_data = db.get_list(conn, list_id) | |
| if list_data is None: | |
| return render( | |
| request, | |
| conn, | |
| account, | |
| "refusal.html", | |
| page_title="List not found", | |
| refusal_kind="not-found", | |
| refusal_heading="List not found", | |
| refusal_message="No local list exists with that identifier.", | |
| back_path="/list/create/", | |
| status_code=404, | |
| ) | |
| if list_data["owner_key"] != account["key"]: | |
| return ownership_refusal(request, conn, account, "/list/create/") | |
| if values.get("csrf") != CSRF_VALUE: | |
| return stale_form_response( | |
| request, conn, account, f"/list/{list_id}/" | |
| ) | |
| title_id = values.get("title_id", "") | |
| if db.get_title(conn, title_id) is None: | |
| return unknown_title_refusal( | |
| request, conn, account, f"/list/{list_id}/", 422 | |
| ) | |
| flash = "1" if db.list_add_member(conn, list_id, title_id) == "added" \ | |
| else "exists" | |
| return RedirectResponse( | |
| f"/list/{list_id}/?added={flash}", status_code=303 | |
| ) | |
| async def browse_page(request: Request) -> HTMLResponse: | |
| """Render typed, route-specific discovery or external-boundary pages.""" | |
| normalized = f"/{request.url.path.strip('/')}/" | |
| boundary = BOUNDARY_PAGES.get(normalized) | |
| if boundary: | |
| boundary_kind, page_title, message = boundary | |
| with closing(db.connect()) as conn: | |
| return render( | |
| request, conn, current_account(request, conn), "boundary.html", | |
| page_title=page_title, boundary_kind=boundary_kind, | |
| boundary_title=page_title, boundary_message=message, | |
| ) | |
| page = BROWSE_PAGES.get(normalized) | |
| page_type = DISCOVERY_PAGE_TYPES.get(normalized) | |
| if page is None or page_type is None: | |
| with closing(db.connect()) as conn: | |
| return render( | |
| request, conn, current_account(request, conn), "refusal.html", | |
| page_title="Page not found", refusal_kind="not-found", | |
| refusal_heading="Page not found", | |
| refusal_message="We couldn't find that IMDb page.", | |
| back_path="/", status_code=404, | |
| ) | |
| page_title, page_deck = page | |
| with closing(db.connect()) as conn: | |
| all_titles = db.all_titles(conn) | |
| titles_by_id = {title["id"]: title for title in all_titles} | |
| people = db.all_people(conn) | |
| genre_sections = [] | |
| for genre in sorted({genre for title in all_titles for genre in title["genres"]}): | |
| genre_sections.append({ | |
| "name": genre, | |
| "titles": [title for title in all_titles if genre in title["genres"]][:6], | |
| }) | |
| media = MEDIA_CATALOG["gallery"][:18] | |
| videos = [ | |
| {**video, "title": db.get_title(conn, video["title_id"])} | |
| for video in MEDIA_CATALOG["videos"][:8] | |
| ] | |
| collection_titles = [ | |
| titles_by_id[title_id] | |
| for title_id in DISCOVERY_COLLECTION_IDS.get(normalized, ()) | |
| if title_id in titles_by_id | |
| ] | |
| calendar_groups: list[dict[str, object]] = [] | |
| for year in sorted( | |
| {str(item.get("year") or "Year unavailable") for item in POPULAR_MOVIES[:30]}, | |
| reverse=True, | |
| ): | |
| year_ids = [ | |
| item["id"] for item in POPULAR_MOVIES[:30] | |
| if str(item.get("year") or "Year unavailable") == year | |
| ] | |
| calendar_groups.append({ | |
| "year": year, | |
| "titles": [titles_by_id[title_id] for title_id in year_ids if title_id in titles_by_id], | |
| }) | |
| news_items = [] | |
| for heading, summary, href, title_id in DISCOVERY_NEWS.get(normalized, ()): | |
| related = titles_by_id.get(title_id) if title_id else None | |
| news_items.append({ | |
| "heading": heading, "summary": summary, "href": href, | |
| "image": related["card"] if related else people[0]["thumb"], | |
| }) | |
| product_cards = ( | |
| ("Search the directory", "Use same-origin title and people suggestions.", "/find/?q=Oppenheimer"), | |
| ("Tune recommendations", "Choose provider labels used by What to Watch.", "/preferences/preferredservices/"), | |
| ("Open the media viewer", "Browse title-bound images and local videos.", "/title/tt0468569/mediaindex/"), | |
| ) | |
| poll_choices = tuple( | |
| (title["title"], f"/title/{title['id']}/") | |
| for title in db.chart_titles(conn, "top")[:4] | |
| ) | |
| return render( | |
| request, | |
| conn, | |
| current_account(request, conn), | |
| "discovery.html", | |
| page_title=page_title, | |
| browse_title=page_title, | |
| browse_deck=page_deck, | |
| page_type=page_type, | |
| page_key=normalized.strip("/").replace("/", "-"), | |
| titles=db.chart_titles(conn, "popular")[:18], | |
| series=db.all_titles(conn, title_type="series"), | |
| people=people, | |
| genre_sections=genre_sections, | |
| media=media, | |
| videos=videos, | |
| collection_titles=collection_titles, | |
| calendar_groups=calendar_groups, | |
| news_items=news_items, | |
| route_links=DISCOVERY_ROUTE_LINKS.get(page_type, ()), | |
| product_cards=product_cards, | |
| poll_choices=poll_choices, | |
| site_groups=MENU_GROUPS, | |
| ) | |
| STATIC_BROWSE_ROUTES = tuple( | |
| route for route in sorted(set(BROWSE_PAGES) | set(BOUNDARY_PAGES)) | |
| if route not in { | |
| "/trailers/", "/what-to-watch/", "/preferences/preferredservices/", | |
| "/chart/top/", "/chart/moviemeter/", "/chart/toptv/", | |
| "/chart/tvmeter/", "/chart/boxoffice/", | |
| } | |
| ) | |
| for browse_route in STATIC_BROWSE_ROUTES: | |
| app.add_api_route( | |
| browse_route, | |
| browse_page, | |
| methods=["GET"], | |
| response_class=HTMLResponse, | |
| name=f"browse-{browse_route.strip('/').replace('/', '-')}", | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Test-compatibility snapshot (server-authoritative state, read-only) | |
| # --------------------------------------------------------------------------- | |
| def store_snapshot() -> dict: | |
| """Read-only snapshot of all account state straight from the database.""" | |
| return db.store_snapshot() | |
| def main() -> None: | |
| port = int(os.environ.get("PORT", str(DEFAULT_PORT))) | |
| uvicorn.run(app, host="127.0.0.1", port=port, access_log=True) | |
| if __name__ == "__main__": | |
| main() | |