{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"""
"""
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"
"""
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"""
Free preview
{esc(title)}
This local preview contains no account charge and does not contact an external manga service.
"
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.
Explore new releases, creator stories, and community highlights. This offline article keeps navigation and reading interactions available without loading remote content.
"""
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}
By creating an account you're agreeing to our Terms of Use & Privacy Policy, and you confirm that you are at least 18 years of age. A local verification step follows; no real email is sent.
""",
)
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, "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.
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"""
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"