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"{icon}{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 = "
{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"
", 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"
{result}"
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.
"
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.
Review previews, reading sessions, and assessment activity on this device.
{('
'+entries+'
') 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."}
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.
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", "
"
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.
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"
◉ 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"
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