AgPerry's picture
Add WebsiteBench card, manifest, and the medium task
bc7aa4f verified
Raw History Blame
94.5 kB
"""Stateful, network-closed Medium offline clone. Public reading and discovery use a deliberately small synthetic corpus. All authoring, publication, account, and community mutations are clone-local and owned by the site-bound WebsiteBench SQLite runtime. """ from __future__ import annotations import io import json import sqlite3 import zipfile from pathlib import Path from typing import Any, Mapping from urllib.parse import quote_plus, urlencode from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response, StreamingResponse from fastapi.staticfiles import StaticFiles import domain import render import site_data from backend import site_model from backend.site_backend_integration import open_site_services from websitebench.local_clone_auth import AuthError from websitebench.site_backend import MailError SITE_ID = "medium" DISPLAY_NAME = "Medium" BACKEND, AUTH = open_site_services() for seed_account in site_data.SEED_ACCOUNTS: AUTH.seed_account(**seed_account) COOKIE = dict(BACKEND.session_cookie) COOKIE_NAME = str(COOKIE.pop("name")) STATIC_DIR = Path(__file__).resolve().parent / "static" app = FastAPI(title=DISPLAY_NAME, docs_url=None, redoc_url=None, openapi_url=None) app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") def _session(request: Request) -> tuple[str, dict[str, Any]]: return AUTH.ensure_session(request.cookies.get(COOKIE_NAME)) def _account(session: Mapping[str, Any]) -> dict[str, Any] | None: account = session.get("account") return dict(account) if account else None def _subject(session: Mapping[str, Any]) -> str | None: account = _account(session) return str(account["subject_id"]) if account else None def _cookie(response: Response, token: str) -> Response: response.set_cookie(COOKIE_NAME, token, **COOKIE) return response def _html(token: str, markup: str, status: int = 200) -> HTMLResponse: return _cookie(HTMLResponse(markup, status_code=status), token) def _json(token: str, payload: Any, status: int = 200) -> JSONResponse: return _cookie(JSONResponse(payload, status_code=status), token) def _to(token: str, target: str) -> RedirectResponse: return _cookie(RedirectResponse(render.safe_next(target), status_code=303), token) def _signin(token: str, request: Request) -> RedirectResponse: path = request.url.path + (f"?{request.url.query}" if request.url.query else "") return _to(token, "/m/signin?" + urlencode({"next": path})) def _error_json(token: str, exc: Exception) -> JSONResponse: if isinstance(exc, domain.ValidationFailure): return _json(token, {"ok": False, "error": str(exc), "errors": exc.errors}, 400) if isinstance(exc, domain.PermissionDenied): return _json(token, {"ok": False, "error": str(exc)}, 403) if isinstance(exc, domain.NotFound): return _json(token, {"ok": False, "error": str(exc)}, 404) if isinstance(exc, domain.Conflict): return _json(token, {"ok": False, "error": str(exc)}, 409) return _json(token, {"ok": False, "error": "The local action could not be completed."}, 500) def _owner_or_error(token: str, session: Mapping[str, Any]) -> tuple[str | None, JSONResponse | None]: subject = _subject(session) if not subject: return None, _json(token, {"ok": False, "error": "Sign in to continue."}, 401) return subject, None async def _payload(request: Request) -> dict[str, Any]: """Read a mutation payload without letting a bad body abort the connection. Page scripts, harness probes, and agent journeys reach the same endpoints with JSON, form encodings, and empty bodies. Raising out of the handler would make the ASGI server tear the keep-alive socket down, so an unreadable body becomes an empty payload and the endpoint answers with its own validation error instead. """ raw = await request.body() if raw: try: value = json.loads(raw) except ValueError: value = None if isinstance(value, Mapping): return dict(value) if value is None: try: form = await request.form() except Exception: return {} return {key: value for key, value in form.items() if isinstance(value, str)} return {} @app.get("/health") @app.get("/healthz") def health() -> dict[str, str]: return {"status": "ok", "site_id": SITE_ID} @app.get("/__websitebench/health") def websitebench_health() -> dict[str, str]: return {"status": "ok"} @app.get("/", response_class=HTMLResponse) def home(request: Request) -> Response: token, session = _session(request) account = _account(session) with BACKEND.lifecycle.connection() as connection: stories = domain.list_public_stories(connection) if not account: body = '''<section class="landing-hero"><div class="hero-copy"><h1><span>Human</span><span>stories <span class="mobile-title-line">&amp; ideas</span></span></h1><p>A place to read, write, and deepen your understanding</p><button class="pill dark big landing-cta" id="start-reading" type="button" aria-haspopup="dialog" aria-controls="home-join-dialog" aria-expanded="false">Start reading</button></div><div class="hero-art" aria-label="Abstract green flower, geometric notes, stars, and a writing hand"><svg viewBox="0 0 500 752" role="img" aria-hidden="true"><g class="hero-flower"><ellipse cx="191" cy="149" rx="46" ry="64" transform="rotate(-12 191 149)"/><ellipse cx="255" cy="174" rx="48" ry="67" transform="rotate(45 255 174)"/><ellipse cx="244" cy="244" rx="48" ry="68" transform="rotate(100 244 244)"/><ellipse cx="166" cy="252" rx="51" ry="67" transform="rotate(148 166 252)"/><ellipse cx="132" cy="187" rx="47" ry="65" transform="rotate(210 132 187)"/><circle class="flower-cut" cx="195" cy="207" r="31"/><path class="flower-mark" d="m181 202 12-9 16 7-4 17-17 2z"/></g><g class="hero-diagram"><path d="M198 342 324 208l108 26M324 208l-5 196M198 342l120 62 114-170M324 208l74 73M318 404l80-123"/><path class="dashed" d="M198 342q91 82 234-108M232 419q124 58 229 39"/><circle cx="198" cy="342" r="3"/><circle cx="324" cy="208" r="3"/><circle cx="318" cy="404" r="3"/></g><path class="hero-green-block" d="M211 395H500V653H211z"/><path class="writing-hand" d="M254 518c28-5 51-27 72-44 8-7 20-2 13 8l-19 21 48-30c10-6 17 5 9 13l-34 29 61-24c11-4 16 9 6 15l-58 33 70-13c12-2 15 12 4 17l-70 30c-24 11-49 9-72-1l-28-13-22-18z"/><path class="pen-line" d="m234 542 83-69 9 11-72 81"/><g class="hero-stars"><path d="m190 483 5 12 12 5-12 5-5 12-5-12-12-5 12-5z"/><path d="m157 459 3 7 7 3-7 3-3 7-3-7-7-3 7-3z"/><path d="m388 443 5 14 14 5-14 5-5 14-5-14-14-5 14-5z"/><path d="m412 555 4 11 11 4-11 4-4 11-4-11-11-4 11-4z"/></g></svg></div></section>''' + render.join_modal() else: cards = "".join(render.story_card(story) for story in stories) promo_arrow = '''<svg class="promo-arrow" width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true"><path d="M4.5 13.5 13.5 4.5M6.1875 4.5H13.5V11.8125"/></svg>''' body = f'''<section class="feed-shell"><div class="welcome-offer"><span>Welcome Offer</span><b>Access to everything. Now 30% off.</b><a href="/plans">Upgrade now</a></div><div class="feed"><nav class="feed-tabs"><a class="active" href="/">For you</a><a href="/search?q=Featured">Featured</a></nav>{cards}</div><aside class="feed-aside"><section class="writer-promo" id="writer-promo"><div class="writer-promo-art"><img src="/static/assets/writer-starter-promo.png" width="303" height="140" alt=""><button type="button" class="writer-promo-close" id="writer-promo-close" aria-label="close"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 5 19 19M19 5 5 19"/></svg></button></div><div class="writer-promo-copy"><h2>Write, grow, and reach readers on Medium</h2><div class="writer-promo-links"><button type="button" id="writer-kit-open" aria-haspopup="dialog" aria-controls="writer-kit-dialog"><span>Get your ten-step writing starter kit</span>{promo_arrow}</button><a href="/help#writing-webinar"><span>Join our Medium Writing 101 Webinar</span>{promo_arrow}</a><a href="/help#writing-tips"><span>Read Medium tips &amp; tricks</span>{promo_arrow}</a><a href="/new-story"><span>Or just start writing!</span>{promo_arrow}</a></div></div></section><section class="staff-picks"><h2>Staff Picks</h2><p><strong>Quiet tools for deeper work</strong><br><span>6 min read</span></p><p><strong>Cities built for curiosity</strong><br><span>4 min read</span></p><h2>Recommended topics</h2><div class="topics"><a class="topic" href="/search?q=Technology">Technology</a><a class="topic" href="/search?q=Writing">Writing</a><a class="topic" href="/search?q=Design">Design</a></div><a href="/search">See more topics</a></section><dialog class="writer-kit-dialog" id="writer-kit-dialog" aria-labelledby="writer-kit-title"><button type="button" id="writer-kit-close" aria-label="Close">×</button><h2 id="writer-kit-title">Your ten-step writing starter kit</h2><p>Choose a clear idea, write for one reader, and begin with the smallest useful draft.</p><a class="pill dark" href="/new-story">Start writing</a></dialog></aside></section>''' return _html(token, render.layout("Medium", body, account=account, page_class="home-page account-home" if account else "home-page")) def _public_information_page( request: Request, *, title: str, eyebrow: str, introduction: str, sections: tuple[tuple[str, str], ...], actions: tuple[tuple[str, str], ...] = (), ) -> Response: """Render a distinct public-information destination without remote dependencies.""" token, session = _session(request) rows = "".join( f'<section>{f"<h2>{render.e(heading)}</h2>" if heading else ""}<p>{render.e(copy)}</p></section>' for heading, copy in sections ) links = "".join( f'<a class="pill {"dark" if index == 0 else ""}" href="{render.e(href)}">{render.e(label)}</a>' for index, (label, href) in enumerate(actions) ) body = f'''<article class="public-information-page"><p class="eyebrow">{render.e(eyebrow)}</p><h1>{render.e(title)}</h1>{f'<p class="information-introduction">{render.e(introduction)}</p>' if introduction else ''}{f'<div class="information-actions">{links}</div>' if links else ''}{f'<div class="information-sections">{rows}</div>' if rows else ''}</article>''' return _html(token, render.layout(f"{title} – Medium", body, account=_account(session))) @app.get("/our-story", response_class=HTMLResponse) @app.get("/about", response_class=HTMLResponse) def our_story(request: Request) -> Response: token, session = _session(request) body = '''<article class="about-page"><span class="about-dot dot-one"></span><span class="about-dot dot-two"></span><span class="about-dot dot-three"></span><span class="about-dot dot-four"></span><span class="about-dot dot-five"></span><h2>Everyone has a story<br>to tell</h2><p class="about-introduction">Medium is a home for human stories and ideas. Here, anyone can share knowledge and wisdom with the world—without having to build a mailing list or a following first. The internet is noisy and chaotic; Medium is quiet yet full of insight. It’s simple, beautiful, collaborative, and helps you find the right readers for whatever you have to say.</p><p class="about-goal"><span>Ultimately, our goal is to deepen our collective</span><br><span>understanding of the world through the power of writing.</span></p><p>We believe that what you read and write matters. Words can divide or empower us, inspire or discourage us. In a world where the most sensational and surface-level stories often win, we’re building a system that rewards depth, nuance, and time well spent. A space for thoughtful conversation more than drive-by takes, and substance over packaging.</p><p>Over 100 million people connect and share their wisdom on Medium every month. They’re software developers, amateur novelists, product designers, CEOs, and anyone burning with a story they need to get out into the world. They write about what they’re working on, what’s keeping them up at night, what they’ve lived through, and what they’ve learned that the rest of us might want to know too.</p><p>Instead of selling ads or selling your data, we’re supported by a growing community of over a million <a href="/membership">Medium members</a> who believe in our mission. If you’re new here, <a href="/m/signin?operation=register&amp;redirect=https%3A%2F%2Fmedium.com%2F&amp;source=--------------------------landing_about------------------">start reading</a>. Dive deeper into whatever matters to you. Find a post that helps you learn something new, or reconsider something familiar—and then <a href="/new-story">write your story</a>.</p></article><nav class="about-actions"><a href="/m/signin?operation=register&amp;redirect=https%3A%2F%2Fmedium.com%2F&amp;source=--------------------------landing_about------------------">Start reading <span>→</span></a><a href="/new-story">Start writing <span>→</span></a><a href="/membership">Become a member <span>→</span></a></nav><footer class="about-footer"><a class="about-footer-wordmark" href="/">Medium</a><nav><a href="/about">About</a><a href="/medium-terms-of-service-9db0094a1e0f">Terms</a><a href="/medium-privacy-policy-f03bf92035c9">Privacy</a><a href="/hc/en-us">Help</a><a href="/about#teams">Teams</a><a href="mailto://pressinquiries@medium.com">Press</a></nav></footer>''' return _html(token, render.layout("About Medium", body, account=_account(session), page_class="about-surface")) @app.get("/search", response_class=HTMLResponse) def search(request: Request) -> Response: token, session = _session(request) query = str(request.query_params.get("q") or "").strip() with BACKEND.lifecycle.connection() as connection: stories = domain.list_public_stories(connection, query) if query and not stories: results = f'''<section class="empty-state"><h2>No stories found for “{render.e(query)}”</h2><p>Try a broader title or topic in this small offline collection.</p><a href="/search">Browse available stories</a><a href="/">Go to your homepage</a></section>''' elif query: results = "".join(render.story_card(story) for story in stories) else: results = '''<section class="search-suggestions"><h2>Explore topics</h2><a href="/search?q=Writing">Writing</a><a href="/search?q=Technology">Technology</a><a href="/search?q=Design">Design</a><a href="/search?q=Cities">Cities</a></section>''' body = f'''<section class="search-page"><form action="/search"><label><span>⌕</span><input name="q" aria-label="Search Medium" value="{render.e(query)}" placeholder="Search"></label><button class="pill dark">Search</button></form><h1>{'Search results for '+render.e(query) if query else 'Search Medium'}</h1>{results}</section>''' return _html(token, render.layout(f"Search{' – '+query if query else ''} – Medium", body, account=_account(session))) @app.get("/tag/{topic}", response_class=HTMLResponse) def tag(request: Request, topic: str) -> Response: return search(request) @app.get("/m/signin", response_class=HTMLResponse) def signin_page(request: Request) -> Response: token, session = _session(request) if session.get("authenticated"): return _to(token, render.safe_next(request.query_params.get("next"), "/")) signup_intent = request.query_params.get("operation") == "register" redirect = str(request.query_params.get("redirect") or "") write_intent = signup_intent and ( request.query_params.get("next") == "/new-story" or redirect.endswith("/new-story") ) email_step = request.query_params.get("step") == "email" email_step_href = ( "/m/signup?step=email&next=%2Fnew-story&intent=write" if write_intent else ("/m/signup?step=email" if signup_intent else "/m/signin?step=email") ) return _html( token, render.auth_page( signup=signup_intent, email_step=email_step, write_intent=write_intent, email_step_href=email_step_href, ), ) @app.get("/m/signup", response_class=HTMLResponse) def signup_page(request: Request) -> Response: token, session = _session(request) if session.get("authenticated"): return _to(token, "/onboarding") write_intent = request.query_params.get("intent") == "write" or request.query_params.get("next") == "/new-story" email_step_href = ( "/m/signup?step=email&next=%2Fnew-story&intent=write" if write_intent else "/m/signup?step=email" ) return _html( token, render.auth_page( signup=True, email_step=request.query_params.get("step") == "email", write_intent=write_intent, email_step_href=email_step_href, ), ) @app.get("/m/recovery", response_class=HTMLResponse) def recovery_page(request: Request) -> Response: """Local-only password recovery, backed by the site's auth outbox.""" token, session = _session(request) if session.get("authenticated"): return _to(token, "/me/settings") return _html(token, render.recovery_page()) @app.post("/api/auth/sign-in") async def api_sign_in(request: Request) -> Response: token, _ = _session(request) data = await _payload(request) try: result = AUTH.sign_in(token, email=str(data.get("email", "")), password=str(data.get("password", ""))) except AuthError: return _json(token, {"ok": False, "error": "The email or password you entered is incorrect."}, 401) return _json(str(result["session_token"]), {"ok": True, "account": result["account"]}) @app.post("/__websitebench/session") async def diagnostic_session(request: Request) -> Response: """Create only a seeded synthetic session for the local diagnostic driver.""" token, _ = _session(request) form = await request.form() try: result = AUTH.sign_in(token, email=str(form.get("email", "")), password=str(form.get("password", ""))) except AuthError: return _json(token, {"ok": False, "error": "credentials are invalid"}, 401) return _json(str(result["session_token"]), {"ok": True, "account": result["account"]}) @app.post("/api/auth/sign-out") def api_sign_out(request: Request) -> Response: token, _ = _session(request) AUTH.sign_out(token) return _json(AUTH.create_anonymous_session(), {"ok": True}) @app.post("/api/auth/register/start") async def api_register_start(request: Request) -> Response: token, session = _session(request) if session.get("authenticated"): return _json(token, {"ok": False, "error": "Sign out before creating another account."}, 409) data = await _payload(request) try: flow = AUTH.start_registration(token, email=str(data.get("email", "")), display_name=str(data.get("display_name", "")), password=str(data.get("password", ""))) local_mail = AUTH.local_mail_for_session(token, purpose="registration") except AuthError as exc: return _json(token, {"ok": False, "error": str(exc)}, 400) return _json(token, {"ok": True, "flow": flow, "local_verification_code": local_mail.get("verification_code") if local_mail else None}) @app.post("/api/auth/register/verify") async def api_register_verify(request: Request) -> Response: token, _ = _session(request) data = await _payload(request) try: AUTH.verify_registration_code(token, str(data.get("code", ""))) result = AUTH.complete_registration(token, subject_factory=domain.create_subject) except (AuthError, domain.DomainError) as exc: return _json(token, {"ok": False, "error": str(exc)}, 400) return _json(str(result["session_token"]), {"ok": True, "account": result["account"]}) @app.post("/api/auth/recovery/start") async def api_recovery_start(request: Request) -> Response: token, session = _session(request) if session.get("authenticated"): return _json(token, {"ok": False, "error": "Sign out before resetting a password."}, 409) data = await _payload(request) try: flow = AUTH.start_password_reset(token, email=str(data.get("email", ""))) # The offline-harbor profile deliberately keeps this local-only. The # code is held by the session-owned fixture inbox, never persisted in # the outbox or sent to a real recipient. local_mail = AUTH.local_mail_for_session(token, purpose="password-reset") except AuthError as exc: return _json(token, {"ok": False, "error": str(exc)}, 400) return _json(token, { "ok": True, "flow": {"accepted": bool(flow.get("accepted")), "message": flow.get("message")}, "mail_status": AUTH.session_mail_status(token, purpose="password-reset"), "local_verification_code": local_mail.get("verification_code") if local_mail else None, }) @app.post("/api/auth/recovery/verify") async def api_recovery_verify(request: Request) -> Response: token, _ = _session(request) data = await _payload(request) try: AUTH.verify_password_reset_code(token, str(data.get("code", ""))) except AuthError as exc: return _json(token, {"ok": False, "error": str(exc)}, 400) return _json(token, {"ok": True, "flow": AUTH.session_flow_status(token, purpose="password-reset")}) @app.post("/api/auth/recovery/complete") async def api_recovery_complete(request: Request) -> Response: token, _ = _session(request) data = await _payload(request) try: session_token = AUTH.complete_password_reset(token, new_password=str(data.get("password", ""))) except AuthError as exc: return _json(token, {"ok": False, "error": str(exc)}, 400) return _json(session_token, {"ok": True}) @app.get("/onboarding", response_class=HTMLResponse) def onboarding(request: Request) -> Response: token, session = _session(request) if not _subject(session): return _signin(token, request) choices = "".join(f'<label><input type="checkbox" name="interests" value="{render.e(value)}">{render.e(value)}</label>' for value in site_data.INTERESTS) body = f'''<section class="onboarding"><p class="eyebrow">Make Medium yours</p><h1>What are you interested in?</h1><p>Choose at least two topics. You can change these local preferences later.</p><div id="onboarding-notice"></div><form id="onboarding-form"><fieldset>{choices}</fieldset><button class="pill green">Continue</button></form></section>''' return _html(token, render.layout("Choose your interests – Medium", body, account=_account(session), page_class="onboarding-page")) @app.post("/api/onboarding") async def api_onboarding(request: Request) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: value = domain.save_onboarding(connection, str(subject), list(data.get("interests") or [])) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "profile": value}) @app.get("/me/lists", response_class=HTMLResponse) def library_page(request: Request) -> Response: token, session = _session(request) if not _subject(session): return _signin(token, request) with BACKEND.lifecycle.connection() as connection: stories = domain.list_public_stories(connection) cards = "".join(render.story_card(story) for story in stories[:3]) body = f'''<section class="library-page"><div class="page-title"><div><h1>Your library</h1><nav><a class="active" href="/me/lists">Saved lists</a><a href="/search">Highlights</a></nav></div></div><section class="library-collection"><p class="eyebrow">Reading list</p><h2>Stories saved for later</h2>{cards or '<div class="empty-state"><p>Your reading list is empty.</p><a href="/search">Find stories</a></div>'}</section></section>''' return _html(token, render.layout("Your library – Medium", body, account=_account(session))) @app.get("/me/notifications", response_class=HTMLResponse) def notifications_page(request: Request) -> Response: token, session = _session(request) if not _subject(session): return _signin(token, request) body = '''<section class="notifications-page"><h1>Notifications</h1><nav class="notification-tabs"><a class="active" href="/me/notifications">All</a><a href="/me/notifications?filter=responses">Responses</a></nav><div class="notification-empty"><span class="notification-empty-icon" aria-hidden="true">✓</span><h2>You’re all caught up.</h2><p>New responses and activity on your local stories will appear here.</p></div></section>''' return _html(token, render.layout("Notifications – Medium", body, account=_account(session))) @app.get("/me") def own_profile(request: Request) -> Response: token, session = _session(request) account = _account(session) if not account: return _signin(token, request) return _to(token, f'/@{site_data.profile_slug(account)}') @app.get("/@{username}", response_class=HTMLResponse) def profile_page(request: Request, username: str) -> Response: token, session = _session(request) profile_account = site_data.account_for_slug(username) if profile_account is None: return _html(token, render.error_page("Profile not found – Medium", "404", "This local writer profile is unavailable.", account=_account(session)), 404) with BACKEND.lifecycle.connection() as connection: stories = [story for story in domain.list_public_stories(connection) if story["owner_subject_id"] == profile_account["subject_id"]] cards = "".join(render.story_card(story) for story in stories) own_profile = _subject(session) == profile_account["subject_id"] body = f'''<section class="profile-page"><header class="profile-heading"><div class="profile-avatar" aria-hidden="true">{render.e(profile_account["display_name"][:1])}</div><div><h1>{render.e(profile_account["display_name"])}</h1><p>Writer on Medium</p></div>{'<a class="profile-edit" href="/me/settings">Edit profile</a>' if own_profile else ''}</header><nav class="profile-tabs"><a class="active" href="/@{render.e(username)}">Home</a><a href="/@{render.e(username)}#lists">Lists</a><a href="/@{render.e(username)}/about">About</a></nav>{cards or '<div class="empty-state"><p>No published stories yet.</p></div>'}</section>''' return _html(token, render.layout(f'{profile_account["display_name"]} – Medium', body, account=_account(session))) @app.get("/me/following-feed/writers", response_class=HTMLResponse) @app.get("/me/following/suggestions", response_class=HTMLResponse) def following_page(request: Request) -> Response: token, session = _session(request) if not _subject(session): return _signin(token, request) body = '''<section class="following-page"><h1>Following</h1><p>Find writers and publications to follow.</p><div class="suggested-writers"><article><span class="profile-avatar" aria-hidden="true">N</span><div><h2>Noah Williams</h2><p>Writing about learning, culture, and science.</p></div><a class="secondary" href="/@noah-williams">View profile</a></article></div></section>''' return _html(token, render.layout("Following – Medium", body, account=_account(session))) @app.get("/me/stories", response_class=HTMLResponse) @app.get("/me/stories/drafts", response_class=HTMLResponse) def drafts(request: Request) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _signin(token, request) with BACKEND.lifecycle.connection() as connection: stories = domain.list_owned_stories(connection, subject) cards = "".join(render.story_card(story, manage=True) for story in stories) body = f'''<section class="stories-page"><div class="page-title"><div><h1>Stories</h1><span class="visually-hidden">Your stories</span><nav><a class="active" href="/me/stories/drafts">Drafts</a><a href="/me/stories?view=scheduled">Scheduled</a><a href="/me/stories?view=published">Published</a><a href="/me/stories?view=unlisted">Unlisted</a><a href="/me/stories?view=submissions">Submissions</a></nav></div><a class="pill green" href="/new-story">Write a story</a></div><div class="story-tools"><a href="/me/stories/import">Import a story</a></div>{cards or '<div class="empty-state"><h2>You have no stories yet.</h2><a href="/new-story">Write your first story</a></div>'}</section>''' return _html(token, render.layout("Your stories – Medium", body, account=_account(session))) @app.get("/new-story") def new_story(request: Request) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _to(token, "/m/signup?operation=register&next=/new-story&intent=write") with BACKEND.lifecycle.connection(transaction=True) as connection: blank = connection.execute("SELECT story_id FROM medium_stories WHERE owner_subject_id=? AND status='draft' AND title='' AND body='' ORDER BY created_at DESC LIMIT 1", (subject,)).fetchone() story_id = str(blank["story_id"]) if blank else domain.create_story(connection, subject) return _to(token, f"/p/{story_id}/edit") @app.get("/p/{story_id}/edit", response_class=HTMLResponse) def story_editor(request: Request, story_id: str) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _signin(token, request) try: with BACKEND.lifecycle.connection() as connection: story = domain.owned_story(connection, subject, story_id) media = domain.story_media(connection, story_id) revisions = domain.story_revisions(connection, subject, story_id) except domain.PermissionDenied: return _html(token, render.error_page("Permission required – Medium", "Permission required", "This draft belongs to another local author.", account=_account(session)), 403) except domain.NotFound: return _html(token, render.error_page("Story not found – Medium", "404", "This story is unavailable. Your other saved drafts are still safe.", account=_account(session)), 404) return _html(token, render.editor(story, media, revisions, _account(session) or {})) @app.get("/p/{story_id}", response_class=HTMLResponse) def story_page(request: Request, story_id: str) -> Response: token, session = _session(request) subject = _subject(session) try: with BACKEND.lifecycle.connection() as connection: story = domain.get_story(connection, story_id) if story["status"] != "published" and story["owner_subject_id"] != subject: raise domain.PermissionDenied("This story is not public.") interactions = domain.engagement(connection, story_id) except domain.PermissionDenied: return _html(token, render.error_page("Story unavailable – Medium", "Private story", "Sign in as the story owner or return to available stories.", account=_account(session)), 403) except domain.NotFound: return _html(token, render.error_page("Page not found – Medium", "404", "You can find (just about) anything on Medium — apparently even a page that doesn’t exist.", account=_account(session)), 404) return _html(token, render.public_story(story, interactions, account=_account(session), owner=story["owner_subject_id"] == subject)) @app.get("/api/stories/{story_id}") def api_story(request: Request, story_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure try: with BACKEND.lifecycle.connection() as connection: story = domain.owned_story(connection, str(subject), story_id) value = {"story": story, "media": domain.story_media(connection, story_id), "revisions": domain.story_revisions(connection, str(subject), story_id)} except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, **value}) @app.put("/api/stories/{story_id}") async def api_save_story(request: Request, story_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: revision = int(data.get("expected_revision", 0)) with BACKEND.lifecycle.connection(transaction=True) as connection: story = domain.save_story(connection, str(subject), story_id, data, expected_revision=revision) except (ValueError, domain.DomainError) as exc: return _error_json(token, exc if isinstance(exc, domain.DomainError) else domain.ValidationFailure({"revision": "Reload the saved version before editing."})) return _json(token, {"ok": True, "story": story, "message": "Saved"}) @app.post("/api/stories/{story_id}/lifecycle") async def api_story_lifecycle(request: Request, story_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: story = domain.transition_story(connection, str(subject), story_id, str(data.get("action", "")), scheduled_at=str(data.get("scheduled_at", ""))) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "story": story, "message": f"Story {story['status']}."}) @app.post("/api/stories/{story_id}/media") async def api_add_media(request: Request, story_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure try: form = await request.form() upload = form.get("media") if upload is None or not hasattr(upload, "read"): raise domain.ValidationFailure({"media": "Choose an image. Your saved story was not changed."}) content = await upload.read() with BACKEND.lifecycle.connection(transaction=True) as connection: media_id = domain.add_media(connection, str(subject), story_id, filename=str(getattr(upload, "filename", "image")), mime_type=str(getattr(upload, "content_type", "")), alt_text=str(form.get("alt_text", "")), content=content) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "media_id": media_id, "message": "Image added."}) @app.delete("/api/stories/{story_id}/media/{media_id}") def api_remove_media(request: Request, story_id: str, media_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure try: with BACKEND.lifecycle.connection(transaction=True) as connection: domain.remove_media(connection, str(subject), story_id, media_id) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "message": "Image removed."}) @app.post("/api/stories/{story_id}/responses") async def api_response(request: Request, story_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: response_id = domain.add_response(connection, str(subject), story_id, str(data.get("body", "")), str(data.get("parent_id", ""))) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "response_id": response_id}) @app.post("/api/stories/{story_id}/clap") def api_clap(request: Request, story_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure try: with BACKEND.lifecycle.connection(transaction=True) as connection: active = domain.toggle_clap(connection, str(subject), story_id) count = domain.engagement(connection, story_id)["claps"] except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "active": active, "count": count}) @app.post("/api/stories/{story_id}/highlights") async def api_highlight(request: Request, story_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: domain.add_highlight(connection, str(subject), story_id, str(data.get("quote", ""))) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "message": "Highlight saved."}) @app.get("/me/publications/new", response_class=HTMLResponse) def publication_create_page(request: Request) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _signin(token, request) with BACKEND.lifecycle.connection() as connection: publications = domain.list_publications(connection, subject) rows = "".join(f'<article><h2>{render.e(item["name"])}</h2><p>{render.e(item["description"])}</p><a href="/publication/{render.e(item["publication_id"])}/settings">Manage publication</a></article>' for item in publications) body = f'''<section class="admin-page"><h1>Your publications</h1><p>Publication settings are stored only in this offline fixture.</p><div id="publication-notice"></div><form id="publication-create-form" class="standard-form"><label>Publication name<input name="name" required maxlength="80"></label><label>Description<textarea name="description" maxlength="240"></textarea></label><button class="pill green">Create publication</button></form><div class="admin-list">{rows}</div></section>''' return _html(token, render.layout("Your publications – Medium", body, account=_account(session))) @app.post("/api/publications") async def api_create_publication(request: Request) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: publication_id = domain.create_publication(connection, str(subject), str(data.get("name", "")), str(data.get("description", ""))) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "publication_id": publication_id}) @app.get("/publication/{publication_id}/settings", response_class=HTMLResponse) def publication_settings(request: Request, publication_id: str) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _signin(token, request) try: with BACKEND.lifecycle.connection() as connection: item = domain.publication_details(connection, subject, publication_id) except domain.DomainError as exc: status = 403 if isinstance(exc, domain.PermissionDenied) else 404 return _html(token, render.error_page("Publication unavailable – Medium", "Publication unavailable", str(exc), account=_account(session)), status) tabs = "".join(f'<a href="#{tab}">{tab.title()}</a>' for tab in site_data.PUBLICATION_TABS) member_rows = "".join(f'''<form class="member-role-form" data-member="{render.e(row['subject_id'])}"><strong>{render.e(row['display_name'])}</strong><select name="role"><option {"selected" if row['role']=="owner" else ""}>owner</option><option {"selected" if row['role']=="editor" else ""}>editor</option><option {"selected" if row['role']=="writer" else ""}>writer</option><option {"selected" if row['role']=="viewer" else ""}>viewer</option></select><button>Save role</button></form>''' for row in item["members"]) subscriber_rows = "".join(f'<li>{render.e(row["display_name"])}</li>' for row in item["subscribers"]) newsletter_rows = "".join(f'<li><strong>{render.e(row["subject"])}</strong> · {render.e(row["status"])}</li>' for row in item["newsletters"]) body = f'''<section class="publication-shell" data-publication-id="{render.e(publication_id)}" style="--publication-accent:{render.e(item['accent'])}"> <aside><a href="/me/publications/new">← Publications</a><h2>{render.e(item['name'])}</h2>{tabs}</aside> <div><h1>Publication settings</h1><div id="publication-notice"></div> <form class="publication-form standard-form" id="general" data-tab="general"><h2>General</h2><label>Name<input name="name" value="{render.e(item['name'])}"></label><label>Description<textarea name="description">{render.e(item['description'])}</textarea></label><button>Save general settings</button></form> <form class="publication-form standard-form" id="navigation" data-tab="navigation"><h2>Navigation</h2><label>Section label<input name="nav_label" value="{render.e(item['nav_label'])}"></label><label>Local path<input name="nav_path" value="{render.e(item['nav_path'])}"></label><button>Save navigation</button></form> <form class="publication-form standard-form" id="theme" data-tab="theme"><h2>Template and theme</h2><p>Select a local publication template and color treatment.</p><label>Template<select name="template_name"><option value="story-grid" {"selected" if item['template_name']=="story-grid" else ""}>Story grid</option><option value="journal" {"selected" if item['template_name']=="journal" else ""}>Journal</option><option value="newsletter" {"selected" if item['template_name']=="newsletter" else ""}>Newsletter</option></select></label><label>Theme<select name="theme_name"><option value="light" {"selected" if item['theme_name']=="light" else ""}>Light</option><option value="warm" {"selected" if item['theme_name']=="warm" else ""}>Warm</option><option value="high-contrast" {"selected" if item['theme_name']=="high-contrast" else ""}>High contrast</option></select></label><button>Save template and theme</button></form> <form class="publication-form standard-form" id="design" data-tab="design"><h2>Design</h2><label>Accent<select name="accent"><option value="#1a8917" {"selected" if item['accent']=="#1a8917" else ""}>Medium green</option><option value="#1565c0" {"selected" if item['accent']=="#1565c0" else ""}>Blue</option><option value="#8e24aa" {"selected" if item['accent']=="#8e24aa" else ""}>Purple</option><option value="#c62828" {"selected" if item['accent']=="#c62828" else ""}>Red</option></select></label><label>Layout<select name="layout"><option value="editorial" {"selected" if item['layout']=="editorial" else ""}>Editorial</option><option value="minimal" {"selected" if item['layout']=="minimal" else ""}>Minimal</option><option value="bold" {"selected" if item['layout']=="bold" else ""}>Bold</option></select></label><div class="publication-preview" id="publication-preview" data-layout="{render.e(item['layout'])}" data-template="{render.e(item['template_name'])}" data-theme="{render.e(item['theme_name'])}"><strong>{render.e(item['name'])}</strong><p>{render.e(item['description'])}</p><small id="preview-style">{render.e(item['template_name'])} · {render.e(item['theme_name'])} · {render.e(item['layout'])}</small></div><button>Save design</button></form> <form class="publication-form standard-form" id="audience" data-tab="audience"><h2>Audience and segmentation</h2><p>Choose which synthetic local reader group this publication view represents.</p><label>Audience<select name="audience_segment"><option value="all-subscribers" {"selected" if item['audience_segment']=="all-subscribers" else ""}>All subscribers</option><option value="new-readers" {"selected" if item['audience_segment']=="new-readers" else ""}>New readers</option><option value="engaged-readers" {"selected" if item['audience_segment']=="engaged-readers" else ""}>Engaged readers</option></select></label><label>Segment label<input name="audience_label" value="{render.e(item['audience_label'])}" maxlength="80"></label><button>Save audience segment</button></form> <section id="members" class="admin-block"><h2>Members and subscribers</h2>{member_rows}<h3>{len(item['subscribers'])} subscribers</h3><ul>{subscriber_rows}</ul></section> <form id="newsletter" class="newsletter-form standard-form"><h2>Newsletter</h2><p>Prepare a local outbox preview. Nothing is delivered externally.</p><label>Subject<input name="subject" value="{render.e(item['newsletter_subject'])}"></label><label>Body<textarea name="body">{render.e(item['newsletter_body'])}</textarea></label><button>Queue local preview</button><ul>{newsletter_rows}</ul></form> <form class="publication-form standard-form" id="integrations" data-tab="integrations"><h2>Integrations</h2><p id="integration-status">Status: <strong>{render.e(item['integration_status'])}</strong>. Providers remain inside this clone and never contact a third party.</p><label>Provider<select name="integration_provider"><option value="none" {"selected" if item['integration_provider']=="none" else ""}>None</option><option value="local-rss" {"selected" if item['integration_provider']=="local-rss" else ""}>Local RSS preview</option><option value="local-analytics" {"selected" if item['integration_provider']=="local-analytics" else ""}>Local analytics summary</option></select></label><label class="check"><input type="checkbox" name="integration_enabled" value="yes" {"checked" if item['integration_status']=="enabled-local" else ""}>Enable this local integration</label><button>Save integration</button></form> <form class="publication-form standard-form" id="domain" data-tab="domain"><h2>Custom domain</h2><p>Status: <strong>{render.e(item['domain_status'])}</strong>. This is a visible simulation; DNS is never changed.</p><label>Domain<input name="custom_domain" value="{render.e(item['custom_domain'])}" placeholder="publication.example"></label><button>Save simulated domain</button></form></div></section>''' return _html(token, render.layout(f"{item['name']} settings – Medium", body, account=_account(session))) @app.put("/api/publications/{publication_id}/{tab}") async def api_save_publication(request: Request, publication_id: str, tab: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: item = domain.save_publication(connection, str(subject), publication_id, tab, data) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "publication": item, "message": f"{tab.title()} settings saved."}) @app.post("/api/publications/{publication_id}/roles") async def api_role(request: Request, publication_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: domain.change_role(connection, str(subject), publication_id, str(data.get("member_subject", "")), str(data.get("role", ""))) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "message": "Contributor role saved."}) @app.post("/api/publications/{publication_id}/newsletter") async def api_newsletter(request: Request, publication_id: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) account = _account(session) or {} try: with BACKEND.lifecycle.connection(transaction=True) as connection: campaign = domain.prepare_newsletter(connection, str(subject), publication_id, str(data.get("subject", "")), str(data.get("body", ""))) job = BACKEND.mail.enqueue("newsletter", str(account.get("email_normalized", "author@medium.local")), {"subject": campaign["subject"], "summary": campaign["body"]}, idempotency_key=f"newsletter:{campaign['campaign_id']}", simulation=True, connection=connection) connection.execute("UPDATE medium_newsletters SET mail_id=? WHERE campaign_id=?", (job["mail_id"], campaign["campaign_id"])) except (domain.DomainError, MailError) as exc: mapped = exc if isinstance(exc, domain.DomainError) else domain.Conflict(str(exc)) return _error_json(token, mapped) return _json(token, {"ok": True, "campaign": {**campaign, "mail_id": job["mail_id"]}, "message": "Newsletter queued in the local outbox. No email was sent."}) @app.get("/me/stats", response_class=HTMLResponse) def stats_page(request: Request) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _signin(token, request) with BACKEND.lifecycle.connection() as connection: value = domain.stats(connection, subject) rows = "".join(f'<tr><td><a href="/p/{render.e(row["story_id"])}">{render.e(row["title"] or "Untitled story")}</a></td><td>{render.e(row["status"])}</td><td>{row["reads"]}</td><td>{row["claps"]}</td><td>{row["responses"]}</td></tr>' for row in value["stories"]) body = f'''<section class="stats-page"><h1>Your story stats</h1><div class="stat-grid"><article><strong>{value['published']}</strong><span>Published</span></article><article><strong>{value['drafts']}</strong><span>Drafts</span></article><article><strong>{value['claps']}</strong><span>Claps</span></article><article><strong>{value['responses']}</strong><span>Responses</span></article></div><table><thead><tr><th>Story</th><th>Status</th><th>Reads</th><th>Claps</th><th>Responses</th></tr></thead><tbody>{rows}</tbody></table></section>''' return _html(token, render.layout("Your stats – Medium", body, account=_account(session))) @app.get("/me/stories/import", response_class=HTMLResponse) def import_page(request: Request) -> Response: token, session = _session(request) if not _subject(session): return _signin(token, request) body = '''<section class="narrow-page"><a href="/me/stories/drafts">← Your stories</a><h1>Import a story</h1><p>Use a <code>local://import/reference</code> fixture URL. Remote websites are never contacted.</p><div id="import-notice"></div><form id="import-form" class="standard-form"><label>Local story URL<input name="url" placeholder="local://import/reference" required></label><button class="pill green">Import</button></form><div class="progress" id="import-progress" hidden><span></span><p>Parsing local content…</p></div></section>''' return _html(token, render.layout("Import a story – Medium", body, account=_account(session))) @app.post("/api/import") async def api_import(request: Request) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: value = domain.import_story(connection, str(subject), str(data.get("url", ""))) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, **value, "message": "Local story imported as a draft."}) @app.get("/me/settings", response_class=HTMLResponse) def settings_page(request: Request) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _signin(token, request) with BACKEND.lifecycle.connection(transaction=True) as connection: profile = domain.profile(connection, subject) body = f'''<section class="settings-page"><h1>Settings</h1><div id="settings-notice"></div><form class="settings-form standard-form" data-tab="notifications"><h2>Notifications</h2><label>Email digest<select name="notification_digest"><option {"selected" if profile['notification_digest']=="off" else ""}>off</option><option {"selected" if profile['notification_digest']=="daily" else ""}>daily</option><option {"selected" if profile['notification_digest']=="weekly" else ""}>weekly</option></select></label><label class="check"><input type="checkbox" name="response_notifications" value="yes" {"checked" if profile['response_notifications'] else ""}>Notify me about local responses</label><button>Save notifications</button></form><form class="settings-form standard-form" data-tab="privacy"><h2>Privacy and sessions</h2><label class="check"><input type="checkbox" name="discoverable" value="yes" {"checked" if profile['discoverable'] else ""}>Allow this synthetic profile to be discovered locally</label><label class="check"><input type="checkbox" name="private_notes" value="yes" {"checked" if profile['private_notes'] else ""}>Keep notes private</label><button>Save privacy</button></form><section class="admin-block"><h2>Your information</h2><p>Download a local export of stories and preferences. No private credentials or session tokens are included.</p><a class="secondary" href="/me/export">Download your information</a></section></section>''' return _html(token, render.layout("Settings – Medium", body, account=_account(session))) @app.put("/api/settings/{tab}") async def api_settings(request: Request, tab: str) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: value = domain.save_preferences(connection, str(subject), data, tab) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "profile": value, "message": f"{tab.title()} preferences saved."}) @app.get("/me/export") def export_account(request: Request) -> Response: token, session = _session(request) subject = _subject(session) if not subject: return _signin(token, request) with BACKEND.lifecycle.connection() as connection: payload = {"site_id": SITE_ID, "profile": domain.profile(connection, subject), "stories": domain.list_owned_stories(connection, subject), "publications": domain.list_publications(connection, subject)} stream = io.BytesIO() with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive: archive.writestr("medium-local-export.json", json.dumps(payload, ensure_ascii=False, indent=2)) stream.seek(0) response = StreamingResponse(stream, media_type="application/zip", headers={"Content-Disposition": 'attachment; filename="medium-local-export.zip"'}) return _cookie(response, token) @app.get("/plans", response_class=HTMLResponse) def plans_page(request: Request) -> Response: token, session = _session(request) cards = '''<article><h2>Free</h2><strong>$0</strong><p>Read and write in the local fixture.</p><button data-plan="free">Choose Free</button></article><article><h2>Medium Member</h2><strong>$5/month</strong><p>Preview a monthly membership selection.</p><button data-plan="member-monthly">Choose monthly</button></article><article><h2>Annual Member</h2><strong>$50/year</strong><p>Preview an annual membership selection.</p><button data-plan="member-yearly">Choose annual</button></article><article><h2>Partner Program</h2><strong>Eligibility review</strong><p>Record interest before finalization.</p><button data-plan="partner-review">Review eligibility</button></article>''' body = f'''<section class="plans-page"><h1>Support human stories</h1><p>Selections remain local and stop before finalization. No card, bank, or wallet field exists.</p><div id="plan-notice"></div><div class="plan-grid">{cards}</div></section>''' return _html(token, render.layout("Medium membership", body, account=_account(session))) @app.post("/api/plans") async def api_plan(request: Request) -> Response: token, session = _session(request) subject, failure = _owner_or_error(token, session) if failure: return failure data = await _payload(request) try: with BACKEND.lifecycle.connection(transaction=True) as connection: value = domain.save_plan(connection, str(subject), str(data.get("plan", ""))) except domain.DomainError as exc: return _error_json(token, exc) return _json(token, {"ok": True, "plan": value["active_plan"], "price": value["active_plan_price"], "message": "Selection saved. Finalization is unavailable in this offline clone."}) @app.get("/membership", response_class=HTMLResponse) def membership_page(request: Request) -> Response: token, session = _session(request) body = '''<section class="source-500-page"><strong>500</strong><div><h1>Apologies, but something went wrong on our end.</h1><p>Refresh the page, check <a href="/status">Medium's site status</a>, or <a href="/">find something interesting to read</a>.</p></div></section>''' return _html(token, render.layout("Membership – Medium", body, account=_account(session), page_class="source-error-surface membership-error-surface")) @app.get("/hc/en-us", response_class=HTMLResponse) @app.get("/help", response_class=HTMLResponse) def help_page(request: Request) -> Response: token, session = _session(request) query = str(request.query_params.get("q") or "").strip() matches = tuple( (title, text, articles) for title, text, articles in site_data.HELP_TOPICS if not query or query.lower() in f"{title} {text} {' '.join(articles)}".lower() ) category_icons = ( '<svg viewBox="0 0 50 50"><circle cx="25" cy="25" r="21"/><circle cx="25" cy="25" r="7"/><path d="m17 33 4-13 13-4-4 13zM25 8v4M25 38v4M8 25h4M38 25h4M13 13l3 3M34 34l3 3M37 13l-3 3M16 34l-3 3"/></svg>', '<svg viewBox="0 0 50 50"><circle cx="25" cy="25" r="21"/><circle cx="25" cy="20" r="7"/><path d="M12 39c2-8 7-12 13-12s11 4 13 12"/></svg>', '<svg viewBox="0 0 50 50"><path d="M6 9c8 0 14 2 19 6v27c-5-4-11-6-19-6zM44 9c-8 0-14 2-19 6v27c4-4 8-5 12-5M12 16l8 2M12 22l8 2M12 28l8 2M38 16l-8 2M38 22l-8 2M38 28l-5 1"/><path d="M37 46v-8c0-2-2-4-4-4s-4 2-4 4v3l-3-2c-2-1-4 1-3 3l4 5"/></svg>', '<svg viewBox="0 0 50 50"><path d="m11 37 5-14L34 5l11 11-18 18zM16 23l11 11M34 5l11 11M11 37l-2 7 7-2"/></svg>', '<svg viewBox="0 0 50 50"><path d="M8 14h34v25H8zM8 14l17 13 17-13M15 9h20"/></svg>', '<svg viewBox="0 0 50 50"><path d="M8 39V11h7l10 16 10-16h7v28h-7V23L25 38 15 23v16z"/></svg>', ) cards = "".join( f'<article><span class="help-category-icon" aria-hidden="true">{category_icons[index % len(category_icons)]}</span><div><h2>{render.e(title)}</h2><p>{render.e(text)}</p><ul class="help-article-list">{"".join(f"<li><a href=\"/help?q={quote_plus(article)}\">{render.e(article)}</a></li>" for article in articles)}</ul><a class="help-see-all" href="/help?q={quote_plus(title)}">See all...</a></div></article>' for index, (title, text, articles) in enumerate(matches) ) result_note = f'<p class="help-result-note">{len(matches)} help topic{"s" if len(matches) != 1 else ""} for “{render.e(query)}”.</p>' if query else "" empty_note = f'<section class="empty-state"><h2>No help topics found for “{render.e(query)}”</h2><p>Try a broader account, reading, writing, or privacy question.</p><a href="/help">Browse all help topics</a></section>' if query and not matches else "" body = f'''<section class="help-page"><div class="help-hero"><h1>How can we help?</h1><form action="/help"><span aria-hidden="true"></span><input name="q" aria-label="Search help" value="{render.e(query)}" placeholder="Search..."><button class="visually-hidden">Search</button></form><p>Popular: <a href="/help?q=membership">Membership</a> <a href="/help?q=partner">Partner Program</a> <a href="/m/signin">Sign in</a></p></div>{result_note}{f'<div class="help-grid">{cards}</div>' if cards else empty_note}<section class="help-safe-note" id="contact"><h2>Can't find what you're looking for?</h2><a class="help-request-link" href="/help#contact">Submit a request</a></section><footer class="help-center-footer"><nav><a href="/status">Status</a><a href="/blog">Writers Blog</a><a href="/jobs-at-medium/work-at-medium-959d1a85284e">Careers</a><a href="/medium-privacy-policy-f03bf92035c9">Privacy</a><a href="/medium-terms-of-service-9db0094a1e0f">Terms</a><a href="/about?autoplay=1">About</a></nav></footer></section>''' return _html(token, render.layout("Medium Help Center", body, account=_account(session), page_class="help-center-surface")) @app.get("/status", response_class=HTMLResponse) def status_page(request: Request) -> Response: token, session = _session(request) uptime = "".join('<i class="uptime-day"></i>' for _ in range(72)) calendar_days = "".join(f'<span>{day}</span>' for day in range(1, 32)) body = f'''<section class="status-page"><section class="status-operational"><h1><span aria-hidden="true">✓</span> We’re fully operational</h1><p>We’re not aware of any issues affecting our systems.</p></section><section class="status-panel"><header><h2>System status</h2><span>‹&nbsp; May 2026 - Aug 2026 &nbsp;›</span></header><article><p><b>✓</b> Web Services <small>3 components⌄</small><em>100% uptime</em></p><div class="uptime-bars">{uptime}</div></article><article><p><b>✓</b> Mobile Apps <small>2 components⌄</small><em>100% uptime</em></p><div class="uptime-bars">{uptime}</div></article></section><section class="status-calendar"><header><h2>Calendar</h2><span>‹&nbsp; Aug 2026 &nbsp;›</span></header><div class="weekdays"><span>M</span><span>T</span><span>W</span><span>T</span><span>F</span><span>S</span><span>S</span></div><div class="calendar-days">{calendar_days}</div></section><p class="status-powered">Powered by <strong>incident.io</strong></p><p class="status-policy">Privacy policy · Terms of service</p></section>''' return _html(token, render.layout("Medium Status", body, account=_account(session), page_class="status-surface")) @app.get("/careers", response_class=HTMLResponse) @app.get("/jobs-at-medium/work-at-medium-959d1a85284e", response_class=HTMLResponse) def careers_page(request: Request) -> Response: token, session = _session(request) body = '''<section class="careers-page"><div class="careers-publication">Jobs at Medium</div><img class="careers-team-banner" src="/static/assets/careers-team-banner.webp" alt="The Medium team together outdoors"><article class="careers-article"><p class="careers-topics">Medium&nbsp;&nbsp; · &nbsp;&nbsp;Careers&nbsp;&nbsp; · &nbsp;&nbsp;Jobs</p><h1>Careers at Medium</h1><h2 class="careers-dek">Help us build the best place to read and write on the internet.</h2><div class="careers-byline"><span class="careers-avatar">M</span><span><b>Jobs @ Medium</b><small>3 min read&nbsp; · &nbsp;Jun 7, 2023</small></span></div><div class="careers-actions">♡&nbsp;&nbsp;&nbsp; — &nbsp;&nbsp;&nbsp;↗</div><p class="careers-warning"><strong>IMPORTANT NOTE: Medium has been made aware of a scam that involves offering people jobs at Medium. Please do not engage with offers that look similar to this. All our open positions are available here.</strong></p><p><a class="careers-link" href="#open-positions">View all open positions</a></p><p>At Medium, we believe in the power of words — and we’re on a mission to bring the world’s expertise to life through memorable storytelling. Our platform rewards great writing and puts power back in the hands of readers. Medium’s subscription model means we rely on our members, not ads. We’re looking for teammates who are inspired by our mission, who are deeply thoughtful and empathetic, and who are passionate about the future of online publishing. Sound like you? Keep reading!</p><p class="careers-note"><em>Note: Medium only hires and communicates via greenhouse.io, our third-party recruiting platform. If you you receive job offers for Medium via LinkedIn or other platforms, it may be a scam; please verify it by contacting us at help.medium.com.</em></p><div class="careers-divider">· &nbsp; · &nbsp; ·</div><h2>Why work at Medium</h2><h3>A meaningful mission</h3><p>From our engineers to our content ops team, employees at Medium (aka “Medians”) are driven by passion, vision, and purpose. We believe in building a high-quality, open platform for sharing ideas — free from harassment, hate speech, and other harmful content. We strive to create a diverse, inclusive place for everyone to feel seen, safe, and supported, both on our product and within our organization.</p><h3>Remote-first culture</h3><p>Collaborate with colleagues from Paris to Portland: Medium is a 100% remote workplace. We’ll provide you with what you need to do your best work, including a stipend for home office expenses, Wi-Fi reimbursement, and a local co-working space membership. (We also know how valuable it is to meet your team IRL, so we hold an all-company retreat twice a year.)</p></article><figure class="careers-collage"><img src="/static/assets/careers-collage-1.webp" alt="Medium colleagues working together"><img src="/static/assets/careers-collage-2.webp" alt="Medium colleagues at a team gathering"><img src="/static/assets/careers-collage-3.webp" alt="Medium colleagues outdoors"><img src="/static/assets/careers-collage-4.webp" alt="Medium colleagues collaborating around a table"></figure><article class="careers-article careers-article-lower"><h3>A creative environment</h3><p>We’re building a culture, not just a product. We believe in experimentation, innovation, and collaboration. We give hi5s and lightning talks and all-company presentations about the ambitious challenges we’re tackling. We share travel photos in our Slack #watercooler channel and craft fun playlists for Thursday writing hours. We question ideas in product workshops, learn from the expertise of our colleagues, and create new things together.</p><h3>Generous benefits</h3><p>Comprehensive health insurance, 401(k) plans, parental leave, and unlimited paid time off are just the start. Our values show up in your benefits: We provide support for your wellbeing at home, education and professional development, financial advising, mental health support, and more.</p><div class="careers-divider">· &nbsp; · &nbsp; ·</div><h2 id="open-positions">Join Our Team</h2><p><a class="careers-link" href="#open-positions">View all open positions</a></p><p>Read our <a class="careers-link" href="#ai-guidance">guidance on AI use for candidates</a>. We believe human ideas have the power to change how people think, for the better. That belief shapes how we hire. We use AI tools ourselves, but we’ve thought carefully about where it adds value and where it gets in the way of something important.</p><div class="careers-join-space" aria-hidden="true"></div><h2>Learn more about Medium</h2><a class="careers-medium-card" href="/blog"><span><b>The Medium Blog</b><small>The official source of news and updates about Medium</small><em>medium.com</em></span><strong>Me</strong></a><p class="careers-tag-row">Medium&nbsp;&nbsp; + &nbsp;&nbsp;Careers&nbsp;&nbsp; + &nbsp;&nbsp;Jobs&nbsp;&nbsp; +</p><div class="careers-actions">♡&nbsp;&nbsp;&nbsp; — <span>↗&nbsp;&nbsp; ☐</span></div><section class="careers-publisher"><div><i></i><p><b>Published in Jobs at Medium</b><small>4.7K followers&nbsp; · &nbsp;Last published Apr 21, 2026</small><em>Keep up to date with our job openings</em></p></div><div><i></i><p><b>Written by Jobs @ Medium</b><small>8.8K followers&nbsp; · &nbsp;21 following</small></p></div></section></article><section class="careers-loading" aria-label="Loading more stories"><i></i><i></i><div><span></span><span></span></div><div><span></span><span></span></div></section></section>''' return _html(token, render.layout("Medium", body, account=_account(session), page_class="careers-surface")) @app.get("/press", response_class=HTMLResponse) def press_page(request: Request) -> Response: return _public_information_page( request, title="Press", eyebrow="Medium", introduction="", sections=(), ) @app.get("/blog", response_class=HTMLResponse) def blog_page(request: Request) -> Response: token, session = _session(request) body = '''<section class="medium-blog-page"><header class="medium-blog-profile"><div class="medium-blog-mark">Me</div><div><h1>The Medium Blog</h1><p>3.4M followers&nbsp; · &nbsp;<span class="blog-editor-dots" aria-hidden="true"><i></i><i></i><i></i><i></i></span>&nbsp; 5+ editors</p></div></header><nav class="medium-blog-tabs"><a href="/blog#product-news">Product News</a><a href="/blog#latest">Latest</a><a href="/blog#newsletter">Newsletter</a></nav><section class="blog-loading-block blog-loading-primary" aria-label="Loading stories"></section><section class="blog-weekly" id="newsletter"><div class="blog-envelope" aria-hidden="true"><span>✉</span></div><h2>Get the best of Medium delivered to you<br>weekly.</h2><button type="button">Subscribe</button></section><section class="blog-loading-row"><i></i><div></div></section><section class="blog-loading-row"><i></i><div></div></section></section>''' return _html( token, render.layout( "The Medium Blog", body, account=_account(session), page_class="medium-blog-surface", ), ) @app.get("/store/medium/", response_class=HTMLResponse) @app.get("/store", response_class=HTMLResponse) def store_page(request: Request) -> Response: token, session = _session(request) products = ( ("TK Merch", "Max Heavyweight Garment Dye Tee", "$25.00", "store-product-1.webp", "sand"), ("", "Reclaimist Pullover Hoodie", "$40.00", "store-product-2.webp", "black"), ("", "Classic Tie Dye Tee", "$24.05", "store-product-3.webp", "colors"), ("Word Cup", "Coffee Mug", "$12.25", "store-product-4.webp", "white"), ("Medium Sweatshirt", "Softstyle Crewneck Sweatshirt", "$29.25", "store-product-5.webp", "white"), ("Medium Wordmark Hoodie", "Heavyweight Pullover Hoodie", "$44.00", "store-product-6.webp", "black"), ) product_cards = "" for product_index, (group, name, price, image, swatches) in enumerate(products): if product_index < 3: media = f'<img src="/static/assets/{image}" alt="{render.e(group or name)}, {render.e(name)}">' else: media = f'<div class="store-product-skeleton skeleton-{product_index}" role="img" aria-label="{render.e(group)}, a {render.e(name)}"><i></i></div>' product_cards += f'''<article class="store-product"><h2>{render.e(group)}</h2>{media}<h3>{render.e(name)}</h3><p>{render.e(price)}</p><div class="store-swatches {swatches}" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i></div></article>''' footer_columns = ( ("Sell online", "Limited edition campaign", "On-demand merch store", "Personal fundraiser"), ("Explore", "Shop the marketplace", "Support a cause", "Product catalog", "Design templates"), ("Nonprofits", "For nonprofits", "Nonprofit merch stores", "Peer-to-peer fundraising"), ("Creators", "For creators", "Discover top creators", "Sell with Merch Shelf", "YouTube creators"), ("Resources", "Blog", "Help center", "Order custom shirts", "Pricing calculator", "Request a custom design", "Stories", "Track my order", "Sitemap"), ("Company", "About", "Careers", "Contact", "Reviews", "Sustainability"), ("Legal", "Accessibility", "Privacy", "Cookie policy", "Cookie preferences", "Terms & conditions", "Do not share or sell my data"), ) footer_lists = "".join( f'''<section><h2>{render.e(items[0])}</h2>{"".join(f'<a href="/store#{index}-{item_index}">{render.e(item)}</a>' for item_index, item in enumerate(items[1:]))}</section>''' for index, items in enumerate(footer_columns) ) cookie_panel = '''<section class="cookie-panel" aria-label="Cookie preferences"><p>We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience, personalize content, customize advertisements, and analyze website traffic. For these reasons, we may share your site usage data with our social media, advertising, and analytics partners. By clicking ”Accept,” you agree to our website's cookie use as described in our <a href="/store/medium/#cookie-policy">Cookie Policy</a>. You can change your cookie settings at any time by clicking “<a href="/store/medium/#preferences">Preferences</a>.”</p><div><button type="button">Preferences</button><button type="button">Decline</button><button type="button">Accept</button></div></section>''' store_menu = '''<aside class="bonfire-mega-menu" id="bonfire-mega-menu" aria-label="Bonfire menu" hidden><button class="bonfire-menu-close" type="button" aria-label="Close menu">×</button><nav><section><h2>How it works</h2><h3>Sell online</h3><a href="#campaign">Sell online in a campaign</a><a href="#store">Create a merch store</a><h3>For creators</h3><a href="#youtube">Sell merch on YouTube</a><a href="#pro">Bonfire Pro <small>Beta</small></a><a href="#branded">Open a fully branded custom merch store</a></section><section><h2>Fundraising</h2><a href="#partial">Partial giving campaigns</a><a href="#personal">Personal fundraising</a><a href="#cause">Discover a cause</a><h3>Fundraising</h3><a href="#peer">Peer-to-peer fundraising</a><a href="#nonprofits">Stores for nonprofits</a><p>This holiday season, give a gift that gives back to a charitable cause with a soft tee from Bonfire.</p><a href="#gifts">Shop gifts</a></section><section><h2>Order Products</h2><a href="#custom">Order custom shirts</a><a href="#studio">Studio</a><a href="#design">Request a custom design</a><a href="#catalog">Product catalog</a><a href="#templates">Design templates</a><a href="#track">Track your order</a></section><section><h2>Shop all shirts</h2><a href="#love">Find something you love</a><a href="#creators">Discover creators</a><a href="#gift-cards">Gift cards</a><h3>By Category</h3><p>Staff Picks · Advocacy · Animal Rescue · Animals · Art &amp; Illustrations · Awareness · Businesses · Conservation · Creators · Fundraising · Hobbies · Holidays · Immigration Rights · Medical · Nonprofits · Schools · Social Justice · Social Movements · Sports</p></section></nav><footer><b>Log in</b><span>Welcome!</span><a href="#dashboard">Dashboard</a><a href="#account">Account Settings</a><a href="#email">Email Preferences</a><a href="#help">Help Center</a><a href="#logout">Log Out</a><a href="#cart">Cart</a></footer></aside>''' body = f'''<main class="bonfire-store">{cookie_panel}<p class="bonfire-source-note">It looks like your browser is outdated. Please update to the latest version in order to get a better experience.</p><div class="returns-strip">▧&nbsp;&nbsp; 90-days hassle-free returns. &nbsp;<a href="/store/medium/#returns">View returns policy</a></div><header class="bonfire-header"><button type="button" class="bonfire-menu" id="bonfire-menu-toggle" aria-controls="bonfire-mega-menu" aria-expanded="false"><i></i><span>MENU</span></button><a class="bonfire-logo" href="/store/medium/"><b>♧</b> BONFIRE</a><nav><a class="bonfire-login" href="/store/medium/#login">Log in</a><a href="/store/medium/#cart"><span class="cart-icon">🛒</span> Cart</a></nav></header>{store_menu}<img class="store-hero" src="/static/assets/store-medium-hero.jpg" alt="Medium Official Merchandise"><section class="store-products">{product_cards}<button class="store-next" type="button" aria-label="Next products">›</button></section><section class="store-share"><button type="button">⇧&nbsp; Share this store</button></section><footer class="bonfire-footer"><a class="bonfire-get-started" href="/start/intent/">Get started <span>→</span></a><div class="bonfire-footer-grid"><section class="bonfire-brand"><a href="/store/medium/" class="bonfire-logo"><b>♧</b> BONFIRE</a><p>Your home for premium<br>custom merch.</p></section>{footer_lists}</div><div class="bonfire-footer-bottom"><span>●&nbsp;&nbsp; ◎&nbsp;&nbsp; ◉&nbsp;&nbsp; 𝕏&nbsp;&nbsp; ▶</span><small>© 2026 Bonfire.com&nbsp;&nbsp;&nbsp;&nbsp; DMCA&nbsp;&nbsp;&nbsp;&nbsp; Trademark Takedown</small><span>⬡&nbsp;&nbsp;&nbsp;&nbsp; Based in Richmond, VA</span></div></footer></main>''' return _html(token, render.layout("Bonfire - Design your own shirt on material you’ll love", body, account=_account(session), page_class="store-surface")) @app.get("/start/intent", response_class=HTMLResponse) @app.get("/start/intent/", response_class=HTMLResponse) def store_start_intent(request: Request) -> Response: """Keep Bonfire's primary campaign-builder handoff inside the clone.""" token, session = _session(request) body = '''<main class="bonfire-intent"><header><a class="bonfire-logo" href="/store/medium/"><b>♧</b> BONFIRE</a></header><section><p class="eyebrow">GET STARTED</p><h1>What would you like to create?</h1><p>Choose a starting point for your local merch idea. This offline clone stops before account creation, payment, publishing, or fulfillment.</p><div><a href="/start/intent/#campaign">Launch a campaign</a><a href="/start/intent/#store">Open a merch store</a><a href="/start/intent/#fundraiser">Start a fundraiser</a></div><a class="back-to-store" href="/store/medium/">← Back to the Medium store</a></section></main>''' return _html(token, render.layout("Get started – Bonfire", body, account=_account(session), page_class="store-surface store-intent-surface")) @app.get("/privacy", response_class=HTMLResponse) @app.get("/medium-privacy-policy-f03bf92035c9", response_class=HTMLResponse) @app.get("/policy/medium-privacy-policy-f03bf92035c9", response_class=HTMLResponse) def privacy_page(request: Request) -> Response: token, session = _session(request) body = '''<section class="source-500-page"><strong>500</strong><div><h1>Apologies, but something went wrong on our end.</h1><p>Refresh the page, check <a href="/status">Medium's site status</a>, or <a href="/">find something interesting to read</a>.</p></div></section>''' return _html(token, render.layout("Medium Privacy Policy", body, account=_account(session), page_class="source-error-surface")) @app.get("/rules", response_class=HTMLResponse) @app.get("/medium-rules-30e5502c4eb4", response_class=HTMLResponse) @app.get("/policy/medium-rules-30e5502c4eb4", response_class=HTMLResponse) def rules_page(request: Request) -> Response: token, session = _session(request) body = '''<section class="source-500-page"><strong>500</strong><div><h1>Apologies, but something went wrong on our end.</h1><p>Refresh the page, check <a href="/status">Medium's site status</a>, or <a href="/">find something interesting to read</a>.</p></div></section>''' return _html(token, render.layout("Medium Rules", body, account=_account(session), page_class="source-error-surface")) @app.get("/terms", response_class=HTMLResponse) @app.get("/medium-terms-of-service-9db0094a1e0f", response_class=HTMLResponse) @app.get("/policy/medium-terms-of-service-9db0094a1e0f", response_class=HTMLResponse) def terms_page(request: Request) -> Response: token, session = _session(request) rows = "".join( f"<{tag}>{render.e(copy)}</{tag}>" for tag, copy in site_data.TERMS_ARTICLE ) action_row = '''<div class="terms-actions"><div><button type="button" aria-label="Clap">♧</button><span>--</span><button type="button" aria-label="Responses">●</button><button type="button" aria-label="Repost">⇄</button></div><div><button type="button" aria-label="Bookmark">☆</button><button type="button" aria-label="Listen">▷</button><button type="button" aria-label="Share">⇧</button></div></div>''' body = f'''<section class="terms-page"><header class="terms-publication">Medium Policy</header><article class="terms-article"><div class="terms-topics"><span>Terms And Conditions <i>+</i></span><span>Terms <i>+</i></span><span>Medium <i>+</i></span></div><h1>Medium Terms of Service</h1><h3>Effective: September 1, 2020</h3><div class="terms-byline"><span>M</span><p><b>Medium</b><small>12 min read&nbsp; · &nbsp;Sep 1, 2020</small></p></div>{action_row}<div class="terms-copy">{rows}</div><div class="terms-bottom-topics">Terms And Conditions&nbsp;&nbsp;&nbsp; Terms&nbsp;&nbsp;&nbsp; Medium</div>{action_row}<section class="terms-publisher"><div><i>Me</i><p><b>Published in Medium Policy</b><small>45K followers&nbsp; · &nbsp;Last published Nov 8, 2021</small><em>Terms of Service, Rules, and Policies</em></p></div><div><i>M</i><p><b>Written by Medium</b><small>1.5M followers&nbsp; · &nbsp;34 following</small><em>Everyone’s stories and ideas</em></p></div></section></article><section class="terms-loading" aria-label="Loading more stories"><i></i><i></i><div><span></span><span></span></div><div><span></span><span></span></div></section></section>''' return _html(token, render.layout("Medium Terms of Service", body, account=_account(session), page_class="terms-surface")) @app.get("/medium/", response_class=HTMLResponse) @app.get("/text-to-speech", response_class=HTMLResponse) def text_to_speech_page(request: Request) -> Response: token, session = _session(request) speechify_columns = ( ("Text to Speech", "iPhone & iPad Apps", "Android App", "Mac App", "Windows App", "Web App", "Chrome Extension", "Edge Add-on", "Download"), ("For Creators", "AI Voice Generator", "Dubbing", "Voice Cloning", "Speechify Work"), ("For Business", "Speechify for Developers", "Teams", "Education", "Text to Speech API Docs", "Voice Agents API Docs"), ("Company", "About", "Contact", "Blog", "Careers", "Affiliates", "Help", "Status", "Press", "Brand Kit"), ) speechify_links = "".join( f'''<section><h3>{render.e(items[0])}</h3>{"".join(f'<a href="/text-to-speech#{column}-{item_index}">{render.e(item)}</a>' for item_index, item in enumerate(items[1:]))}</section>''' for column, items in enumerate(speechify_columns) ) recommended = ("Dictation & Voice Typing", "PDF Text to Speech Android", "Female Voice Generator", "Top Dyslexia Reading Programs", "Text to Speech Anime", "PDF Audio Reader", "Text to Speech Chrome Extension", "PDF Read Aloud", "Texto a Voz", "Voice AI Assistant", "Text to Speech Reader", "Male Voice Generator", "Robot Voice Generator", "AI Voice Changer", "Can Google Docs Read to Me", "Hindi Text to Speech", "AI Voice Generator", "Leitor de Texto") languages = ("العربية", "Magyar", "中文 (简体)", "中文 (台灣)", "中文 (简体 中国大陆)", "Čeština", "Dansk", "Nederlands", "Français", "Suomi", "Deutsch", "हिन्दी", "Italiano", "日本語", "한국어", "Norsk bokmål", "Polski", "Português Brasileiro", "Русский", "Українська", "Español", "Español (México)", "Svenska", "ไทย", "Türkçe", "Tiếng Việt", "Română", "Português", "Български", "ქართული", "Slovenčina", "Slovenščina", "Eesti", "Hrvatski", "Ελληνικά", "Lietuvių", "עברית", "Bahasa Indonesia", "বাংলা", "Català", "Bahasa Melayu", "اردو") speechify_menu = '''<aside class="speechify-mega-menu" id="speechify-mega-menu" aria-label="Speechify product navigation" hidden><button type="button" aria-label="Close menu">×</button><nav><section><h2>Products</h2><a href="#text-to-speech">Text to Speech</a><a href="#iphone">iPhone &amp; iPad Apps</a><a href="#android">Android App</a><a href="#chrome">Chrome Extension</a><a href="#edge">Edge Extension</a><a href="#web">Web App</a><a href="#mac">Mac App</a><a href="#windows">Windows App</a></section><section><h2>AI Voice Generator</h2><a href="#voice-over">Voice Over</a><a href="#dubbing">Dubbing</a><a href="#voice-cloning">Voice Cloning</a><a href="#studio-voices">Studio Voices</a><a href="#captions">Studio Captions</a><a href="#delegate">Delegate Work to AI</a><a href="#work">Speechify Work</a></section><section><h2>Use Cases</h2><a href="#read-aloud">Text to Speech — read aloud PDFs, docs and more</a><a href="#podcasts">AI Podcasts — turn anything into shows</a><a href="#dictation">Voice Typing Dictation — write 5× faster</a><a href="#delegate-work">Delegate Work to AI — get result in seconds</a></section><section><h2>Company</h2><a href="#story">Our Story</a><a href="#blog">Blog</a><a href="#news">News</a><a href="#contact">Contact</a><a href="#careers">Careers</a><a href="#help">Help Center</a><a href="#pricing">Pricing</a><a href="#reviews">Reviews</a><a href="#press">Press</a></section><section><h2>Enterprise</h2><a href="#enterprise-edu">Speechify for Enterprise &amp; EDU</a><a href="#access-to-work">Speechify for Access to Work</a><a href="#dsa">Speechify for DSA</a><a href="#developers">Speechify for Developers</a></section></nav></aside>''' body = f'''<main class="speechify-page"><a class="speechify-banner" href="/medium/#dictation"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="3" width="8" height="13" rx="4"/><path d="M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8"/></svg> Speechify is Launching Voice Typing Dictation <b>›</b></a><header class="speechify-header"><a class="speechify-logo" href="/medium/"><svg viewBox="0 0 34 26" aria-hidden="true"><path d="m1 14 4-3 2 8 4-15 3 18 4-16 3 13 4-9 3 5 5-2"/></svg> Speechify</a><nav><a href="#products" aria-controls="speechify-mega-menu">Products</a><a href="#use-cases" aria-controls="speechify-mega-menu">Use Cases</a><a href="#download">Download</a><a href="#api">API</a><a href="#company" aria-controls="speechify-mega-menu">Company</a><a href="#enterprise" aria-controls="speechify-mega-menu">Enterprise</a></nav><div><a class="speechify-login" href="#login">Log In</a><a class="speechify-trial" href="#trial">Try For Free</a></div></header>{speechify_menu}<article class="speechify-article"><p class="speechify-breadcrumb">Home&nbsp;&nbsp; / &nbsp;&nbsp;<span>Medium members can listen to any Medium story with the Speechify Play Button</span></p><h1>Medium members can listen to any Medium story with the Speechify Play Button.</h1><p>At Medium and Speechify, we’re always exploring new ways to make content more accessible. That’s why we’re excited to share that Speechify is available to all Medium members with the launch of Medium’s Listen feature. Any Medium member can click the “Listen” button at the top of most stories to hear an audio version <u>read aloud</u> from a number of narrators. Users who aren’t Medium members will be invited to sign up for membership.</p><p>Since the launch of our partnership, Medium members have told us that audio has helped them consume more stories than ever before – up to three times as many. Audio helps people listen to Medium articles during the day when they normally wouldn’t be reading: while going on walks, commuting, exercising, doing chores, doing other things on their computer, or even as they fall asleep.</p><p>We’ve also heard many members tell us they retain information better when they have a chance to listen and read at the same time. This is a new way of consuming content that our partnership supports – Speechify highlights text as it reads the audio out loud to you.</p><blockquote>“When working out, I used to read on my phone between sets. Now, it’s so much easier with audio — I can listen to many more articles than I could read before.”</blockquote><p class="speechify-author">— Jess, Medium listener</p><p>From everything we’ve heard, we believe the Speechify play button on Medium can make your experience with Medium more enjoyable and flexible.</p><h2>A Magical Way to Read More</h2><p>If you love reading, you probably have a long list of articles bookmarked. You can now use the Listen feature to make your way through that list faster. Speechify also allows you to change your listening speed. Some users listen to articles at 2-3x the normal listening speed. You can listen to articles at up to 4.5x the normal speed. Speed listening is a productivity hack for many, and we’re excited to make it easier for you.</p><h2>A Tool for Proofreading</h2><p>We’ve heard that writers find the Listen feature helpful when they’re proofreading their drafts. Sentences often sound different when you read them out loud, and we’re excited to help our community of creators improve the stories they bring to life. To listen to one of your drafts, you can click the “…” button in Medium’s web editor, then select “share draft link,” visit that link yourself, and click the Listen button.</p><h2>Making Reading Easy</h2><p>By some estimates, one in five people faces dyslexia, which can make traditional reading difficult. Many people also have visual impairment. Through our listening option, we aim to lower the barrier to learning and delight across Medium.</p><h2>How You Can Listen to Medium with Speechify</h2><p>You can find the Listen button at the top of a Medium story. When you press this button via web browser, as a logged-in Medium member, the story text is read to you and you’ll see the words highlighted as you go.</p><p>We all have our own tastes. If you’d like to listen to a voice other than the default option, you can select a new one by clicking the voice button in the bottom left corner.</p><p>In the bottom right corner, you can click the speed button to adjust the playback speed from 0.5x to 4.5x.</p><p>Happy listening!</p><p>– Team Medium &amp; Team Speechify</p></article><footer class="speechify-footer"><div class="speechify-footer-main">{speechify_links}<section class="speechify-social"><h3>Follow Speechify</h3><div class="speechify-social-icons"><img src="/static/assets/speechify-instagram.svg" alt="Instagram"><img src="/static/assets/speechify-facebook.svg" alt="Facebook"><img src="/static/assets/speechify-x.svg" alt="X"><img src="/static/assets/speechify-tiktok.svg" alt="TikTok"><img src="/static/assets/speechify-linkedin.svg" alt="LinkedIn"><img src="/static/assets/speechify-youtube.svg" alt="YouTube"></div></section><section class="speechify-download"><h3>Get The App</h3><a href="#ios"><img src="/static/assets/speechify-app-store-badge.svg" alt="Download on App Store"></a><a href="#android"><img src="/static/assets/speechify-play-store-badge.svg" alt="Download on Play Store"></a><a href="#mac"><img src="/static/assets/speechify-apple.svg" alt="Apple">Download for macOS</a><a href="#windows"><img src="/static/assets/speechify-windows.svg" alt="Windows">Download for Windows</a></section></div><section class="speechify-recommended"><h2>Recommended Reading</h2><div>{"".join(f'<a href="/medium/#recommended-{index}">{render.e(item)}</a>' for index, item in enumerate(recommended))}</div></section><section class="speechify-languages"><h2>View in other languages</h2><div>{"".join(f'<a href="/medium/#language-{index}">{render.e(item)}</a>' for index, item in enumerate(languages))}</div></section><div class="speechify-bottom"><a class="speechify-logo" href="/medium/"><svg viewBox="0 0 34 26" aria-hidden="true"><path d="m1 14 4-3 2 8 4-15 3 18 4-16 3 13 4-9 3 5 5-2"/></svg> Speechify</a><span>Cookie Preferences&nbsp;&nbsp;&nbsp;&nbsp; Terms of Service&nbsp;&nbsp;&nbsp;&nbsp; Privacy Policy&nbsp;&nbsp;&nbsp;&nbsp; © Speechify Inc 2026</span></div></footer><section class="speechify-language-bar"><strong>Choose your language to get the best Speechify experience</strong><button type="button">◉&nbsp;&nbsp; English&nbsp;&nbsp;&nbsp;&nbsp;⌄</button><button type="button">Continue</button><button class="speechify-language-close" type="button">×</button></section></main>''' return _html(token, render.layout("Medium Members Can Listen To Any Medium Story With The Speechify Play Button | Speechify", body, account=_account(session), page_class="speechify-surface")) @app.get("/api/state") def api_state(request: Request) -> Response: token, session = _session(request) subject = _subject(session) value: dict[str, Any] = {"authenticated": bool(subject), "account": _account(session)} if subject: with BACKEND.lifecycle.connection() as connection: value.update({"profile": domain.profile(connection, subject), "stories": domain.list_owned_stories(connection, subject), "stats": domain.stats(connection, subject)}) return _json(token, value) @app.post("/__websitebench/reset") async def reset(request: Request) -> Response: data = await _payload(request) if data.get("site_id") != SITE_ID: return JSONResponse({"ok": False, "error": "site_id confirmation is required"}, status_code=400) AUTH.reset_site_state(site_reset=site_model.site_reset, seed_accounts=site_data.SEED_ACCOUNTS) return _json(AUTH.create_anonymous_session(), {"ok": True, "site_id": SITE_ID}) @app.get("/{missing_path:path}", response_class=HTMLResponse) def not_found(request: Request, missing_path: str = "") -> Response: token, session = _session(request) return _html(token, render.error_page("Page not found – Medium", "404", "You can find (just about) anything on Medium — apparently even a page that doesn’t exist.", account=_account(session)), 404) if __name__ == "__main__": import os import uvicorn uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("PORT", "8003")), log_level="info")
"""Stateful, network-closed Medium offline clone.
Public reading and discovery use a deliberately small synthetic corpus. All
authoring, publication, account, and community mutations are clone-local and
owned by the site-bound WebsiteBench SQLite runtime.
"""
from __future__ import annotations
import io
import json
import sqlite3
import zipfile
from pathlib import Path
from typing import Any, Mapping
from urllib.parse import quote_plus, urlencode
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response, StreamingResponse
from fastapi.staticfiles import StaticFiles
import domain
import render
import site_data
from backend import site_model
from backend.site_backend_integration import open_site_services
from websitebench.local_clone_auth import AuthError
from websitebench.site_backend import MailError
SITE_ID = "medium"
DISPLAY_NAME = "Medium"
BACKEND, AUTH = open_site_services()
for seed_account in site_data.SEED_ACCOUNTS:
AUTH.seed_account(**seed_account)
COOKIE = dict(BACKEND.session_cookie)
COOKIE_NAME = str(COOKIE.pop("name"))
STATIC_DIR = Path(__file__).resolve().parent / "static"
app = FastAPI(title=DISPLAY_NAME, docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
def _session(request: Request) -> tuple[str, dict[str, Any]]:
return AUTH.ensure_session(request.cookies.get(COOKIE_NAME))
def _account(session: Mapping[str, Any]) -> dict[str, Any] | None:
account = session.get("account")
return dict(account) if account else None
def _subject(session: Mapping[str, Any]) -> str | None:
account = _account(session)
return str(account["subject_id"]) if account else None
def _cookie(response: Response, token: str) -> Response:
response.set_cookie(COOKIE_NAME, token, **COOKIE)
return response
def _html(token: str, markup: str, status: int = 200) -> HTMLResponse:
return _cookie(HTMLResponse(markup, status_code=status), token)
def _json(token: str, payload: Any, status: int = 200) -> JSONResponse:
return _cookie(JSONResponse(payload, status_code=status), token)
def _to(token: str, target: str) -> RedirectResponse:
return _cookie(RedirectResponse(render.safe_next(target), status_code=303), token)
def _signin(token: str, request: Request) -> RedirectResponse:
path = request.url.path + (f"?{request.url.query}" if request.url.query else "")
return _to(token, "/m/signin?" + urlencode({"next": path}))
def _error_json(token: str, exc: Exception) -> JSONResponse:
if isinstance(exc, domain.ValidationFailure):
return _json(token, {"ok": False, "error": str(exc), "errors": exc.errors}, 400)
if isinstance(exc, domain.PermissionDenied):
return _json(token, {"ok": False, "error": str(exc)}, 403)
if isinstance(exc, domain.NotFound):
return _json(token, {"ok": False, "error": str(exc)}, 404)
if isinstance(exc, domain.Conflict):
return _json(token, {"ok": False, "error": str(exc)}, 409)
return _json(token, {"ok": False, "error": "The local action could not be completed."}, 500)
def _owner_or_error(token: str, session: Mapping[str, Any]) -> tuple[str | None, JSONResponse | None]:
subject = _subject(session)
if not subject:
return None, _json(token, {"ok": False, "error": "Sign in to continue."}, 401)
return subject, None
async def _payload(request: Request) -> dict[str, Any]: