from __future__ import annotations import html import hashlib import os import re import sqlite3 import threading import time from pathlib import Path from urllib.parse import quote_plus, unquote, urlsplit 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 websitebench.local_clone_auth import AuthConflict, AuthError, AuthRejected from websitebench.site_backend.errors import PaymentError, PaymentRejected ROOT = Path(__file__).resolve().parent BACKEND, AUTH = open_site_services() DB = BACKEND.lifecycle.database_path SITE_ID = "blinkist" SESSION_COOKIE = BACKEND.session_cookie["name"] LOCAL_SESSION_COOKIE = f"websitebench-{SITE_ID}-session" COOKIE_SECURE = bool(BACKEND.session_cookie["secure"]) LOCAL_HTTP_COOKIE_OVERRIDE = os.environ.get("WEBSITEBENCH_LOCAL_HTTP_COOKIE", "1") == "1" APP = FastAPI(title="Blinkist offline clone", docs_url=None, redoc_url=None, openapi_url=None) APP.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static") _DB_SCHEMA_LOCK = threading.Lock() _DB_SCHEMA_READY = False @APP.get("/__websitebench/health") async def websitebench_health(): return {"status": "ok"} @APP.get("/healthz") async def healthz(): return {"status": "ok"} def esc(value: object) -> str: return html.escape(str(value), quote=True) def slugify(value: str) -> str: return re.sub(r"[^a-z0-9]+", "-", value.casefold()).strip("-") def books() -> list[dict[str, object]]: rows = [{"slug": "atomic-habits", "title": "Atomic Habits", "author": "James Clear", "category": "Productivity", "minutes": 25, "color": "#d9e6ff", "description": "An Easy & Proven Way to Build Good Habits & Break Bad Ones.", "narrator": "Amanda Mahr", "rating": 4.6, "ratings": 23456, "key_ideas": 7, "level": "Beginner", "language": "English", "schedule": "On demand"}] seed = [ ("The Psychology of Money", "Morgan Housel", "Money"), ("Deep Work", "Cal Newport", "Productivity"), ("Thinking, Fast and Slow", "Daniel Kahneman", "Mind"), ("The 7 Habits of Highly Effective People", "Stephen R. Covey", "Self-improvement"), ("Essentialism", "Greg McKeown", "Productivity"), ("The Power of Habit", "Charles Duhigg", "Psychology"), ("The Almanack of Naval Ravikant", "Eric Jorgenson", "Success"), ("Mindset", "Carol S. Dweck", "Psychology"), ("Teams That Meet the Moment", "Karina Mangu-Ward", "Career & Success"), ("The Ambition Penalty", "Stefanie O’Connell", "Career & Success"), ] rows.extend({"slug": slugify(title), "title": title, "author": author, "category": category, "minutes": 12 + (i % 9), "color": ["#f6dccd", "#d8f0e8", "#f4e6bd", "#e7dafa"][i % 4], "description": f"A concise Blink of {title} with practical ideas you can apply today.", "narrator": "Blinkist Audio", "rating": 4.4, "ratings": 1200 + i, "key_ideas": 6, "level": ("Beginner", "Intermediate", "Advanced")[i % 3], "language": "English", "schedule": "On demand"} for i, (title, author, category) in enumerate(seed, 1)) for i in range(len(rows), 200): title = f"Blinkist Guide {i + 1:03d}" rows.append({"slug": slugify(title), "title": title, "author": "Blinkist Editors", "category": ["Career", "Wellbeing", "Leadership", "Science"][i % 4], "minutes": 10 + i % 16, "color": ["#e2ebf8", "#f5ded6", "#e1f0df", "#ede4f6"][i % 4], "description": f"A concise Blink of {title} with practical ideas you can apply today.", "narrator": "Blinkist Audio", "rating": 4.2, "ratings": 800 + i, "key_ideas": 5, "level": ("Beginner", "Intermediate", "Advanced")[i % 3], "language": "English", "schedule": "On demand"}) return rows BOOKS = books() BOOK_BY_SLUG = {str(book["slug"]): book for book in BOOKS} BOOK_BY_SLUG["the-ambition-penalty"].update({ "minutes": 20, "key_ideas": 5, "description": "How Corporate Culture Tells Women to Step Up—and Then Pushes Them Down", }) def key_ideas_for(book: dict[str, object]) -> list[str]: """Return the short, source-aligned idea map shown on a Blink detail page.""" if book["slug"] == "atomic-habits": return [ "Build identity-based habits", "Make the cue obvious", "Make the routine attractive", "Make the action easy", "Make the reward satisfying", "Use habit stacking to create a reliable cue", "Review and reset when a routine breaks", ] return [ f"Notice the central idea in {book['title']}", "Turn one insight into a small repeatable action", "Use a clear cue to make the action easier to remember", "Review the result and adjust the routine", "Return to the Blink when you need a quick refresher", ][: int(book.get("key_ideas", 5))] def order_for(request: Request, order_id: str | None = None) -> sqlite3.Row | None: if not owner(request): return None with db() as conn: if order_id: return conn.execute( "SELECT order_id,plan,amount_minor,currency,status,scenario,flow_id,attempt_id,created_at FROM blinkist_orders WHERE owner=? AND order_id=?", (owner(request), order_id), ).fetchone() return conn.execute( "SELECT order_id,plan,amount_minor,currency,status,scenario,flow_id,attempt_id,created_at FROM blinkist_orders WHERE owner=? ORDER BY created_at DESC LIMIT 1", (owner(request),), ).fetchone() def db() -> sqlite3.Connection: global _DB_SCHEMA_READY conn = sqlite3.connect(str(DB), timeout=30) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys=ON") conn.execute("PRAGMA busy_timeout=30000") if not _DB_SCHEMA_READY: with _DB_SCHEMA_LOCK: if not _DB_SCHEMA_READY: conn.executescript(""" CREATE TABLE IF NOT EXISTS blinkist_favorites (owner TEXT NOT NULL, slug TEXT NOT NULL, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), PRIMARY KEY(owner, slug)); CREATE TABLE IF NOT EXISTS blinkist_subscriptions (owner TEXT PRIMARY KEY, plan TEXT NOT NULL, status TEXT NOT NULL, payment_scenario TEXT NOT NULL, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))); CREATE TABLE IF NOT EXISTS blinkist_orders (order_id TEXT PRIMARY KEY, owner TEXT NOT NULL, plan TEXT NOT NULL, amount_minor INTEGER NOT NULL, currency TEXT NOT NULL, status TEXT NOT NULL, scenario TEXT NOT NULL, flow_id TEXT NOT NULL, attempt_id TEXT NOT NULL, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))); CREATE TABLE IF NOT EXISTS blinkist_progress (owner TEXT NOT NULL, slug TEXT NOT NULL, mode TEXT NOT NULL, position INTEGER NOT NULL DEFAULT 0, completed INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), PRIMARY KEY(owner, slug, mode)); CREATE TABLE IF NOT EXISTS blinkist_assessments (owner TEXT NOT NULL, slug TEXT NOT NULL, score INTEGER NOT NULL DEFAULT 0, completed INTEGER NOT NULL DEFAULT 0, answers TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), PRIMARY KEY(owner, slug)); CREATE TABLE IF NOT EXISTS blinkist_history (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, slug TEXT NOT NULL, action TEXT NOT NULL, mode TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))); CREATE TABLE IF NOT EXISTS blinkist_spaces (owner TEXT NOT NULL, space TEXT NOT NULL, slug TEXT NOT NULL, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), PRIMARY KEY(owner, space, slug)); CREATE TABLE IF NOT EXISTS blinkist_highlights (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, slug TEXT NOT NULL, note TEXT NOT NULL, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))); CREATE TABLE IF NOT EXISTS blinkist_masterclass_rsvps (owner TEXT NOT NULL, session_id TEXT NOT NULL, created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')), PRIMARY KEY(owner, session_id)); CREATE TABLE IF NOT EXISTS blinkist_preferences (owner TEXT PRIMARY KEY, language TEXT NOT NULL DEFAULT 'English', email_all INTEGER NOT NULL DEFAULT 1, daily_pick INTEGER NOT NULL DEFAULT 1, weekly_summary INTEGER NOT NULL DEFAULT 1, top_charts INTEGER NOT NULL DEFAULT 1, insights INTEGER NOT NULL DEFAULT 1, product_news INTEGER NOT NULL DEFAULT 1, surveys INTEGER NOT NULL DEFAULT 1, offers INTEGER NOT NULL DEFAULT 1); CREATE TABLE IF NOT EXISTS blinkist_connection_checks (owner TEXT PRIMARY KEY, report TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now'))); """) conn.commit() _DB_SCHEMA_READY = True return conn def current_session(request: Request) -> tuple[str, dict]: token = getattr(request.state, "session_token", None) or request.cookies.get(session_cookie_name(request)) return AUTH.ensure_session(token) def session_cookie_name(request: Request) -> str: return LOCAL_SESSION_COOKIE if is_loopback(request) and LOCAL_HTTP_COOKIE_OVERRIDE else SESSION_COOKIE def account(request: Request) -> dict | None: return current_session(request)[1].get("account") def owner(request: Request) -> str | None: item = account(request) return f"account:{item['account_id']}" if item else None def subscription_for(request: Request) -> sqlite3.Row | None: with db() as conn: return conn.execute("SELECT plan,status,payment_scenario FROM blinkist_subscriptions WHERE owner=?", (owner(request) or "",)).fetchone() EMAIL_PREFERENCES = [ ("daily_pick", "Daily Pick", "Daily", "Get the free title of the day via email"), ("weekly_summary", "The Summary", "Weekly", "Find out which free titles are coming up in the next week"), ("top_charts", "Top Charts", "Monthly", "Discover the most popular titles in the Blinkist app"), ("insights", "Your Blinkist", "", "Insights on how you use Blinkist, product news, and surveys to improve your Blinkist experience"), ("product_news", "Product News", "Occasionally", "Be the first to discover the latest product updates and new features"), ("surveys", "Surveys", "Occasionally", "Get involved in Blinkist's journey and help us improve the product for you"), ("offers", "Offers", "Occasionally", "Receive our latest special offers and discounts"), ] def preferences_for(request: Request) -> sqlite3.Row | None: if not owner(request): return None with db() as conn: row = conn.execute("SELECT * FROM blinkist_preferences WHERE owner=?", (owner(request),)).fetchone() if row is None: conn.execute("INSERT OR IGNORE INTO blinkist_preferences(owner) VALUES (?)", (owner(request),)) conn.commit() row = conn.execute("SELECT * FROM blinkist_preferences WHERE owner=?", (owner(request),)).fetchone() return row def settings_tabs(active: str) -> str: tabs = [("Account", "/settings"), ("Content", "/settings/content"), ("Email Preferences", "/settings/email_optins"), ("Connected Services", "/settings/external_services")] return "".format("".join(f"{label}" for label, href in tabs)) def record_history(request: Request, slug: str, action: str, mode: str = "") -> None: if not owner(request): return with db() as conn: conn.execute("INSERT INTO blinkist_history(owner,slug,action,mode) VALUES (?,?,?,?)", (owner(request), slug, action, mode)) conn.commit() def progress_for(request: Request, slug: str, mode: str) -> sqlite3.Row | None: if not owner(request): return None with db() as conn: return conn.execute("SELECT position,completed,updated_at FROM blinkist_progress WHERE owner=? AND slug=? AND mode=?", (owner(request), slug, mode)).fetchone() def save_progress(request: Request, slug: str, mode: str, position: int, completed: bool = False) -> None: if not owner(request): return with db() as conn: conn.execute("INSERT INTO blinkist_progress(owner,slug,mode,position,completed,updated_at) VALUES (?,?,?,?,?,strftime('%s','now')) ON CONFLICT(owner,slug,mode) DO UPDATE SET position=excluded.position,completed=excluded.completed,updated_at=excluded.updated_at", (owner(request), slug, mode, max(0, min(100, position)), int(completed))) conn.commit() def safe_next(value: str | None) -> str: candidate = (value or "").strip() decoded = unquote(candidate) parsed = urlsplit(decoded) if ( candidate.startswith("/") and decoded.startswith("/") and not candidate.startswith("//") and not decoded.startswith("//") and "\\" not in candidate and "\\" not in decoded and "\x00" not in decoded and not parsed.netloc and not parsed.scheme ): return candidate return "/en/app/for-you" 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 set_session_cookie(response, request: Request, token: str) -> None: secure = COOKIE_SECURE and not (LOCAL_HTTP_COOKIE_OVERRIDE and is_loopback(request)) response.set_cookie(session_cookie_name(request), token, httponly=True, samesite="lax", secure=secure, path="/") def shell(title: str, body: str, request: Request, *, active: str = "For You") -> str: path = request.url.path if active == "For You": for prefix, label in (("/settings", "Settings"), ("/en/nc/settings", "Settings"), ("/app/progress", "Settings"), ("/app/history", "Settings"), ("/help", "Help & Support"), ("/app/check", "Help & Support"), ("/app/daily", "Today's Free Blink"), ("/app/explore", "Explore"), ("/app/library", "My Library"), ("/app/spaces", "Spaces"), ("/app/highlights", "Highlights"), ("/app/infographics", "Infographics"), ("/app/masterclasses", "Masterclasses")): if path.startswith(prefix): active = label break nav = [("For You", "/en/app/for-you", "⌂"), ("Today's Free Blink", "/app/daily", "♧"), ("Explore", "/app/explore", "⌕"), ("My Library", "/app/library", "♧"), ("Spaces", "/app/spaces", "▦"), ("Highlights", "/app/highlights", "◇"), ("Infographics", "/app/infographics", "▣"), ("Masterclasses", "/app/masterclasses", "◉")] links = "".join(f"{esc(label)}" for label, href, icon in nav) settings_class = "active" if active == "Settings" else "" help_class = "active" if active == "Help & Support" else "" user = account(request) user_html = "" if user else "Log inGet started" side_auth = "
" if user else "" account_slot = f"
{user_html}
" if user_html else "" return f"{esc(title)}
Blinkist{account_slot}
{body}
" def card(book: dict[str, object], *, favorite: bool = False) -> str: return f"
{esc(str(book['title']).split()[0])}
{esc(book['title'])}
{esc(book['author'])}
{esc(book['category'])}{esc(book['minutes'])} min{'♥' if favorite else ''}
" def page_for_you(request: Request, *, active: str = "For You") -> HTMLResponse: with db() as conn: favs = {row["slug"] for row in conn.execute("SELECT slug FROM blinkist_favorites WHERE owner=?", (owner(request) or "",))} content = "".join(card(book, favorite=str(book["slug"]) in favs) for book in BOOKS[:12]) masterclass_previews = "".join(f"
{esc(session['title'].split(':')[0])}{esc(':'.join(session['title'].split(':')[1:]).strip())}
{esc(session['date'])}

{esc(session['title'])}

{esc(session['host'])}

{esc(session['description'])}

Masterclass · Live · {esc(session['duration'])}
" for session in MASTERCLASSES) body = f"

Masterclasses

Interactive, expert-led live sessions

See all →

Selected just for you

Cliffs, Fog, Fire and the
Self-Knowledge Imperative
What to Make
of a Life

What to Make of a Life

Jim Collins

▶  19 min

Recommended for you

Browse ideas selected for your interests

See all →
{content}
" return HTMLResponse(shell("For You | Blinkist", body, request, active=active)) @APP.middleware("http") async def session_middleware(request: Request, call_next): cookie_name = session_cookie_name(request) token, _ = AUTH.ensure_session(request.cookies.get(cookie_name)) request.state.session_token = token response = await call_next(request) supplied = request.cookies.get(cookie_name) if token != supplied and "set-cookie" not in response.headers: secure = COOKIE_SECURE and not (LOCAL_HTTP_COOKIE_OVERRIDE and is_loopback(request)) response.set_cookie(cookie_name, token, httponly=True, samesite="lax", secure=secure, path="/") response.headers["Content-Security-Policy"] = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; form-action 'self'" response.headers["X-Content-Type-Options"] = "nosniff" return response @APP.get("/", response_class=HTMLResponse) async def home(request: Request): return page_for_you(request) @APP.get("/en/app/for-you", response_class=HTMLResponse) async def for_you(request: Request): return page_for_you(request) @APP.get("/app/explore", response_class=HTMLResponse) async def explore(request: Request, category: str | None = None): query = request.query_params level = query.get("level", "") language = query.get("language", "") schedule = query.get("schedule", "") max_minutes = int(query["max_minutes"]) if query.get("max_minutes", "").isdigit() else 0 min_rating = float(query["min_rating"]) if re.fullmatch(r"[0-9]+(?:\.[0-9])?", query.get("min_rating", "")) else 0 selected = [book for book in BOOKS if ( (not category or str(book["category"]).casefold() == category.casefold()) and (not level or str(book.get("level", "")).casefold() == level.casefold()) and (not language or str(book.get("language", "")).casefold() == language.casefold()) and (not schedule or str(book.get("schedule", "")).casefold() == schedule.casefold()) and (not max_minutes or int(book["minutes"]) <= max_minutes) and (not min_rating or float(book["rating"]) >= min_rating) )] cards = "".join(card(book) for book in selected) params = "&".join(f"{quote_plus(str(k))}={quote_plus(str(v))}" for k, v in query.multi_items() if k != "category") def filter_link(label: str) -> str: extra = f"&{params}" if params else "" selected_class = "selected" if category and category.casefold() == label.casefold() else "" return f"{esc(label)}" controls = "".join(filter_link(x) for x in ["Productivity", "Mind", "Career", "Wellbeing", "Leadership"]) def options(values: tuple[object, ...], selected: object) -> str: return "".join(f"" for value, label in ((value, str(value)) for value in values)) level_options = options(("Beginner", "Intermediate", "Advanced"), level) duration_options = options((15, 25, 35), max_minutes) rating_options = options((4.0, 4.5), min_rating) level_options = "" + level_options duration_options = "" + duration_options.replace("", " min") rating_options = "" + rating_options.replace("", "+ stars") language_options = f"" schedule_options = f"" results = f'
{cards}
' if cards else '

