from __future__ import annotations import hashlib import html import os import re import sqlite3 from pathlib import Path from urllib.parse import quote_plus from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from backend.site_backend_integration import open_site_services from backend.site_schema import reset_business from websitebench.local_clone_auth import AuthError from websitebench.site_backend.errors import PaymentError ROOT = Path(__file__).resolve().parent SITE_ID = "crunchyroll" DISPLAY_NAME = "Crunchyroll" BACKEND, AUTH = open_site_services() DB = BACKEND.lifecycle.database_path SESSION_COOKIE = BACKEND.session_cookie["name"] LOCAL_SESSION_COOKIE = f"websitebench-{SITE_ID}-session" LOCAL_HTTP_COOKIE = os.environ.get("WEBSITEBENCH_LOCAL_HTTP_COOKIE", "1") == "1" app = FastAPI( title=f"{DISPLAY_NAME} offline clone", docs_url=None, redoc_url=None, openapi_url=None, ) app.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static") DEMO_EMAIL = "viewer@example.test" DEMO_PASSWORD = "DemoPass123!" DEMO_SUBJECT_ID = "crunchyroll-demo-viewer" AUTH.seed_account( subject_id=DEMO_SUBJECT_ID, email=DEMO_EMAIL, display_name="Anime Fan", password=DEMO_PASSWORD, ) CATALOG = [ { "id": "GRMG8ZQZR", "slug": "one-piece", "title": "One Piece", "genre": "Adventure", "maturity": "14+", "rating": "4.9", "meta": "Sub | Dub", "c1": "#20466b", "c2": "#e85531", "synopsis": "Embark on a voyage with a spirited pirate crew searching for the legendary treasure known as the One Piece.", "cast": "Mayumi Tanaka, Kazuya Nakai, Akemi Okamura", "audio": "Japanese, English", "subtitles": "English (US), Español", "related": ["jujutsu-kaisen", "spy-x-family", "attack-on-titan"], }, { "id": "GRDV0019R", "slug": "jujutsu-kaisen", "title": "JUJUTSU KAISEN", "genre": "Action", "maturity": "16+", "rating": "4.8", "meta": "Sub | Dub", "c1": "#1a263d", "c2": "#6550a8", "synopsis": "A student enters a hidden world of curses and sorcerers after swallowing a powerful cursed object.", "cast": "Junya Enoki, Yuichi Nakamura", "audio": "Japanese, English", "subtitles": "English (US), Deutsch", "related": ["one-piece", "attack-on-titan", "chainsaw-man"], }, { "id": "G4PH0WXVJ", "slug": "spy-x-family", "title": "SPY x FAMILY", "genre": "Comedy", "maturity": "14+", "rating": "4.8", "meta": "Sub | Dub", "c1": "#27675f", "c2": "#e8b1b8", "synopsis": "A spy, an assassin, and a telepath form a pretend family while keeping their secret lives hidden.", "cast": "Takuya Eguchi, Atsumi Tanezaki", "audio": "Japanese, English", "subtitles": "English (US), Français", "related": ["one-piece", "frieren-beyond-journeys-end", "my-hero-academia"], }, { "id": "GR751KNZY", "slug": "attack-on-titan", "title": "Attack on Titan", "genre": "Drama", "maturity": "18+", "rating": "4.9", "meta": "Sub | Dub", "c1": "#31261f", "c2": "#8f392a", "synopsis": "Humanity fights for survival behind enormous walls as a young soldier uncovers the truth about the Titans.", "cast": "Yuki Kaji, Yui Ishikawa", "audio": "Japanese, English", "subtitles": "English (US), Español", "related": ["jujutsu-kaisen", "chainsaw-man", "one-piece"], }, { "id": "GG5H5XQX4", "slug": "frieren-beyond-journeys-end", "title": "Frieren: Beyond Journey's End", "genre": "Fantasy", "maturity": "14+", "rating": "4.9", "meta": "Sub | Dub", "c1": "#31495d", "c2": "#b7d3d4", "synopsis": "An elven mage retraces a heroic journey to understand the fleeting lives of her former companions.", "cast": "Atsumi Tanezaki, Kana Ichinose", "audio": "Japanese, English", "subtitles": "English (US)", "related": ["spy-x-family", "one-piece", "solo-leveling"], }, { "id": "GDKHZEJ0K", "slug": "solo-leveling", "title": "Solo Leveling", "genre": "Action", "maturity": "16+", "rating": "4.8", "meta": "Sub | Dub", "c1": "#17213a", "c2": "#7751bd", "synopsis": "The weakest hunter gains a mysterious ability to level up and takes on ever more dangerous dungeons.", "cast": "Taito Ban, Genta Nakamura", "audio": "Japanese, English", "subtitles": "English (US)", "related": ["jujutsu-kaisen", "chainsaw-man", "attack-on-titan"], }, { "id": "G6NQ5DWZ6", "slug": "my-hero-academia", "title": "My Hero Academia", "genre": "Action", "maturity": "14+", "rating": "4.7", "meta": "Sub | Dub", "c1": "#1e593c", "c2": "#f4bd35", "synopsis": "A determined student without powers inherits a heroic gift and enrolls at the world's leading hero academy.", "cast": "Daiki Yamashita, Nobuhiko Okamoto", "audio": "Japanese, English", "subtitles": "English (US)", "related": ["spy-x-family", "jujutsu-kaisen", "one-piece"], }, { "id": "GVDHX8QNW", "slug": "chainsaw-man", "title": "Chainsaw Man", "genre": "Action", "maturity": "18+", "rating": "4.7", "meta": "Sub | Dub", "c1": "#2b3d27", "c2": "#d95a22", "synopsis": "A debt-ridden devil hunter is reborn with the power of his chainsaw companion.", "cast": "Kikunosuke Toya, Tomori Kusunoki", "audio": "Japanese, English", "subtitles": "English (US)", "related": ["jujutsu-kaisen", "attack-on-titan", "solo-leveling"], }, { "id": "GY8VM8MWY", "slug": "haikyu", "title": "HAIKYU!!", "genre": "Sports", "maturity": "10+", "rating": "4.8", "meta": "Sub | Dub", "c1": "#19314d", "c2": "#f07b20", "synopsis": "A determined volleyball player joins forces with a former rival to take their high school team higher.", "cast": "Ayumu Murase, Kaito Ishikawa", "audio": "Japanese, English", "subtitles": "English (US)", "related": ["spy-x-family", "my-hero-academia", "one-piece"], }, ] CATALOG.append( { "id": "GT00371630", "slug": "daemons-of-the-shadow-realm", "title": "Daemons of the Shadow Realm", "genre": "Fantasy", "maturity": "16+", "rating": "4.8", "meta": "Sub | Dub", "c1": "#172b40", "c2": "#e65a2b", "synopsis": "Yuru, a young hunter living quietly in a remote village, is pulled into a world of powerful supernatural beings.", "cast": "Kensho Ono, Yume Miyamoto", "audio": "Japanese, English", "subtitles": "English (US), Español", "related": ["jujutsu-kaisen", "attack-on-titan", "frieren-beyond-journeys-end"], } ) BY_SLUG = {item["slug"]: item for item in CATALOG} BY_ID = {item["id"]: item for item in CATALOG} POSTER_SLUGS = { "one-piece", "jujutsu-kaisen", "spy-x-family", "attack-on-titan", "my-hero-academia", "daemons-of-the-shadow-realm", "frieren-beyond-journeys-end", "solo-leveling", "chainsaw-man", "haikyu", } EPISODES = [ { "id": "GN7UD8ARD", "number": 1, "title": "I'm Luffy! The Man Who's Gonna Be King of the Pirates!", "duration": 1440, }, { "id": "G14U4DMEJ", "number": 2, "title": "Enter the Great Swordsman! Pirate Hunter Roronoa Zoro!", "duration": 1440, }, { "id": "G6P8D8N76", "number": 3, "title": "Morgan versus Luffy! Who's the Mysterious Pretty Girl?", "duration": 1440, }, { "id": "G50UZEW02", "number": 4, "title": "Luffy's Past! Enter Red-Haired Shanks!", "duration": 1440, }, ] DAEMONS_EPISODES = [ { "id": "GE00374585ENUS", "number": 1, "title": "Asa and Yuru", "duration": 1440, } ] def episodes_for(item: dict) -> list[dict]: if item["slug"] == "one-piece": return EPISODES if item["slug"] == "daemons-of-the-shadow-realm": return DAEMONS_EPISODES return [ { "id": f"{item['id']}-E{number}", "number": number, "title": f"{item['title']} Episode {number}", "duration": 1440, } for number in range(1, 5) ] def esc(value: object) -> str: return html.escape(str(value), quote=True) def db() -> sqlite3.Connection: connection = sqlite3.connect(str(DB), timeout=30) connection.row_factory = sqlite3.Row connection.execute("PRAGMA foreign_keys=ON") connection.execute("PRAGMA busy_timeout=30000") return connection def is_loopback(request: Request) -> bool: host = request.client.host if request.client else "" return host in {"127.0.0.1", "::1", "localhost", "testclient"} def cookie_name(request: Request) -> str: return ( LOCAL_SESSION_COOKIE if LOCAL_HTTP_COOKIE and is_loopback(request) else SESSION_COOKIE ) def session(request: Request) -> tuple[str, dict]: token = getattr(request.state, "session_token", None) if token: resolved = AUTH.resolve_session(token) if resolved is not None: return token, resolved token = request.cookies.get(cookie_name(request)) token, value = AUTH.ensure_session(token) request.state.session_token = token return token, value def account(request: Request) -> dict | None: return session(request)[1].get("account") def owner(request: Request) -> str | None: item = account(request) return f"subject:{item['subject_id']}" if item else None def set_session_cookie(response, request: Request, token: str) -> None: secure = bool(BACKEND.session_cookie["secure"]) and not ( LOCAL_HTTP_COOKIE and is_loopback(request) ) response.set_cookie( cookie_name(request), token, httponly=True, samesite="lax", secure=secure, path="/", ) def ensure_member_rows(owner_id: str, *, seed_demo: bool = False) -> None: with db() as connection: connection.execute( "INSERT OR IGNORE INTO crunchyroll_profiles(owner,profile_id,name,maturity,language,is_active) VALUES (?,?,?,?,?,1)", (owner_id, "main", "Anime Fan", "Mature", "English (US)"), ) connection.execute( "INSERT OR IGNORE INTO crunchyroll_profiles(owner,profile_id,name,maturity,language,is_active) VALUES (?,?,?,?,?,0)", (owner_id, "kids", "Kids", "Teen", "English (US)"), ) connection.execute( "INSERT OR IGNORE INTO crunchyroll_preferences(owner) VALUES (?)", (owner_id,), ) device_removed = connection.execute( "SELECT 1 FROM crunchyroll_history WHERE owner=? AND item_type='device-deactivated' LIMIT 1", (owner_id,), ).fetchone() if not device_removed: connection.execute( "INSERT OR IGNORE INTO crunchyroll_devices(owner,device_id,label,last_used) VALUES (?,?,?,?)", (owner_id, "web-browser", "Web Browser", "Today"), ) connection.execute( "INSERT OR IGNORE INTO crunchyroll_progress(owner,episode_id,position,duration) VALUES (?,?,?,?)", (owner_id, EPISODES[0]["id"], 522, EPISODES[0]["duration"]), ) if seed_demo and owner_id == f"subject:{DEMO_SUBJECT_ID}": connection.execute( "INSERT OR IGNORE INTO crunchyroll_watchlist(owner,series_id) VALUES (?,?)", (owner_id, CATALOG[0]["id"]), ) connection.execute( "INSERT OR IGNORE INTO crunchyroll_subscriptions(owner,plan,term,status,amount_minor,currency,payment_scenario,flow_id) VALUES (?,?,?,?,?,?,?,?)", ( owner_id, "Mega Fan", "Monthly", "Active", 1399, "USD", "seeded-local", "seeded-demo", ), ) exists = connection.execute( "SELECT 1 FROM crunchyroll_history WHERE owner=? AND item_type='subscription'", (owner_id,), ).fetchone() if not exists: connection.execute( "INSERT INTO crunchyroll_history(owner,item_type,title,status,detail) VALUES (?,?,?,?,?)", ( owner_id, "subscription", "Mega Fan Monthly", "Active", "Local sandbox subscription · $13.99/month", ), ) connection.commit() def page_response(request: Request, document: str, *, status_code: int = 200): token, _ = session(request) response = HTMLResponse(document, status_code=status_code) set_session_cookie(response, request, token) return response def redirect_with_session(request: Request, path: str, token: str | None = None): active = token or session(request)[0] response = RedirectResponse(path, status_code=303) set_session_cookie(response, request, active) return response def nav(request: Request) -> str: member = account(request) is not None account_links = ( "ProfilesMy ListAccount" if member else "Log In" ) return f"""""" def shell(request: Request, title: str, body: str, *, status_code: int = 200) -> str: return f"""{esc(title)}{nav(request)}
{body}
""" def card(item: dict) -> str: image = ( f"{esc(item[" if item["slug"] in POSTER_SLUGS else f"{esc(item['title'])}" ) return f"""
{image}▶ View Series

{esc(item["title"])}

{esc(item["meta"])} · ★ {esc(item["rating"])}
""" def row(title: str, items: list[dict]) -> str: return f"""

{esc(title)}

View All
{"".join(card(x) for x in items[:5])}
""" def auth_card(title: str, contents: str) -> str: return f"

{esc(title)}

{contents}
" def protected(request: Request, next_path: str): if account(request) is not None: ensure_member_rows(owner(request) or "") return None q = quote_plus(next_path) return page_response( request, shell( request, "Sign in required", auth_card( "Log In Required", f"
Log in or create an account to continue.
Log InCreate Account
", ), ), status_code=401, ) @app.get("/healthz") def healthz() -> dict: return {"ok": True, "site_id": SITE_ID} @app.get("/__websitebench/health") def benchmark_health() -> dict: return {"status": "ok"} @app.post("/__websitebench/reset") def reset_state() -> dict: def reset_all(connection: sqlite3.Connection) -> None: BACKEND.lifecycle.reset_embedded(connection, confirm_site_id=SITE_ID) reset_business(connection) AUTH.reset_site_state( site_reset=reset_all, seed_accounts=[ { "subject_id": "crunchyroll-demo-viewer", "email": DEMO_EMAIL, "display_name": "Anime Fan", "password": DEMO_PASSWORD, "email_verified": True, } ], ) ensure_member_rows(f"subject:{DEMO_SUBJECT_ID}", seed_demo=True) return {"ok": True, "site_id": SITE_ID, "seed": "crunchyroll-seed-v1"} @app.get("/", response_class=HTMLResponse) def home(request: Request): member = account(request) if member: ensure_member_rows(owner(request) or "") hero = """
Daemons of the Shadow Realm
16+ · Sub | Dub · Action, Adventure, Fantasy