No titles match these filters

Try a broader topic, duration, or rating.

Clear filters
' body = f"
EXPLORE

Find your next great idea

Browse 200+ concise book summaries, audio guides, and collections.

{controls}

{esc(category or 'All titles')}

{len(selected)} titles
{results}
" return HTMLResponse(shell("Explore | Blinkist", body, request, active="Explore")) @APP.get("/en/app/explore", response_class=HTMLResponse) async def explore_localized(request: Request, category: str | None = None): return await explore(request, category) @APP.get("/search", response_class=HTMLResponse) async def search(request: Request, q: str = ""): query = q.strip().casefold() found = [book for book in BOOKS if query in str(book["title"]).casefold() or query in str(book["author"]).casefold()] if query else [] body = f"
SEARCH

Search results

{len(found)} results for {esc(q or 'all titles')}

{('
'+''.join(card(book) for book in found)+'
') if found else '
⌕

No results yet

Try a different title, author, or collection.

Explore all titles
'}
" return HTMLResponse(shell("Search | Blinkist", body, request, active="Explore")) @APP.get("/app/books/{slug}", response_class=HTMLResponse) async def detail(request: Request, slug: str): slug = "atomic-habits" if slug == "atomic-habits-en" else slug book = BOOK_BY_SLUG.get(slug) if book is None: return HTMLResponse(shell("Not found | Blinkist", "

We couldn't find that Blink

Back to Explore
", request), status_code=404) is_fav = False if owner(request): with db() as conn: is_fav = conn.execute("SELECT 1 FROM blinkist_favorites WHERE owner=? AND slug=?", (owner(request), slug)).fetchone() is not None fav_label = "In My Library" if is_fav else "Add to My Library" ratings = f"{int(book['ratings']):,}" premium = subscription_for(request) premium_active = bool(premium and premium["status"] == "active") action_html = f"◉ ListenRead" if premium_active else f"▣ Unlock with Premium" similar = [BOOK_BY_SLUG[s] for s in ("thinking-fast-and-slow", "the-7-habits-of-highly-effective-people", "deep-work", "essentialism") if s in BOOK_BY_SLUG and s != slug] similar_html = "".join(card(item) for item in similar) is_atomic = slug == "atomic-habits" topics = "⌗ Personal Development♧ Psychology" if is_atomic else f"⌗ {esc(book['category'])}" author_copy = f"{esc(book['author'])} is the author of {esc(book['title'])}, sharing practical ideas and useful frameworks for everyday learning." art_title = "
".join(esc(str(book['title']).split()[:2])) ideas_html = "".join(f"
  • {index}

    {esc(idea)}

  • " for index, idea in enumerate(key_ideas_for(book), 1)) content_map = f"
    {esc(book['key_ideas'])} key ideasShort, practical takeaways
    {esc(book['minutes'])} minutesText and audio formats
    {esc(book['level'])}{esc(book['schedule'])}
    " body = f"""
    {esc(book['category'])}

    {esc(book['title'])}

    {esc(book['author'])}

    Narrated by {esc(book['narrator'])}

    {esc(book['description'])}

    ☆ {esc(book['rating'])} ({esc(ratings)} ratings)◷ {esc(book['minutes'])} mins♧ {esc(book['key_ideas'])} Key ideas♬ Audio & text
    {action_html}
    {art_title}Practical ideas,
    remarkable results

    What's it about?

    {topics}

    {esc(book['title'])} distills practical ideas, research, and real-world examples into a focused Blink you can apply today.

    {content_map}

    Key ideas

    The short takeaways in this Blink

      {ideas_html}

    About the author

    {author_copy}

    Similar Blinks

    Related Blinks you might enjoy

    {similar_html}

    Trending

    What's popular right now

    {''.join(card(item) for item in BOOKS[4:8])}
    """ return HTMLResponse(shell(f"{book['title']} | Blinkist", body, request, active="Explore")) @APP.post("/app/books/{slug}/favorite") async def favorite(request: Request, slug: str): if not owner(request): return RedirectResponse(f"/login?next={quote_plus('/app/books/' + slug)}", status_code=303) if slug not in BOOK_BY_SLUG: return RedirectResponse("/app/explore", status_code=303) with db() as conn: existing = conn.execute("SELECT 1 FROM blinkist_favorites WHERE owner=? AND slug=?", (owner(request), slug)).fetchone() if existing: conn.execute("DELETE FROM blinkist_favorites WHERE owner=? AND slug=?", (owner(request), slug)) else: conn.execute("INSERT INTO blinkist_favorites(owner,slug) VALUES (?,?)", (owner(request), slug)) conn.commit() return RedirectResponse(f"/app/books/{quote_plus(slug)}", status_code=303) def book_or_404(slug: str) -> dict[str, object] | None: return BOOK_BY_SLUG.get("atomic-habits" if slug == "atomic-habits-en" else slug) def player_body(request: Request, book: dict[str, object], mode: str, *, preview: bool = False) -> str: slug = str(book["slug"]) row = progress_for(request, slug, mode) position = int(row["position"]) if row else 0 label = "Preview" if preview else ("Listen" if mode == "listen" else "Read") intro = "A short local preview" if preview else ("Audio summary" if mode == "listen" else "Key ideas in text") action = f"
    " return f"
    ← Back to {esc(book['title'])}
    {esc(str(book['title']).split()[0])}
    {esc(label)}

    {esc(book['title'])}

    {esc(intro)} · {esc(book['minutes'])} minutes

    Ready to start

    Offline playback is simulated locally; no source request is made.

    00:00 / {int(book['minutes']):02d}:00

    {'First ideas' if preview else 'Build better systems'}

    Small changes compound into remarkable results. Make the cue obvious, the routine attractive, and the reward satisfying.

    Use this local player to exercise the same route, state, and progress transitions as the captured member experience.

    {action}
    " @APP.get("/app/books/{slug}/preview", response_class=HTMLResponse) async def preview(request: Request, slug: str): book = book_or_404(slug) if book is None: return HTMLResponse("Not found", status_code=404) record_history(request, str(book["slug"]), "preview", "preview") return HTMLResponse(shell(f"Preview {book['title']} | Blinkist", player_body(request, book, "preview", preview=True), request, active="Explore")) @APP.get("/app/books/{slug}/read", response_class=HTMLResponse) async def read_book(request: Request, slug: str, mode: str = "text"): book = book_or_404(slug) if book is None: return HTMLResponse("Not found", status_code=404) if mode not in {"text", "listen"}: mode = "text" if not owner(request): return RedirectResponse(f"/login?next={quote_plus('/app/books/' + str(book['slug']) + '/read?mode=' + mode)}", status_code=303) subscription = subscription_for(request) if not subscription or subscription["status"] != "active": return RedirectResponse(f"/subscribe?next={quote_plus('/app/books/' + str(book['slug']) + '/read?mode=' + mode)}", status_code=303) record_history(request, str(book["slug"]), "open", mode) return HTMLResponse(shell(f"{mode.title()} {book['title']} | Blinkist", player_body(request, book, mode), request, active="Explore")) @APP.post("/app/books/{slug}/progress") async def update_progress(request: Request, slug: str, mode: str = Form("text"), position: int = Form(0), completed: int = Form(0)): book = book_or_404(slug) if book is None: return RedirectResponse("/app/explore", status_code=303) if mode not in {"text", "listen", "preview"}: mode = "text" save_progress(request, str(book["slug"]), mode, position, bool(completed or position >= 100)) record_history(request, str(book["slug"]), "complete" if completed or position >= 100 else "progress", mode) destination = "/app/books/" + quote_plus(str(book["slug"])) + ("/preview" if mode == "preview" else "/read?mode=" + mode) return RedirectResponse(destination, status_code=303) @APP.get("/app/books/{slug}/listen", response_class=HTMLResponse) async def listen_book(request: Request, slug: str): return await read_book(request, slug, mode="listen") @APP.get("/app/books/{slug}/assessment", response_class=HTMLResponse) async def assessment(request: Request, slug: str): book = book_or_404(slug) if book is None: return HTMLResponse("Not found", status_code=404) if not owner(request): return RedirectResponse(f"/login?next={quote_plus('/app/books/' + str(book['slug']) + '/assessment')}", status_code=303) with db() as conn: row = conn.execute("SELECT score,completed FROM blinkist_assessments WHERE owner=? AND slug=?", (owner(request), str(book["slug"]))).fetchone() result = f"
    {'Assessment complete' if row and row['completed'] else 'Assessment ready'}{row['score'] if row else 0}/3 correct
    " first = f"What is the central idea in {esc(book['title'])}?" body = f"
    ← Back to {esc(book['title'])}
    CHECK YOUR UNDERSTANDING

    {esc(book['title'])} assessment

    Answer three quick questions based on this Blink.

    {result}
    1. {first}
    2. What makes a useful idea easier to use?
    3. How should you continue?
    " return HTMLResponse(shell("Assessment | Blinkist", body, request, active="Explore")) @APP.post("/app/books/{slug}/assessment") async def submit_assessment(request: Request, slug: str, q1: str = Form(""), q2: str = Form(""), q3: str = Form("")): book = book_or_404(slug) if book is None or not owner(request): return RedirectResponse("/login", status_code=303) answers = {"q1": q1, "q2": q2, "q3": q3} score = sum([q1 == "obvious", q2 == "small", q3 == "reward"]) with db() as conn: conn.execute("INSERT INTO blinkist_assessments(owner,slug,score,completed,answers,updated_at) VALUES (?,?,?,?,?,strftime('%s','now')) ON CONFLICT(owner,slug) DO UPDATE SET score=excluded.score,completed=excluded.completed,answers=excluded.answers,updated_at=excluded.updated_at", (owner(request), str(book["slug"]), score, 1, str(answers))) conn.commit() record_history(request, str(book["slug"]), "assessment", "text") return RedirectResponse(f"/app/books/{quote_plus(str(book['slug']))}/assessment", status_code=303) @APP.get("/app/library", response_class=HTMLResponse) async def library(request: Request): with db() as conn: slugs = [row["slug"] for row in conn.execute("SELECT slug FROM blinkist_favorites WHERE owner=? ORDER BY created_at DESC", (owner(request) or "",))] selected = [BOOK_BY_SLUG[slug] for slug in slugs if slug in BOOK_BY_SLUG] cards = "".join(card(book, favorite=True) for book in selected) body = f"
    MY LIBRARY

    Your saved Blinks

    Keep the ideas you want to come back to close at hand.

    {('
    '+cards+'
    ') if cards else '
    ♡

    Your library is waiting

    Save a Blink from Explore and it will appear here.

    Explore titles
    '}
    " return HTMLResponse(shell("My Library | Blinkist", body, request, active="My Library")) @APP.get("/en/app/library", response_class=HTMLResponse) async def library_localized(request: Request): return await library(request) @APP.get("/register", response_class=HTMLResponse) async def register_form(request: Request): body = "
    GET STARTED

    Create your Blinkist account

    Start building a reading habit with concise ideas.

    A verification code will be available in the local outbox for this offline clone.

    Already a member? Log in

    " return HTMLResponse(shell("Create account | Blinkist", body, request)) @APP.post("/register") async def register(request: Request, email: str = Form(...), display_name: str = Form(...), password: str = Form(...), terms: str = Form("")): token, _ = current_session(request) if terms != "on": return HTMLResponse(shell("Registration | Blinkist", "

    We couldn't create your account

    Please accept the Terms of Service and Privacy Policy.

    Try again
    ", request), status_code=422) try: result = AUTH.start_registration(token, email=email, display_name=display_name, password=password) except AuthError as exc: return HTMLResponse(shell("Registration | Blinkist", f"

    We couldn't create your account

    {esc(exc)}

    Try again
    ", request), status_code=422) return RedirectResponse(f"/verify?pending={quote_plus(result['pending_id'])}", status_code=303) @APP.get("/verify", response_class=HTMLResponse) async def verify_form(request: Request, pending: str = ""): body = f"
    CHECK YOUR INBOX

    Verify your email

    In the offline clone, verification messages are retained in the local outbox for testing.

    " return HTMLResponse(shell("Verify email | Blinkist", body, request)) @APP.post("/verify") async def verify(request: Request, pending: str = Form(...), code: str = Form(...)): token, _ = current_session(request) try: AUTH.verify_registration_code(token, code) result = AUTH.complete_registration(token) except AuthError as exc: return HTMLResponse(shell("Verify email | Blinkist", f"

    Verification failed

    {esc(exc)}

    Try again
    ", request), status_code=422) response = RedirectResponse("/en/app/for-you", status_code=303) set_session_cookie(response, request, result["session_token"]) return response @APP.get("/login", response_class=HTMLResponse) async def login_form(request: Request, next: str = ""): destination = safe_next(next) body = f"
    WELCOME BACK

    Log in to Blinkist

    Forgot password?

    New here? Create an account

    " return HTMLResponse(shell("Log in | Blinkist", body, request)) @APP.post("/login") async def login(request: Request, email: str = Form(...), password: str = Form(...), next: str = Form("")): token, _ = current_session(request) try: result = AUTH.sign_in(token, email=email, password=password) except AuthRejected: return HTMLResponse(shell("Log in | Blinkist", "

    Log in to Blinkist

    Those details don't match an active account.

    Try again
    ", request), status_code=401) response = RedirectResponse(safe_next(next), status_code=303) set_session_cookie(response, request, result["session_token"]) return response @APP.post("/logout") async def logout(request: Request): cookie_name = session_cookie_name(request) AUTH.sign_out(request.cookies.get(cookie_name)) response = RedirectResponse("/en/app/for-you", status_code=303) response.delete_cookie(cookie_name, path="/") return response @APP.get("/forgot-password", response_class=HTMLResponse) async def forgot_password_form(request: Request): body = "
    ACCOUNT RECOVERY

    Reset your password

    Enter your email and a local verification message will be available if an account matches.

    Back to log in

    " return HTMLResponse(shell("Reset password | Blinkist", body, request)) @APP.post("/forgot-password") async def forgot_password(request: Request, email: str = Form(...)): token, _ = current_session(request) try: AUTH.start_password_reset(token, email=email) except AuthError: pass return RedirectResponse("/reset-password", status_code=303) @APP.get("/reset-password", response_class=HTMLResponse) async def reset_password_form(request: Request): body = "
    ACCOUNT RECOVERY

    Choose a new password

    Use the six-digit code from the local recovery outbox.

    " return HTMLResponse(shell("Choose new password | Blinkist", body, request)) @APP.post("/reset-password") async def reset_password(request: Request, code: str = Form(...), new_password: str = Form(...)): token, _ = current_session(request) try: AUTH.verify_password_reset_code(token, code) new_token = AUTH.complete_password_reset(token, new_password=new_password) except AuthError as exc: return HTMLResponse(shell("Reset password | Blinkist", f"

    Recovery failed

    {esc(exc)}

    Try again
    ", request), status_code=422) response = RedirectResponse("/en/app/for-you", status_code=303) set_session_cookie(response, request, new_token) return response @APP.get("/subscribe", response_class=HTMLResponse) async def subscribe_form(request: Request, next: str = "", scenario: str = ""): destination = safe_next(next) current = subscription_for(request) current_label = "Active Premium annual plan" if current and current["status"] == "active" else "Premium annual" if scenario in {"sandbox-approved", "sandbox-declined", "sandbox-retry"}: labels = {"sandbox-approved": "Simulated approval", "sandbox-declined": "Simulated decline", "sandbox-retry": "Simulated retry"} review = f"
    Local sandbox review

    Scenario: {labels[scenario]}. No card details or external provider are used.

    " else: review = f"
    " body = f"
    BLINKIST PREMIUM

    Make learning a daily habit

    Unlock the full library with the Premium annual plan.

    {current_label}

    Unlimited access to Blinks, audio, and collections.

    $99.99 / year{review}

    No real payment or external request is made in this offline clone.

    " return HTMLResponse(shell("Premium | Blinkist", body, request)) @APP.get("/subscribe/review", response_class=HTMLResponse) async def subscribe_review(request: Request, next: str = ""): destination = safe_next(next) body = f"
    ORDER REVIEW

    Review your Premium annual plan

    Choose a deterministic local outcome to exercise the checkout states.

    Premium annual$99.99 / year · USD

    No real payment details are accepted or sent.

    " return HTMLResponse(shell("Review Premium | Blinkist", body, request)) @APP.post("/subscribe") async def subscribe(request: Request, scenario: str = Form("sandbox-approved"), next: str = Form("")): if not owner(request): return RedirectResponse("/login?next=" + quote_plus("/subscribe?next=" + safe_next(next)), status_code=303) existing = subscription_for(request) if existing and existing["status"] == "active": return RedirectResponse(safe_next(next), status_code=303) if scenario not in {"sandbox-approved", "sandbox-declined", "sandbox-retry"}: return JSONResponse({"error": "unknown local payment scenario"}, status_code=422) account_owner = owner(request) amount_minor = 9999 fingerprint = hashlib.sha256(f"{account_owner}:premium-annual:USD:{amount_minor}".encode()).hexdigest() status = {"sandbox-approved": "active", "sandbox-declined": "declined", "sandbox-retry": "retryable"}[scenario] created_at = int(time.time()) try: with BACKEND.lifecycle.connection(transaction=True) as conn: flow = BACKEND.payments.create_intent(owner=account_owner, amount_minor=amount_minor, currency="USD", fingerprint=fingerprint, idempotency_key="blinkist-premium-annual", connection=conn) attempt = BACKEND.payments.attempt(flow_id=flow["flow_id"], owner=account_owner, amount_minor=amount_minor, currency="USD", fingerprint=fingerprint, scenario_id=scenario, idempotency_key=f"blinkist-premium-annual-{scenario}", connection=conn) if attempt["status"] == "APPROVED": BACKEND.payments.consume_approval(conn, flow_id=flow["flow_id"], owner=account_owner, amount_minor=amount_minor, currency="USD", fingerprint=fingerprint) conn.execute("INSERT INTO blinkist_subscriptions(owner,plan,status,payment_scenario) VALUES (?,?,?,?) ON CONFLICT(owner) DO UPDATE SET plan=excluded.plan,status=excluded.status,payment_scenario=excluded.payment_scenario", (account_owner, "premium-annual", status, scenario)) order_id = "BLK-" + hashlib.sha256(f"{account_owner}:{attempt['attempt_id']}".encode()).hexdigest()[:10].upper() conn.execute( "INSERT INTO blinkist_orders(order_id,owner,plan,amount_minor,currency,status,scenario,flow_id,attempt_id,created_at) VALUES (?,?,?,?,?,?,?,?,?,?) ON CONFLICT(order_id) DO UPDATE SET status=excluded.status,scenario=excluded.scenario", (order_id, account_owner, "premium-annual", amount_minor, "USD", status, scenario, flow["flow_id"], attempt["attempt_id"], created_at), ) except (PaymentError, PaymentRejected, sqlite3.IntegrityError, sqlite3.OperationalError) as exc: return HTMLResponse(shell("Premium | Blinkist", f"

    Payment could not be completed

    {esc(exc)}

    Try again
    ", request), status_code=422) target = "/subscribe/success" if status == "active" else "/subscribe/result" return RedirectResponse(f"{target}?order_id={quote_plus(order_id)}&next={quote_plus(safe_next(next))}", status_code=303) def order_page(request: Request, *, order_id: str, next: str, success: bool) -> HTMLResponse: order = order_for(request, order_id) if order is None: body = "

    Order not found

    This local checkout result is no longer available for this account.

    Return to Premium
    " return HTMLResponse(shell("Order result | Blinkist", body, request), status_code=404) amount = f"${int(order['amount_minor']) / 100:.2f}" if success and order["status"] == "active": body = f"
    LOCAL SANDBOX
    ✓

    Your Premium annual plan is active

    The local checkout was approved. Your account can now open text and audio Blinks.

    Confirmation{esc(order['order_id'])}
    PlanPremium annual
    Total{amount} {esc(order['currency'])}
    StatusApproved in local sandbox

    No card details, provider request, real email, or live payment was used.

    Continue to your BlinkView payment history
    " else: label = {"declined": "Declined in local sandbox", "retryable": "Retryable in local sandbox"}.get(str(order['status']), str(order['status'])) body = f"
    LOCAL SANDBOX

    We couldn't activate Premium yet

    The selected local payment scenario was recorded without contacting a provider.

    Attempt{esc(order['order_id'])}
    PlanPremium annual
    Result{esc(label)}
    Choose another local outcomeBack to For You
    " return HTMLResponse(shell("Order result | Blinkist", body, request)) @APP.get("/subscribe/success", response_class=HTMLResponse) async def subscribe_success(request: Request, order_id: str = "", next: str = ""): return order_page(request, order_id=order_id, next=next, success=True) @APP.get("/subscribe/result", response_class=HTMLResponse) async def subscribe_result(request: Request, order_id: str = "", next: str = ""): return order_page(request, order_id=order_id, next=next, success=False) @APP.get("/api/local/outbox") async def local_outbox(request: Request, purpose: str = "registration"): if not is_loopback(request) or os.environ.get("WEBSITEBENCH_LOCAL_OUTBOX_DEBUG", "1") != "1": return JSONResponse({"error": "local outbox is loopback-only"}, status_code=404) token, _ = current_session(request) item = AUTH.local_mail_for_session(token, purpose=purpose) if item is None: return JSONResponse({"status": "empty", "purpose": purpose}) return {"status": item["status"], "purpose": purpose, "recipient": item["recipient"]} @APP.get("/app/progress", response_class=HTMLResponse) async def progress_page(request: Request): rows = [] if owner(request): with db() as conn: rows = conn.execute("SELECT slug,mode,position,completed,updated_at FROM blinkist_progress WHERE owner=? ORDER BY updated_at DESC", (owner(request),)).fetchall() entries = "".join(f"
    {esc(BOOK_BY_SLUG.get(str(row['slug']), {'title': row['slug']})['title'])}{esc(row['mode'].title())}
    {int(row['position'])}%{' · Complete' if row['completed'] else ''}
    " for row in rows) body = f"
    YOUR LEARNING

    Progress

    Pick up where you left off across reading and listening.

    {entries or '

    No progress yet

    Open a preview or start a Blink to see your progress here.

    Explore titles
    '}
    " return HTMLResponse(shell("Progress | Blinkist", body, request, active="For You")) @APP.get("/app/assessment") async def assessment_entry(request: Request): return RedirectResponse("/app/books/atomic-habits/assessment", status_code=307) @APP.get("/app/read") async def read_entry(request: Request): return RedirectResponse("/app/books/atomic-habits/read?mode=text", status_code=307) @APP.get("/app/listen") async def listen_entry(request: Request): return RedirectResponse("/app/books/atomic-habits/read?mode=listen", status_code=307) @APP.get("/app/history", response_class=HTMLResponse) async def history_page(request: Request): rows = [] if owner(request): with db() as conn: rows = conn.execute("SELECT id,slug,action,mode,created_at FROM blinkist_history WHERE owner=? ORDER BY created_at DESC,id DESC LIMIT 40", (owner(request),)).fetchall() entries = "".join(f"
  • {esc(BOOK_BY_SLUG.get(str(row['slug']), {'title': row['slug']})['title'])}{esc(row['action'].replace('_',' ').title())}{(' · ' + esc(row['mode'].title())) if row['mode'] else ''}
  • " for row in rows) body = f"
    ACTIVITY

    History & management

    Review previews, reading sessions, and assessment activity on this device.

    {('') if entries else '

    Your activity will appear here

    Start a Blink to build a local history.

    '}
    " return HTMLResponse(shell("History | Blinkist", body, request, active="For You")) @APP.post("/app/history/{history_id}/delete") async def delete_history(request: Request, history_id: int): if owner(request): with db() as conn: conn.execute("DELETE FROM blinkist_history WHERE id=? AND owner=?", (history_id, owner(request))) conn.commit() return RedirectResponse("/app/history", status_code=303) @APP.get("/settings", response_class=HTMLResponse) async def settings_page(request: Request): user = account(request) subscription = subscription_for(request) plan = "Premium annual · Active" if subscription and subscription["status"] == "active" else "Basic" identity = esc(user["display_name"]) + " · " + esc(user.get("email_normalized", "")) if user else "Not signed in" auth_action = "
    " if user else "Log in" email = esc(user.get("email_normalized", "")) if user else "Not signed in" body = f"
    ACCOUNT

    Settings

    {settings_tabs('Account')}

    Your Subscription plans

    {plan}

    {'Unlimited access to Blinks, audio, and collections.' if subscription and subscription['status'] == 'active' else "You're on the free plan, with access to 1 pre-selected book a day."}

    {'Manage plan' if subscription and subscription['status'] == 'active' else 'Upgrade now'}

    Profile

    {identity}

    Edit profile

    Login variants

    Email {email}

    Password ••••••••••

    Change Password

    Troubleshooting

    Audio or content not loading? Run a quick check of your connection, account, and audio server — you'll get a code our support team can look up.

    Run a connection check

    Privacy

    Change which cookies Blinkist may use. You can update your choice at any time.

    Want to share Blinkist with your team?

    Did you know we also offer company subscriptions? Click below, or ask your Learning & Development team to get in touch, to find out how you and your team can use Blinkist to level up — personally and professionally.

    Learn more

    Delete your account

    Please note that deleting your account will delete all your content, your library and your completion history. Deleting your account will not automatically end a purchased subscription.

    {auth_action}
    " return HTMLResponse(shell("Settings | Blinkist", body, request, active="For You")) @APP.get("/settings/profile", response_class=HTMLResponse) async def settings_profile(request: Request): user = account(request) if not user: return RedirectResponse("/login?next=/settings/profile", status_code=303) body = f"
    ACCOUNT

    Edit profile

    {settings_tabs('Account')}
    ← Back to Settings
    " return HTMLResponse(shell("Edit profile | Blinkist", body, request, active="For You")) @APP.post("/settings/profile") async def save_settings_profile(request: Request, display_name: str = Form(...)): user = account(request) clean_name = display_name.strip()[:80] if not user: return RedirectResponse("/login?next=/settings/profile", status_code=303) if len(clean_name) < 2: return HTMLResponse(shell("Edit profile | Blinkist", "

    Profile not saved

    Display name must be at least 2 characters.

    Try again
    ", request), status_code=422) with AUTH.connect() as conn: conn.execute("UPDATE local_auth_accounts SET display_name=? WHERE account_id=?", (clean_name, str(user["account_id"]))) conn.commit() return RedirectResponse("/settings", status_code=303) @APP.post("/account/delete") async def delete_account(request: Request, confirmation: str = Form("")): user = account(request) if not user: return RedirectResponse("/login", status_code=303) if confirmation != "DELETE": return HTMLResponse(shell("Settings | Blinkist", "

    Confirmation required

    Type DELETE exactly to remove this local account.

    Back to Settings
    ", request), status_code=422) account_id = str(user["account_id"]) account_owner = f"account:{account_id}" with AUTH.connect() as conn: conn.execute("PRAGMA foreign_keys=ON") conn.execute("BEGIN IMMEDIATE") try: for table in ("blinkist_favorites", "blinkist_subscriptions", "blinkist_progress", "blinkist_assessments", "blinkist_history", "blinkist_spaces", "blinkist_highlights", "blinkist_masterclass_rsvps", "blinkist_preferences", "blinkist_connection_checks"): conn.execute(f"DELETE FROM {table} WHERE owner=?", (account_owner,)) conn.execute("DELETE FROM local_auth_password_reset_flows WHERE account_id=?", (account_id,)) conn.execute("DELETE FROM local_auth_sessions WHERE account_id=?", (account_id,)) conn.execute("DELETE FROM local_auth_accounts WHERE account_id=?", (account_id,)) conn.commit() except BaseException: conn.rollback() raise response = RedirectResponse("/register", status_code=303) response.delete_cookie(session_cookie_name(request), path="/") return response @APP.get("/en/nc/settings/account", response_class=HTMLResponse) async def settings_account_alias(request: Request): return await settings_page(request) @APP.get("/settings/content", response_class=HTMLResponse) async def settings_content(request: Request): preferences = preferences_for(request) selected = preferences["language"] if preferences else "English" choices = "".join(f"" for language in ("English", "German", "Spanish")) body = f"
    ACCOUNT

    Settings

    {settings_tabs('Content')}

    Language

    We'll show you content in the language you prefer.

    {choices}
    Current language: {esc(selected)}
    " return HTMLResponse(shell("Content settings | Blinkist", body, request, active="For You")) @APP.post("/settings/content") async def save_settings_content(request: Request, language: str = Form("English")): if owner(request) and language in {"English", "German", "Spanish"}: with db() as conn: conn.execute("INSERT INTO blinkist_preferences(owner,language) VALUES (?,?) ON CONFLICT(owner) DO UPDATE SET language=excluded.language", (owner(request), language)) conn.commit() return RedirectResponse("/settings/content", status_code=303) @APP.get("/settings/email_optins", response_class=HTMLResponse) async def settings_email_optins(request: Request): preferences = preferences_for(request) values = preferences or {"email_all": 1, **{key: 1 for key, *_ in EMAIL_PREFERENCES}} def toggle(name: str, label: str) -> str: enabled = bool(values[name]) return f"
    {esc(label)}
    " rows = toggle("email_all", "Manage all emails") + "

    Turn all emails on or off. You'll still receive emails about your Blinkist account and subscription which we are legally obliged to send you.

    " groups = {"Your Library": EMAIL_PREFERENCES[:3], "Your Blinkist": EMAIL_PREFERENCES[3:]} for heading, entries in groups.items(): rows += f"

    {heading}

    " + "".join(f"
    {esc(label)}{f'{esc(cadence)}' if cadence else ''}

    {esc(description)}

    {toggle(key, label)}
    " for key, label, cadence, description in entries) body = f"
    ACCOUNT

    Settings

    {settings_tabs('Email Preferences')}

    Manage your email preferences

    {rows}

    You can activate push notifications on your mobile phone in the app settings.

    " return HTMLResponse(shell("Email preferences | Blinkist", body, request, active="For You")) @APP.post("/settings/email_optins") async def save_settings_email_optins(request: Request, preference: str = Form(...)): valid = {"email_all", *(key for key, *_ in EMAIL_PREFERENCES)} if owner(request) and preference in valid: with db() as conn: current = preferences_for(request) enabled = 0 if current and current[preference] else 1 conn.execute(f"UPDATE blinkist_preferences SET {preference}=? WHERE owner=?", (enabled, owner(request))) if preference == "email_all": conn.execute("UPDATE blinkist_preferences SET daily_pick=?,weekly_summary=?,top_charts=?,insights=?,product_news=?,surveys=?,offers=? WHERE owner=?", (enabled, enabled, enabled, enabled, enabled, enabled, enabled, owner(request))) conn.commit() return RedirectResponse("/settings/email_optins", status_code=303) @APP.get("/settings/external_services", response_class=HTMLResponse) async def settings_external_services(request: Request): body = "
    ACCOUNT

    Settings

    " + settings_tabs("Connected Services") + "

    Kindle connect

    Send blinks right to your Kindle and read them whenever you want.

    Upgrade now

    Kindle connection is available for Premium members in this offline clone.

    " return HTMLResponse(shell("Connected services | Blinkist", body, request, active="For You")) @APP.get("/settings/payment-history", response_class=HTMLResponse) async def settings_payment_history(request: Request): subscription = subscription_for(request) history = f"
    Premium annual{'Approved in local sandbox' if subscription and subscription['status'] == 'active' else 'No completed purchases'}
    " if subscription and subscription["status"] == "active" else "

    You have not purchased any products yet.

    Explore Premium
    " body = f"
    ACCOUNT

    Payment history

    {history}
    " return HTMLResponse(shell("Payment history | Blinkist", body, request, active="For You")) @APP.get("/en/nc/settings/invoices", response_class=HTMLResponse) async def invoices_page(request: Request): body = "
    ACCOUNT

    Invoices

    If you need an invoice for a local sandbox purchase, contact the local support fixture with your account email. No real invoice or payment provider is contacted.

    For subscriptions purchased in the app, invoices are provided by the relevant app store.

    Back to Settings
    " return HTMLResponse(shell("Invoices | Blinkist", body, request, active="For You")) @APP.get("/app/check", response_class=HTMLResponse) async def connection_check(request: Request, run: int = 0): checks = ["Blinkist website reachable", "Signed in to your account", "Audio server reachable", "Browser audio support", "Error reporting"] report = "" if run or owner(request): report = "All local checks passed" if owner(request): with db() as conn: conn.execute("INSERT INTO blinkist_connection_checks(owner,report,updated_at) VALUES (?,?,strftime('%s','now')) ON CONFLICT(owner) DO UPDATE SET report=excluded.report,updated_at=excluded.updated_at", (owner(request), report)) conn.commit() rows = "".join(f"
  • ✓{label}Passed
  • " for label in checks) body = f"
    TROUBLESHOOTING

    Connection check

    These checks help us find out why audio or content might not load on your network. We'll try to share the results with our support team automatically.

    {f'
    {esc(report)}
    ' if report else ''}
    Run againContact support
    " return HTMLResponse(shell("Connection check | Blinkist", body, request, active="For You")) @APP.get("/help", response_class=HTMLResponse) async def help_page(request: Request, topic: str = ""): focus = f"
    Help topic: {esc(topic)}
    " if topic else "" body = f"
    SUPPORT

    Help & Support

    Find quick answers for your account and offline learning space.

    {focus}
    How do I save a Blink?

    Open a title and select Add to My Library. Saved titles appear in My Library.

    How does Premium work here?

    Premium is simulated by the local sandbox. No payment provider or source site is contacted.

    Where did my reading progress go?

    Use Progress or History in Settings. Progress is isolated to this local account and SQLite runtime.

    Need to recover access?

    Start password recovery and use the local outbox code.

    Back to For You
    " return HTMLResponse(shell("Help & Support | Blinkist", body, request, active="For You")) MASTERCLASSES = [ {"id": "ai-unlocked-how-to-future-proof-yourself", "title": "AI Unlocked: How to Future-Proof Yourself", "host": "Sebastian Kamilli", "date": "Tue, 25 Aug & 1 more date", "description": "Find out what AI really means for your career and leave with a concrete plan to stay ahead.", "duration": "60 min", "color": "#e8ddff"}, {"id": "become-a-blinkist-power-user-live-guide", "title": "Become a Blinkist Power User: Live Guide", "host": "Chiara Chidini", "date": "Tue, 25 Aug & 3 more dates", "description": "Learn how to get the most out of Blinkist — from navigating the app to building a learning habit that actually sticks", "duration": "45 min", "color": "#d8f0e8"}, {"id": "thrive-without-the-overdrive-sustainable-success-strategies", "title": "Thrive Without the Overdrive: Sustainable Success Strategies", "host": "Katharina Loth", "date": "Fri, 04 Sep", "description": "Uncover your hidden energy drains and master the balance between doing less and achieving more.", "duration": "60 min", "color": "#f4e6bd"}, {"id": "work-smarter-not-harder-peak-productivity-tools", "title": "Work Smarter, Not Harder: Peak Productivity Tools", "host": "Sebastian Kamilli", "date": "Thu, 08 Oct & 1 more date", "description": "Reclaim your time with proven strategies used by the world's most productive people.", "duration": "60 min", "color": "#d9e6ff"}, {"id": "the-innovation-edge-problem-solving-made-simple", "title": "The Innovation Edge: Problem-Solving Made Simple", "host": "Nicole Lenzen", "date": "Wed, 11 Nov", "description": "Build an innovation mindset that makes generating great ideas feel like second nature.", "duration": "60 min", "color": "#f6dccd"}, {"id": "learn-like-a-pro-master-skills-faster", "title": "Learn Like a Pro: Master Skills Faster", "host": "Sebastian Kamilli", "date": "Wed, 18 Nov", "description": "Unlock the science of learning and pick up new skills faster than you thought possible.", "duration": "60 min", "color": "#e1f0df"}, {"id": "build-your-own-second-brain-from-info-to-action", "title": "Build Your Own Second Brain: From Info to Action", "host": "Sebastian Kamilli", "date": "Thu, 26 Nov", "description": "Build a personal system that turns information overload into your competitive advantage.", "duration": "60 min", "color": "#ede4f6"}, ] MASTERCLASS_ALIASES = { "ai-unlocked": "ai-unlocked-how-to-future-proof-yourself", "blinkist-power-user": "become-a-blinkist-power-user-live-guide", "thrive-without-the-overdrive": "thrive-without-the-overdrive-sustainable-success-strategies", "work-smarter-not-harder": "work-smarter-not-harder-peak-productivity-tools", "the-innovation-edge": "the-innovation-edge-problem-solving-made-simple", "learn-like-a-pro": "learn-like-a-pro-master-skills-faster", "build-your-own-second-brain": "build-your-own-second-brain-from-info-to-action", } def canonical_masterclass_id(session_id: str) -> str: return MASTERCLASS_ALIASES.get(session_id, session_id) def masterclass_card(session: dict[str, str]) -> str: return f"
    LIVE{esc(session['title'].split(':')[0])}
    {esc(session['date'])}

    {esc(session['title'])}

    {esc(session['host'])}

    {esc(session['description'])}

    Masterclass · Live · {esc(session['duration'])}
    " @APP.get("/app/daily", response_class=HTMLResponse) async def daily_page(request: Request): book = BOOK_BY_SLUG["the-ambition-penalty"] progress = progress_for(request, "the-ambition-penalty", "preview") percent = int(progress["position"]) if progress else 0 body = f"

    Today’s Free Blink

    Key ideas from a different title daily—free for 24h!

    Free for 22hrs 34min 51sec
    Better than a summary

    {esc(book['title'])}

    {esc(book['description'])}

    ◷  {esc(book['minutes'])} mins♧  {esc(book['key_ideas'])} key ideas

    Free—no sign up required

    What's it about?

    ◉  Career & Success♧  Society & Culture▣  Corporate Culture

    {esc(book['title'])} pulls back the curtain on why women’s drive to achieve more keeps getting punished rather than rewarded. It equips readers with the language and evidence to push back and shows what real change could look like.

    Browse popular titles →
    " return HTMLResponse(shell("Today's Free Blink | Blinkist", body, request, active="Today's Free Blink")) @APP.get("/app/spaces", response_class=HTMLResponse) async def spaces_page(request: Request, space: str = "My reading list"): space = (space.strip() or "My reading list")[:60] assigned = set() if owner(request): with db() as conn: assigned = {row["slug"] for row in conn.execute("SELECT slug FROM blinkist_spaces WHERE owner=? AND space=?", (owner(request), space))} choices = BOOKS[:10] rows = "".join(f"
    {esc(book['title'])}{esc(book['author'])}{('Saved' if str(book['slug']) in assigned else f'
    ')}
    " for book in choices) body = f"
    SPACES

    Organize ideas your way

    Keep related Blinks together so you can return to a theme when you need it.

    {esc(space)}{len(assigned)} saved locally
    {rows}
    " return HTMLResponse(shell("Spaces | Blinkist", body, request, active="Spaces")) @APP.post("/app/spaces/add") async def add_to_space(request: Request, slug: str = Form(...), space: str = Form("My reading list")): if not owner(request): return RedirectResponse("/login?next=/app/spaces", status_code=303) normalized_space = (space.strip() or "My reading list")[:60] if slug in BOOK_BY_SLUG: with db() as conn: conn.execute("INSERT OR IGNORE INTO blinkist_spaces(owner,space,slug) VALUES (?,?,?)", (owner(request), normalized_space, slug)) conn.commit() record_history(request, slug, "add_to_space", normalized_space) return RedirectResponse(f"/app/spaces?space={quote_plus(normalized_space)}", status_code=303) @APP.get("/app/highlights", response_class=HTMLResponse) async def highlights_page(request: Request): highlights = [] if owner(request): with db() as conn: highlights = conn.execute("SELECT id,slug,note,created_at FROM blinkist_highlights WHERE owner=? ORDER BY created_at DESC,id DESC", (owner(request),)).fetchall() entries = "".join(f"
    {esc(row['note'])}
    {esc(BOOK_BY_SLUG.get(str(row['slug']), {'title': row['slug']})['title'])}
    " for row in highlights) sample = "
    Small changes compound into remarkable results.
    Atomic Habits · Local starter highlight
    " if not entries else "" body = f"
    HIGHLIGHTS

    Keep the ideas that stick

    Save a short note while you read, then revisit it from one place.

    {entries or sample}
    " return HTMLResponse(shell("Highlights | Blinkist", body, request, active="Highlights")) @APP.post("/app/highlights") async def add_highlight(request: Request, slug: str = Form(...), note: str = Form(...)): if not owner(request): return RedirectResponse("/login?next=/app/highlights", status_code=303) if slug in BOOK_BY_SLUG and note.strip(): with db() as conn: conn.execute("INSERT INTO blinkist_highlights(owner,slug,note) VALUES (?,?,?)", (owner(request), slug, note.strip()[:280])) conn.commit() record_history(request, slug, "highlight", "text") return RedirectResponse("/app/highlights", status_code=303) @APP.post("/app/highlights/{highlight_id}/delete") async def delete_highlight(request: Request, highlight_id: int): if owner(request): with db() as conn: conn.execute("DELETE FROM blinkist_highlights WHERE id=? AND owner=?", (highlight_id, owner(request))) conn.commit() return RedirectResponse("/app/highlights", status_code=303) @APP.get("/app/infographics", response_class=HTMLResponse) async def infographics_page(request: Request, category: str = ""): categories = ["All", "Productivity", "Psychology", "Leadership", "Career"] selected = [book for book in BOOKS[:16] if not category or category.casefold() == "all" or str(book["category"]).casefold() == category.casefold()] filters = "".join(f"{esc(item)}" for item in categories) cards = "".join(f"
    INFOGRAPHIC{esc(book['title'])}{esc(book['key_ideas'])} ideas · {esc(book['minutes'])} min

    {esc(book['title'])}

    {esc(book['category'])} · Visual summary

    " for book in selected) body = f"
    INFOGRAPHICS

    See the big ideas at a glance

    Visual summaries turn a Blink into a quick reference you can scan and share.

    {filters}
    {cards}
    " return HTMLResponse(shell("Infographics | Blinkist", body, request, active="Infographics")) @APP.get("/app/infographics/{slug}", response_class=HTMLResponse) async def infographic_detail(request: Request, slug: str): book = book_or_404(slug) if book is None: return HTMLResponse("Not found", status_code=404) steps = ["Make the cue obvious", "Make the routine attractive", "Make the reward satisfying", "Repeat until it becomes automatic"] items = "".join(f"
  • {index}{esc(step)}

    Apply this idea to {esc(book['title'])} in a small, repeatable way.

  • " for index, step in enumerate(steps, 1)) body = f"
    ← Infographics
    VISUAL SUMMARY

    {esc(book['title'])}

    {esc(book['description'])}

      {items}
    Open full Blink
    " return HTMLResponse(shell(f"Infographic: {book['title']} | Blinkist", body, request, active="Infographics")) @APP.get("/app/masterclasses", response_class=HTMLResponse) async def masterclasses_page(request: Request): sessions = "".join(masterclass_card(session) for session in MASTERCLASSES) body = f"
    MASTERCLASSES

    Masterclasses: turn insight into action, live

    60-minute interactive live sessions, led by experts, designed to provide practical frameworks.

    {sessions}
    " return HTMLResponse(shell("Masterclasses | Blinkist", body, request, active="Masterclasses")) @APP.get("/app/masterclasses/{session_id}", response_class=HTMLResponse) async def masterclass_detail(request: Request, session_id: str, registered: int = 0): canonical_id = canonical_masterclass_id(session_id) session = next((item for item in MASTERCLASSES if item["id"] == canonical_id), None) if session is None: return HTMLResponse("Not found", status_code=404) joined = False if owner(request): with db() as conn: joined = conn.execute("SELECT 1 FROM blinkist_masterclass_rsvps WHERE owner=? AND session_id=?", (owner(request), canonical_id)).fetchone() is not None message = "You're registered for this local session." if joined else "Reserve a place in this local session to keep it on your learning calendar." body = f"
    ← Masterclasses
    LIVE MASTERCLASS

    {esc(session['title'])}

    {esc(session['date'])} · {esc(session['duration'])}

    {esc(session['host'])}

    {esc(session['description'])}

    {esc(message)}
    " return HTMLResponse(shell(f"{session['title']} | Blinkist", body, request, active="Masterclasses")) @APP.post("/app/masterclasses/{session_id}/register") async def register_masterclass(request: Request, session_id: str): if not owner(request): return RedirectResponse(f"/login?next={quote_plus('/app/masterclasses/' + session_id)}", status_code=303) canonical_id = canonical_masterclass_id(session_id) if any(item["id"] == canonical_id for item in MASTERCLASSES): with db() as conn: conn.execute("INSERT OR IGNORE INTO blinkist_masterclass_rsvps(owner,session_id) VALUES (?,?)", (owner(request), canonical_id)) conn.commit() return RedirectResponse(f"/app/masterclasses/{quote_plus(canonical_id)}?registered=1", status_code=303) @APP.get("/app/{section}", response_class=HTMLResponse) async def auxiliary_section(request: Request, section: str): if section == "settings": return await settings_page(request) if section == "help": return await help_page(request) if section == "progress": return await progress_page(request) if section == "history": return await history_page(request) if section == "daily": return await daily_page(request) if section == "spaces": return await spaces_page(request) if section == "highlights": return await highlights_page(request) if section == "infographics": return await infographics_page(request) if section == "masterclasses": return await masterclasses_page(request) labels = {"daily": "Today's Free Blink", "spaces": "Spaces", "highlights": "Highlights", "infographics": "Infographics", "masterclasses": "Masterclasses", "settings": "Settings", "help": "Help & Support"} label = labels.get(section) if label is None: return HTMLResponse("Not found", status_code=404) return HTMLResponse("Not found", status_code=404) @APP.get("/{section}", response_class=HTMLResponse) async def root_auxiliary_section(request: Request, section: str): if section not in {"settings", "help"}: return HTMLResponse("Not found", status_code=404) return await auxiliary_section(request, section) @APP.get("/api/status") async def status(request: Request): with db() as conn: subscription = conn.execute("SELECT plan,status,payment_scenario FROM blinkist_subscriptions WHERE owner=?", (owner(request) or "",)).fetchone() count = conn.execute("SELECT COUNT(*) AS n FROM blinkist_favorites WHERE owner=?", (owner(request) or "",)).fetchone()["n"] latest_order = order_for(request) return {"site_id": SITE_ID, "authenticated": account(request) is not None, "favorite_count": count, "subscription": dict(subscription) if subscription else None, "latest_order": dict(latest_order) if latest_order else None, "catalog_count": len(BOOKS)} if __name__ == "__main__": import uvicorn uvicorn.run( APP, host=os.environ.get("HOST", "127.0.0.1"), port=int(os.environ.get("PORT", "8000")), log_level=os.environ.get("LOG_LEVEL", "warning"), )