Yuru, a young hunter who lives quietly in a remote village, is pulled into a world of powerful supernatural beings.

""" continue_row = row("Continue Watching", CATALOG[:5]) if member else "" body = ( hero + continue_row + row("Most Popular", CATALOG[:5]) + row("New Episodes", CATALOG[3:8]) + row("Because You Watched Action", CATALOG[5:10]) ) return page_response( request, shell(request, "Watch Popular Anime & Read Manga Online", body) ) @app.get("/videos/{kind}", response_class=HTMLResponse) def browse(request: Request, kind: str, genre: str = "", sort: str = "popular"): allowed_genres = {"action", "adventure", "comedy", "drama", "fantasy", "sports"} if kind not in {"popular", "new", "alphabetical", *allowed_genres}: return not_found(request) items = list(CATALOG) heading = { "popular": "Popular", "new": "Newly Added", "alphabetical": "Browse All (A-Z)", "action": "Action", "adventure": "Adventure", "drama": "Drama", "comedy": "Comedy", "fantasy": "Fantasy", "sports": "Sports", }[kind] if kind in allowed_genres: items = [x for x in items if x["genre"].casefold() == kind] elif genre.casefold() in allowed_genres: items = [x for x in items if x["genre"].casefold() == genre.casefold()] if kind == "alphabetical" or sort == "alphabetical": items = sorted(items, key=lambda x: x["title"]) cards = "".join(card(x) for x in items) body = f"""
Browse anime

{esc(heading)}

Explore series available in the offline anime catalog.

{cards}
""" return page_response(request, shell(request, f"{heading} Anime", body)) @app.get("/search", response_class=HTMLResponse) def search(request: Request, q: str = ""): query = q.strip() results = ( [ x for x in CATALOG if query.casefold() in (x["title"] + " " + x["genre"]).casefold() ] if query else CATALOG ) if results: content = f"
{''.join(card(x) for x in results)}
" message = ( f"{len(results)} matching title{'s' if len(results) != 1 else ''}" if query else "Browse every title" ) else: content = """

No results found

We couldn't find a match. Try another title or clear your search.

Browse PopularClear Search
""" message = "No matches" body = f"""
Anime records and actions

Search

{esc(message)}

{content}
""" return page_response(request, shell(request, f"Search {query}".strip(), body)) @app.get("/series/{series_id}/{slug}", response_class=HTMLResponse) def series(request: Request, series_id: str, slug: str): item = BY_ID.get(series_id) or BY_SLUG.get(slug) if item is None: return not_found(request) member = account(request) is not None saved = False if member: ensure_member_rows(owner(request) or "") with db() as connection: saved = ( connection.execute( "SELECT 1 FROM crunchyroll_watchlist WHERE owner=? AND series_id=?", (owner(request), item["id"]), ).fetchone() is not None ) watch_action = f"""
""" episodes = episodes_for(item) episode_html = "".join( f"""
E{ep["number"]}
Episode {ep["number"]} · {esc(ep["title"])}

24m · Sub | Dub

Play
""" for ep in episodes ) related = [BY_SLUG[x] for x in item["related"] if x in BY_SLUG] hero = f"""
{esc(item["genre"])} · Series

{esc(item["title"])}

★ {esc(item["rating"])}{esc(item["maturity"])} {esc(item["meta"])}

{esc(item["synopsis"])}

Start Watching E1{watch_action}
""" details = f"""

Season 1

{episode_html}
""" return page_response( request, shell(request, item["title"], hero + details + row("More Like This", related)), ) @app.post("/watchlist/toggle") def toggle_watchlist( request: Request, series_id: str = Form(""), return_to: str = Form("/watchlist") ): guard = protected(request, return_to) if guard: return guard item = BY_ID.get(series_id) if not item: return redirect_with_session(request, "/watchlist") owner_id = owner(request) with db() as connection: # Serialize the read/modify/write toggle; concurrent requests must not # both observe an absent row and race the unique constraint. connection.execute("BEGIN IMMEDIATE") existing = connection.execute( "SELECT 1 FROM crunchyroll_watchlist WHERE owner=? AND series_id=?", (owner_id, series_id), ).fetchone() if existing: connection.execute( "DELETE FROM crunchyroll_watchlist WHERE owner=? AND series_id=?", (owner_id, series_id), ) else: connection.execute( "INSERT INTO crunchyroll_watchlist(owner,series_id) VALUES (?,?)", (owner_id, series_id), ) connection.commit() safe_return = ( return_to if return_to.startswith("/") and not return_to.startswith("//") else "/watchlist" ) return redirect_with_session(request, safe_return) @app.get("/watchlist", response_class=HTMLResponse) def watchlist(request: Request): guard = protected(request, "/watchlist") if guard: return guard with db() as connection: ids = [ x["series_id"] for x in connection.execute( "SELECT series_id FROM crunchyroll_watchlist WHERE owner=? ORDER BY created_at DESC", (owner(request),), ) ] items = [BY_ID[x] for x in ids if x in BY_ID] content = ( f"
{''.join(card(x) for x in items)}
" if items else "

Your Watchlist is empty

Add a series to find it here.

Browse Popular
" ) return page_response( request, shell( request, "My List", f"
Your library

My List

{content}
", ), ) @app.get("/manga", response_class=HTMLResponse) def manga(request: Request): books = ( ("Smoking Behind the Supermarket with You", "manga-1.webp"), ("The Summer Hikaru Died", "manga-2.webp"), ("That Time I Got Reincarnated as a Slime", "manga-3.webp"), ("My Dress-Up Darling", "manga-4.webp"), ) cards = "".join( f"{esc(title)} cover

{esc(title)}

Read preview →
" for i, (title, image) in enumerate(books, 1) ) body = f"""
Crunchyroll Manga

A new way to read manga

Discover popular stories and continue reading with a local preview experience.

Explore Manga

Popular right now

Search all
{cards}
""" return page_response(request, shell(request, "Read Manga Online", body)) @app.get("/manga/{book_id}", response_class=HTMLResponse) def manga_detail(request: Request, book_id: int): if book_id not in {1, 2, 3, 4}: return not_found(request) title = ("Smoking Behind the Supermarket with You", "The Summer Hikaru Died", "That Time I Got Reincarnated as a Slime", "My Dress-Up Darling")[book_id - 1] body = f"""
Cover of {esc(title)}
Free preview

{esc(title)}

This local preview contains no account charge and does not contact an external manga service.

Back to Manga
""" return page_response(request, shell(request, title, body)) @app.get("/games", response_class=HTMLResponse) def games(request: Request): body = """
Crunchyroll Games

Play anime-inspired games

Discover Game Vault titles included with eligible Premium memberships.

Featured Games

Moonstone Island

Creature-collecting life sim

View Game
Shantae and the Seven Sirens

Platform adventure

View Game
""" return page_response(request, shell(request, "Anime-Inspired Games", body)) @app.get("/games/{game_id}", response_class=HTMLResponse) def game_detail(request: Request, game_id: str): names = {"river-city-girls": "River City Girls", "moonstone-island": "Moonstone Island", "shantae": "Shantae and the Seven Sirens"} if game_id not in names: return not_found(request) body = f"""
Game Vault

{esc(names[game_id])}

This page recreates game discovery locally. Game installation is unavailable in the offline fixture.

""" return page_response(request, shell(request, names[game_id], body)) @app.get("/store", response_class=HTMLResponse) def store(request: Request): body = """
Crunchyroll Store

Anime merch for every fan

Figures, apparel, manga, and exclusive collectibles.

Shop Featured

Featured collections

ONE PIECE

Monkey D. Luffy Figure

$29.99

JUJUTSU KAISEN

Sorcerer Hoodie

$54.95

SPY x FAMILY

Anya Plush

$24.99

""" return page_response(request, shell(request, "Crunchyroll Store", body)) @app.get("/news", response_class=HTMLResponse) def news(request: Request): stories = ("New Anime Arrivals to Watch This Week", "Behind the Scenes with Your Favorite Creators", "The Biggest Announcements from Anime Expo", "Summer Season Streaming Guide") articles = "".join(f"{esc(title)}
Anime News

{esc(title)}

Read the latest story, interviews, and updates.

" for i, title in enumerate(stories, 1)) body = f"
Crunchyroll News

Latest Anime News

Events
{articles}
" return page_response(request, shell(request, "Anime News & Top Stories", body)) @app.get("/news/{story_id}", response_class=HTMLResponse) def news_detail(request: Request, story_id: int): stories = ("New Anime Arrivals to Watch This Week", "Behind the Scenes with Your Favorite Creators", "The Biggest Announcements from Anime Expo", "Summer Season Streaming Guide") if story_id not in range(1, 5): return not_found(request) title = stories[story_id - 1] body = f"""
Anime News

{esc(title)}

The latest news from the world of anime, recreated from the supplied page materials.

{esc(title)}

Explore new releases, creator stories, and community highlights. This offline article keeps navigation and reading interactions available without loading remote content.

All NewsWatch New Anime
""" return page_response(request, shell(request, title, body)) @app.get("/events", response_class=HTMLResponse) def events(request: Request): body = """
Events & Experiences

See Crunchyroll live

Explore convention appearances, premieres, and fan experiences.

Upcoming Events

Upcoming Events

""" return page_response(request, shell(request, "Events", body)) @app.get("/events/{event_id}", response_class=HTMLResponse) def event_detail(request: Request, event_id: str): names = {"crunchyroll-expo": "Crunchyroll Expo", "anime-nyc": "Anime NYC"} if event_id not in names: return not_found(request) body = f"
Event Details

{esc(names[event_id])}

Schedule and venue details are shown as a local preview. Registration is not performed by this offline clone.

Back to Events
" return page_response(request, shell(request, names[event_id], body)) @app.get("/animeawards", response_class=HTMLResponse) def anime_awards(request: Request): body = """
Crunchyroll Anime Awards

Celebrating anime's brightest stars

Relive winners, performances, and unforgettable moments.

2026 Highlights

Anime of the Year

Discover this year's winner

Best Animation

Celebrating outstanding artistry

Best Original Anime

Honoring bold new stories

""" return page_response(request, shell(request, "The Anime Awards", body)) @app.get("/simulcastcalendar", response_class=HTMLResponse) def simulcast_calendar(request: Request, day: str = "Monday"): days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") day = day if day in days else "Monday" tabs = "".join( "{label}".format( active="active" if item == day else "", day=item, label=item[:3] ) for item in days ) episodes = "".join(f"
E{i}

{esc(show['title'])}

Episode {i} · Available at {9 + i}:00 PM

View Series
" for i, show in enumerate(CATALOG[:4], 1)) body = f"
Release Calendar

Simulcast Calendar

{tabs}

{esc(day)}

{episodes}
" return page_response(request, shell(request, "Simulcast Calendar", body)) @app.get("/premium", response_class=HTMLResponse) def premium(request: Request, term: str = "monthly"): term = "yearly" if term == "yearly" else "monthly" prices = {"Fan": "7.99", "Mega Fan": "13.99", "Ultimate Fan": "17.99"} plans = [] benefits = { "Fan": [ "Stream on 1 device", "Full anime library", "New episodes shortly after Japan", ], "Mega Fan": [ "Stream on 4 devices", "Offline viewing", "Crunchyroll Game Vault", "Store benefits", ], "Ultimate Fan": [ "Stream on 6 devices", "Offline viewing", "Exclusive merchandise", "Expanded store benefits", ], } for name in ("Fan", "Mega Fan", "Ultimate Fan"): price = prices[name] if term == "monthly" else f"{float(prices[name]) * 10:.2f}" badge = "
Most Popular
" if name == "Mega Fan" else "" plans.append( f"""
{badge}

{name}

${price}/{"mo" if term == "monthly" else "yr"}
""" ) body = f"""
Premium membership

Upgrade Your Anime Experience with Premium

Choose the plan that fits how you watch.

MonthlyYearly
{"".join(plans)}

Local fixture pricing in USD. Plans renew until cancelled. No real payment information is accepted.

""" return page_response(request, shell(request, "Crunchyroll Premium", body)) @app.post("/select-plan") def select_plan(request: Request, plan: str = Form(""), term: str = Form("monthly")): if plan not in {"Fan", "Mega Fan", "Ultimate Fan"}: return redirect_with_session(request, "/premium") path = f"/checkout?plan={quote_plus(plan)}&term={'yearly' if term == 'yearly' else 'monthly'}" if account(request) is None: return redirect_with_session(request, f"/register?next={quote_plus(path)}") return redirect_with_session(request, path) @app.get("/login", response_class=HTMLResponse) def login_form(request: Request, next: str = "/", error: str = ""): message = f"
{esc(error)}
" if error else "" body = auth_card( "Log In", f"""{message}
Demo access
""", ) return page_response(request, shell(request, "Log In", body)) @app.post("/login") def login( request: Request, email: str = Form(""), password: str = Form(""), next: str = Form("/"), ): token, _ = session(request) if not email or not password: return login_form(request, next, "Enter your email address and password.") try: result = AUTH.sign_in(token, email=email, password=password) except AuthError: return login_form(request, next, "Email address or password is incorrect.") destination = next if next.startswith("/") and not next.startswith("//") else "/" ensure_member_rows(f"subject:{result['account']['subject_id']}") return redirect_with_session(request, destination, result["session_token"]) @app.post("/fixture/session") def fixture_session(request: Request, next: str = Form("/")): token, _ = session(request) result = AUTH.sign_in(token, email=DEMO_EMAIL, password=DEMO_PASSWORD) ensure_member_rows(f"subject:{result['account']['subject_id']}", seed_demo=True) destination = next if next.startswith("/") and not next.startswith("//") else "/" return redirect_with_session(request, destination, result["session_token"]) @app.post("/logout") def logout(request: Request): AUTH.sign_out(request.cookies.get(cookie_name(request))) return redirect_with_session(request, "/") @app.get("/register", response_class=HTMLResponse) def register_form( request: Request, next: str = "/checkout?plan=Mega+Fan&term=monthly", error: str = "", ): message = f"
{esc(error)}
" if error else "" body = auth_card( "Create Account", f"""{message}
Use at least 6 characters, do not use empty spaces
""", ) return page_response(request, shell(request, "Create Account", body)) @app.post("/register") def register( request: Request, email: str = Form(""), password: str = Form(""), next: str = Form("/checkout?plan=Mega+Fan&term=monthly"), ): token, _ = session(request) if not email or not password: return register_form( request, next, "Enter an email address and password before continuing." ) try: AUTH.start_registration( token, email=email, display_name=email.split("@", 1)[0] or "Anime Fan", password=password, ) mail = AUTH.local_mail_for_session(token, purpose="registration") except (AuthError, ValueError) as exc: return register_form(request, next, str(exc)) if not mail: return register_form( request, next, "Local verification guidance is unavailable. Try again." ) body = auth_card( "Verify Your Email", f"""
No email was sent. Use this local-only verification code: {esc(mail["verification_code"])}

The code belongs only to this browser session and expires locally.

""", ) return page_response(request, shell(request, "Verify Your Email", body)) @app.post("/register/verify") def verify_registration( request: Request, code: str = Form(""), next: str = Form("/checkout?plan=Mega+Fan&term=monthly"), ): token, _ = session(request) try: AUTH.verify_registration_code(token, code) result = AUTH.complete_registration(token) except AuthError as exc: return register_form(request, next, str(exc)) ensure_member_rows(f"subject:{result['account']['subject_id']}") destination = next if next.startswith("/") and not next.startswith("//") else "/" return redirect_with_session(request, destination, result["session_token"]) @app.get("/reset-password", response_class=HTMLResponse) def reset_form(request: Request, error: str = "", notice: str = ""): message = ( f"
{esc(error)}
" if error else (f"
{esc(notice)}
" if notice else "") ) body = auth_card( "Reset Password", f"""{message}

A link would normally be sent to your email address to reset your password. This offline clone sends nothing.

""", ) return page_response(request, shell(request, "Reset Password", body)) @app.post("/reset-password") def reset_password(request: Request, email: str = Form("")): if not email: return reset_form(request, "Enter the email address for the account.") token, _ = session(request) try: AUTH.start_password_reset(token, email=email) except (AuthError, ValueError): pass return reset_form( request, notice="If a matching local account exists, recovery guidance is available in this browser. No reset message was sent.", ) @app.get("/profiles", response_class=HTMLResponse) def profiles(request: Request, error: str = ""): guard = protected(request, "/profiles") if guard: return guard with db() as connection: rows = connection.execute( "SELECT * FROM crunchyroll_profiles WHERE owner=? ORDER BY profile_id", (owner(request),), ).fetchall() cards = "".join( f"""
{esc(x["name"][:1])}

{esc(x["name"])}

{esc(x["maturity"])} · {esc(x["language"])}

""" for x in rows ) body = f"""
Who's watching?

Select Profile

{f"
{esc(error)}
" if error else ""}
{cards}

Create or edit a profile

""" return page_response(request, shell(request, "Select Profile", body)) @app.post("/profiles") def save_profile( request: Request, name: str = Form(""), maturity: str = Form("Mature"), language: str = Form("English (US)"), ): guard = protected(request, "/profiles") if guard: return guard clean = name.strip() if not clean: return profiles(request, "Profile name is required.") profile_id = ( re.sub(r"[^a-z0-9]+", "-", clean.casefold()).strip("-")[:30] or "profile" ) with db() as connection: connection.execute( "INSERT INTO crunchyroll_profiles(owner,profile_id,name,maturity,language,is_active) VALUES (?,?,?,?,?,0) ON CONFLICT(owner,profile_id) DO UPDATE SET name=excluded.name,maturity=excluded.maturity,language=excluded.language", (owner(request), profile_id, clean, maturity, language), ) connection.commit() return redirect_with_session(request, "/profiles") @app.post("/profiles/switch") def switch_profile(request: Request, profile_id: str = Form("")): guard = protected(request, "/profiles") if guard: return guard with db() as connection: exists = connection.execute( "SELECT 1 FROM crunchyroll_profiles WHERE owner=? AND profile_id=?", (owner(request), profile_id), ).fetchone() if exists: connection.execute( "UPDATE crunchyroll_profiles SET is_active=0 WHERE owner=?", (owner(request),), ) connection.execute( "UPDATE crunchyroll_profiles SET is_active=1 WHERE owner=? AND profile_id=?", (owner(request), profile_id), ) connection.commit() return redirect_with_session(request, "/") @app.get("/watch/{episode_id}/{slug}", response_class=HTMLResponse) def watch(request: Request, episode_id: str, slug: str): guard = protected(request, request.url.path) if guard: return guard series_item = next((x for x in CATALOG if x["slug"] in slug), None) if series_item is None: series_item = next( ( item for item in CATALOG if any(ep["id"] == episode_id for ep in episodes_for(item)) ), CATALOG[0], ) episodes = episodes_for(series_item) episode = next((x for x in episodes if x["id"] == episode_id), episodes[0]) with db() as connection: progress = connection.execute( "SELECT position,duration FROM crunchyroll_progress WHERE owner=? AND episode_id=?", (owner(request), episode["id"]), ).fetchone() position = int(progress["position"]) if progress else 0 index = episodes.index(episode) next_action = ( f"Next Episode" if index + 1 < len(episodes) else f"Back to Series" ) body = f"""
Local controls and progress simulation. No licensed media or remote stream is loaded.

{esc(series_item["title"])}

Episode {episode["number"]} · {esc(episode["title"])}

{position // 60}m
Episodes & Seasons{next_action}
""" return page_response(request, shell(request, f"Watch {series_item['title']}", body)) @app.post("/api/progress") async def save_progress(request: Request): if account(request) is None: return JSONResponse( { "error": "sign-in-required", "correction": "Log in before saving playback progress.", }, status_code=401, ) data = await request.json() episode_id = str(data.get("episode_id", "")) try: position = max(0, int(data.get("position", 0))) duration = max(1, int(data.get("duration", 1440))) except (TypeError, ValueError): return JSONResponse({"error": "invalid-progress"}, status_code=422) with db() as connection: connection.execute( "INSERT INTO crunchyroll_progress(owner,episode_id,position,duration,updated_at) VALUES (?,?,?,?,strftime('%s','now')) ON CONFLICT(owner,episode_id) DO UPDATE SET position=excluded.position,duration=excluded.duration,updated_at=excluded.updated_at", (owner(request), episode_id, min(position, duration), duration), ) connection.commit() return {"ok": True, "position": min(position, duration)} @app.get("/checkout", response_class=HTMLResponse) def checkout( request: Request, plan: str = "Mega Fan", term: str = "monthly", error: str = "", status: str = "", ): guard = protected(request, request.url.path + "?" + request.url.query) if guard: return guard plan = plan if plan in {"Fan", "Mega Fan", "Ultimate Fan"} else "Mega Fan" term = "yearly" if term == "yearly" else "monthly" amounts = {"Fan": 799, "Mega Fan": 1399, "Ultimate Fan": 1799} amount = amounts[plan] * (10 if term == "yearly" else 1) message = ( f"
{esc(error)}
" if error else (f"
{esc(status)}
" if status else "") ) body = f"""
Secure local checkout

Review Membership

{message}

{esc(plan)} · {term.title()}

${amount / 100:.2f}/{"mo" if term == "monthly" else "yr"}

4 concurrent streams and offline viewing are included with Mega Fan.

Change plan

Payment option

Local sandbox only. Do not enter a card number, CVV, bank account, wallet, or real payment credential.

""" return page_response(request, shell(request, "Review Membership", body)) @app.post("/checkout") def complete_checkout( request: Request, plan: str = Form(""), term: str = Form(""), scenario: str = Form(""), terms: str = Form(""), card_number: str = Form(""), cvv: str = Form(""), ): guard = protected(request, "/checkout") if guard: return guard if card_number or cvv: return checkout( request, plan or "Mega Fan", term or "monthly", "Payment credentials are forbidden. Choose only a local sandbox outcome.", ) if ( plan not in {"Fan", "Mega Fan", "Ultimate Fan"} or term not in {"monthly", "yearly"} or scenario not in {"sandbox-approved", "sandbox-declined", "sandbox-retry"} or not terms ): return checkout( request, plan or "Mega Fan", term or "monthly", "Choose a valid plan, local outcome, and accept the terms before continuing.", ) amount = {"Fan": 799, "Mega Fan": 1399, "Ultimate Fan": 1799}[plan] * ( 10 if term == "yearly" else 1 ) owner_id = owner(request) or "" fingerprint = hashlib.sha256( f"{SITE_ID}|{owner_id}|{plan}|{term}|{amount}|USD".encode() ).hexdigest() key_suffix = hashlib.sha256( f"{owner_id}|{plan}|{term}|{scenario}".encode() ).hexdigest()[:24] with db() as connection: existing = connection.execute( "SELECT plan,term,status FROM crunchyroll_subscriptions WHERE owner=?", (owner_id,), ).fetchone() if ( existing and existing["plan"] == plan and existing["term"] == term.title() and existing["status"] == "Active" ): return redirect_with_session(request, "/account/history") try: with BACKEND.lifecycle.connection(transaction=True) as connection: flow = BACKEND.payments.create_intent( owner=owner_id, amount_minor=amount, currency="USD", fingerprint=fingerprint, idempotency_key=f"checkout-create:{key_suffix}", connection=connection, ) attempt = BACKEND.payments.attempt( flow_id=flow["flow_id"], owner=owner_id, amount_minor=amount, currency="USD", fingerprint=fingerprint, scenario_id=scenario, idempotency_key=f"checkout-attempt:{key_suffix}", connection=connection, ) if attempt["status"] == "APPROVED": BACKEND.payments.consume_approval( connection, flow_id=flow["flow_id"], owner=owner_id, amount_minor=amount, currency="USD", fingerprint=fingerprint, ) connection.execute( "INSERT INTO crunchyroll_subscriptions(owner,plan,term,status,amount_minor,currency,payment_scenario,flow_id) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(owner) DO UPDATE SET plan=excluded.plan,term=excluded.term,status=excluded.status,amount_minor=excluded.amount_minor,currency=excluded.currency,payment_scenario=excluded.payment_scenario,flow_id=excluded.flow_id", ( owner_id, plan, term.title(), "Active", amount, "USD", scenario, flow["flow_id"], ), ) connection.execute( "INSERT INTO crunchyroll_history(owner,item_type,title,status,detail) VALUES (?,?,?,?,?)", ( owner_id, "subscription", f"{plan} {term.title()}", "Active", f"Local sandbox subscription · ${amount / 100:.2f}/{'month' if term == 'monthly' else 'year'}", ), ) except PaymentError as exc: return checkout(request, plan, term, str(exc)) if attempt["status"] == "DECLINED": return checkout( request, plan, term, "The local sandbox declined this attempt. Choose another outcome and try again.", ) if attempt["status"] == "RETRYABLE": return checkout( request, plan, term, "The local sandbox is temporarily unavailable. Retry when ready.", ) return redirect_with_session(request, "/account/history?created=1") @app.get("/account/history", response_class=HTMLResponse) def history(request: Request, created: int = 0): guard = protected(request, "/account/history") if guard: return guard ensure_member_rows(owner(request) or "") with db() as connection: rows = connection.execute( "SELECT * FROM crunchyroll_history WHERE owner=? ORDER BY created_at DESC,history_id DESC", (owner(request),), ).fetchall() items = "".join( f"""
{esc(x["item_type"])}

{esc(x["title"])}

{esc(x["detail"])}

{esc(x["status"])}
DetailsEdit or Cancel
""" for x in rows ) message = ( "
Mega Fan membership was saved to your account history.
" if created else "" ) return page_response( request, shell( request, "Account History", f"
Account

History

{message}{items}Back to My List
", ), ) @app.get("/account/settings", response_class=HTMLResponse) def settings(request: Request, tab: str = "preferences", saved: int = 0, cancelled: int = 0): guard = protected(request, "/account/settings") if guard: return guard ensure_member_rows(owner(request) or "") with db() as connection: prefs = connection.execute( "SELECT * FROM crunchyroll_preferences WHERE owner=?", (owner(request),) ).fetchone() subscription = connection.execute( "SELECT * FROM crunchyroll_subscriptions WHERE owner=?", (owner(request),) ).fetchone() devices = connection.execute( "SELECT * FROM crunchyroll_devices WHERE owner=?", (owner(request),) ).fetchall() side = """""" if tab == "billing": plan = ( f"

{esc(subscription['plan'])} · {esc(subscription['term'])}

{esc(subscription['status'])} · ${subscription['amount_minor'] / 100:.2f} {esc(subscription['currency'])}

" if subscription else "

No active membership

" ) notice = "
Your local membership was cancelled.
" if cancelled else "" cancel = "" if not subscription or subscription["status"] == "Cancelled" else """""" content = f"""{notice}
{plan}
Upgrade or Downgrade{cancel}Payment History

Actions affect only the local sandbox account.

Cancel membership?

Your access remains a local simulation. This action can be reversed by choosing another plan.

""" elif tab == "devices": content = ( "

Manage Devices

" + "".join( f"
{esc(x['label'])}
{esc(x['last_used'])}
" for x in devices ) + ("

No active devices remain.

" if not devices else "") + "
" ) else: content = f"""

Playback & Language

{'
Preferences saved.
' if saved else ""}
""" body = f"
Account

Settings

{side}
{content}
" return page_response(request, shell(request, "Account Settings", body)) @app.post("/account/settings") def save_settings( request: Request, audio_language: str = Form("Japanese"), subtitle_language: str = Form("English (US)"), autoplay: str = Form(""), notifications: str = Form(""), privacy_mode: str = Form("Standard"), ): guard = protected(request, "/account/settings") if guard: return guard with db() as connection: connection.execute( "UPDATE crunchyroll_preferences SET audio_language=?,subtitle_language=?,autoplay=?,notifications=?,privacy_mode=? WHERE owner=?", ( audio_language, subtitle_language, int(bool(autoplay)), int(bool(notifications)), privacy_mode, owner(request), ), ) connection.commit() return redirect_with_session(request, "/account/settings?saved=1") @app.post("/account/subscription/cancel") def cancel_subscription(request: Request): guard = protected(request, "/account/settings?tab=billing") if guard: return guard with db() as connection: subscription = connection.execute( "SELECT plan,term FROM crunchyroll_subscriptions WHERE owner=?", (owner(request),), ).fetchone() if subscription: connection.execute( "UPDATE crunchyroll_subscriptions SET status='Cancelled' WHERE owner=?", (owner(request),), ) connection.execute( "INSERT INTO crunchyroll_history(owner,item_type,title,status,detail) VALUES (?,?,?,?,?)", (owner(request), "subscription", f"{subscription['plan']} {subscription['term'].title()}", "Cancelled", "Local sandbox membership cancellation"), ) connection.commit() return redirect_with_session(request, "/account/settings?tab=billing&cancelled=1") @app.post("/account/devices/remove") def remove_device(request: Request, device_id: str = Form("")): guard = protected(request, "/account/settings?tab=devices") if guard: return guard with db() as connection: removed = connection.execute( "SELECT label FROM crunchyroll_devices WHERE owner=? AND device_id=?", (owner(request), device_id), ).fetchone() connection.execute( "DELETE FROM crunchyroll_devices WHERE owner=? AND device_id=?", (owner(request), device_id), ) if removed: connection.execute( "INSERT INTO crunchyroll_history(owner,item_type,title,status,detail) VALUES (?,?,?,?,?)", (owner(request), "device-deactivated", removed["label"], "Deactivated", "Local device access removed"), ) connection.commit() return redirect_with_session(request, "/account/settings?tab=devices") @app.get("/help", response_class=HTMLResponse) def help_page(request: Request, q: str = ""): query = q.strip() topics = ( ("Using Crunchyroll", "Browse anime records, search titles, manage My List, and use playback controls.", "/videos/popular", "Browse anime"), ("Account Access", "Find sign-in, registration, profile, password recovery, and membership guidance.", "/login", "Account access"), ("Fix a Problem", "Get guidance for failed actions, billing, subtitles, audio, and video playback.", "/help/contact", "Contact Us"), ) matches = [topic for topic in topics if not query or query.casefold() in (topic[0] + " " + topic[1]).casefold()] results = "".join(f"

{esc(title)}

{esc(copy)}

{esc(label)}
" for title, copy, path, label in matches) if not results: results = "

No help topics found

Try another phrase or contact support.

Contact Us
" body = f"""
Support & Customer Service

Crunchyroll Help

{f'

{len(matches)} topic(s) found

' if query else ''}
{results}
""" return page_response(request, shell(request, "Crunchyroll Help", body)) @app.get("/help/contact", response_class=HTMLResponse) def contact(request: Request): body = """
Support

Contact Us

Choose the guidance that matches your issue. This offline support page does not send a ticket or expose private account data.

Anime records and actionsBrowse guidance
Account accessRecovery guidance
Failed playback or billing actionAccount guidance
Back to Help
""" return page_response(request, shell(request, "Contact Us", body)) @app.get("/terms", response_class=HTMLResponse) def terms(request: Request): return page_response( request, shell( request, "Terms of Use", "

Terms of Use

This offline fixture accepts only synthetic local data and creates no external service effect.

", ), ) @app.get("/privacy", response_class=HTMLResponse) def privacy(request: Request): return page_response( request, shell( request, "Privacy Policy", "

Privacy Policy

No credentials, cookies, private account data, or payment information are sent to a remote service.

", ), ) @app.get("/accessibility", response_class=HTMLResponse) def accessibility(request: Request): return page_response( request, shell( request, "Accessibility", "

Accessibility

Keyboard-labelled controls, semantic headings, visible focus, and responsive layouts are provided throughout this offline experience.

", ), ) @app.get("/{path:path}", response_class=HTMLResponse) def not_found(request: Request, path: str = ""): body = """
404

Page Not Found

Yuzu says there's nothing to see here!

Browse Popular AnimeTake Me Home
""" return page_response( request, shell(request, "404 - Page Not Found", body), status_code=404 )