Download tasks/autoslash/environment/reference/clone/app.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 70.1 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/autoslash/environment/reference/clone/app.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/autoslash/environment/reference/clone/app.py
-
curl -L -o app.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/autoslash/environment/reference/clone/app.py
70.1 kB
| from __future__ import annotations | |
| import hashlib | |
| import html | |
| import json | |
| import os | |
| import re | |
| import secrets | |
| from datetime import date | |
| from pathlib import Path | |
| from typing import Any | |
| from urllib.parse import parse_qs, urlparse | |
| from fastapi import FastAPI, Request | |
| from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response | |
| from starlette.staticfiles import StaticFiles | |
| from backend.business import read_draft, save_draft, utc_now | |
| from websitebench.site_backend import SiteBackend, load_runtime | |
| ROOT = Path(__file__).resolve().parent | |
| STATIC_DIR = ROOT / "static" | |
| SITE_ROOT = ROOT.parent | |
| SITE_ID = "autoslash" | |
| COOKIE_FALLBACK = "__Host-websitebench-autoslash" | |
| REFERENCE_PAGE_FILES = { | |
| "story": STATIC_DIR / "site" / "reference-pages" / "story.html", | |
| "how": STATIC_DIR / "site" / "reference-pages" / "how.html", | |
| "help": STATIC_DIR / "site" / "reference-pages" / "help.html", | |
| "coupons": STATIC_DIR / "site" / "reference-pages" / "coupons.html", | |
| "quote-home": STATIC_DIR / "site" / "reference-pages" / "quote-home.html", | |
| "quote-vehicle": STATIC_DIR / "site" / "reference-pages" / "quote-vehicle.html", | |
| "quote-memberships": STATIC_DIR / "site" / "reference-pages" / "quote-memberships.html", | |
| "quote-contact": STATIC_DIR / "site" / "reference-pages" / "quote-contact.html", | |
| } | |
| CONTENT_SECURITY_POLICY = ( | |
| "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; " | |
| "script-src 'self'; connect-src 'self'; font-src 'self' data:; " | |
| "frame-ancestors 'none'; base-uri 'self'; form-action 'self'" | |
| ) | |
| EMAIL_RE = re.compile(r"^[^@\s]{1,128}@[^@\s]{1,190}$") | |
| COMPANIES = ( | |
| "Abbycar", "Ace", "ACTIVE Car Rental", "ADA", "addCar", "Adobe", | |
| "Advantage", "AirCar", "Alamo", "Alquicoche Rent a Car", | |
| "America Car Rental", "AmiGo Rent a Car", "Autatlantis", "Autocandia", | |
| "AUTOMARKET Rent a Car", "AutoRent", "Autos Menorca", "AutoUnion", | |
| "AutoVia", "Avec Car Rentals", "Avis", "Avro Rent a Car", "Bargain", | |
| "BLUU Car Rental", "Bravacar", "Bravo Rent a Car", "B-Rent", | |
| "Buchbinder", "Budget", "CarGini", "CarQ", "Carwiz", "Centauro", "Cicar", | |
| "City Car Rental", "Click and Rent", "DIRENT", "Dollar", "Drivalia", | |
| "Drive Car Rental", "Drive On Holidays", "Drive Rent a Car", | |
| "Driving Force", "Easirent", "East Coast Car Rentals", | |
| "EasyCar Costa Rica", "Economy Rent-a-Car", "Ecovia", "Enterprise", | |
| "Essence Car Rental", "Europcar", "EveryCar", "EXER", "FairCar Rental", | |
| "Felirent", "Firefly", "First Car Mauritius", "Flexways", "Flizzr Cyprus", | |
| "Foco", "Fox", "GetYourCar", "Global Rent a Car", "Go By Car", | |
| "Goldcar rental", "GoRentalsNZ", "Green Motion", "GRS Car Rental", | |
| "Guadeloupe Rental", "Guerin", "Hawk Rent a Car", "Hemingways Travel", | |
| "Hertz", "Hiper Rent a Car", "Ilha Verde Rent a car", "InterRent", | |
| "Island car rentals", "Italy Car Rent", "Jumbo Car", "keddy by Europcar", | |
| "Kenings", "Key'n Go", "KK Rent-A-Car", "Lagorent", "Leasys", "LetsDrive", | |
| "Localiza", "Locationauto", "Maggiore", "Mas by Mex Rent-A-Car", | |
| "Megadrive", "Mex Rent-a-Car", "Midway", "Movida Rent A Car", | |
| "Naniko Rent a Car", "National", "NextCar", "Nico Nico Rent a Car", | |
| "Nippon Rent a Car", "Nokta Rent A Car", "Noleggiare", "Nordic Car Rental", | |
| "Nova Rent a Car", "NU", "Offer Car Hire", "OK Mobility", "OPORent", | |
| "Orlando Rent A Car", "Oryx Rent a Car", "Other (Not Listed)", | |
| "OtoQ Car Rental", "Otorento", "Owners Cars", "Pandora", "Panek", | |
| "Payless", "Pricecarz", "Priceless", "RecordGo", "RenMartinique Rental", | |
| "Rentacar", "RentByCar", "RENTMOTORS", "Rentscape", "RightCars", "Routes", | |
| "S S TRAVELS", "Scandia Rent", "Schiller Rent a Car", "Sicily By Car", | |
| "Sixt", "SR Rent a Car", "StarCar", "State Van Rental", | |
| "Street Rent a Car", "Stride", "SurPrice", "Tangerine Rent a Car", | |
| "Thai Rent A Car", "Thrifty", "Top Rent a Car", "TopCar", "Travelcar", | |
| "Turisprime", "Unidas", "United International Car Rentals", | |
| "United Rent A Car", "U-Save", "Viaggiare", "WheeGo", "Yours Rent A Car", | |
| "Zezgo", | |
| ) | |
| VEHICLE_LABELS = { | |
| "ACAR": "Least expensive option", | |
| "ECAR": "Economy car", | |
| "CCAR": "Compact car", | |
| "ICAR": "Midsize car", | |
| "SCAR": "Standard car", | |
| "FCAR": "Full-size car", | |
| "PCAR": "Premium car", | |
| "LCAR": "Luxury car", | |
| "CFAR": "Compact SUV", | |
| "IFAR": "Midsize SUV", | |
| "SFAR": "Standard SUV", | |
| "PGAR": "Premium SUV", | |
| "FFAR": "Full-size SUV", | |
| "PFAR": "Luxury SUV", | |
| "MVAR": "Minivan", | |
| "RVAR": "Passenger van", | |
| "IPAR": "Pickup truck", | |
| } | |
| COUNTRY_LABELS = {"US": "United States"} | |
| AFFILIATION_LABELS = { | |
| "3": "American Express", | |
| "25": "Amex Platinum", | |
| "6": "Discover", | |
| "9": "Mastercard", | |
| "23": "Mastercard World Elite", | |
| "11": "Visa", | |
| "24": "Visa Infinite/Signature", | |
| } | |
| _BACKEND: SiteBackend | None = None | |
| _BACKEND_KEY: tuple[str, str] | None = None | |
| def _backend() -> SiteBackend: | |
| global _BACKEND, _BACKEND_KEY | |
| runtime_path = Path( | |
| os.environ.get( | |
| "WEBSITEBENCH_SITE_BACKEND_RUNTIME", | |
| str(SITE_ROOT / "backend" / "runtime.json"), | |
| ) | |
| ).resolve() | |
| database_override = os.environ.get("WEBSITEBENCH_SITE_BACKEND_DATABASE", "") | |
| key = (str(runtime_path), database_override) | |
| if _BACKEND is not None and _BACKEND_KEY == key: | |
| return _BACKEND | |
| runtime = load_runtime(runtime_path) | |
| if database_override: | |
| database_path = Path(database_override).resolve() | |
| if database_path.name != runtime.database_filename: | |
| raise RuntimeError("deployed database filename does not match runtime") | |
| backend = SiteBackend.open( | |
| json.loads(runtime_path.read_text(encoding="utf-8")), | |
| data_root=database_path.parent, | |
| migration_hook=__import__( | |
| "backend.business", fromlist=["migrate_v1"] | |
| ).migrate_v1, | |
| ) | |
| if backend.lifecycle.database_path != database_path: | |
| raise RuntimeError("deployed database path mismatch") | |
| else: | |
| backend = SiteBackend.open( | |
| runtime_path, | |
| migration_hook=__import__( | |
| "backend.business", fromlist=["migrate_v1"] | |
| ).migrate_v1, | |
| ) | |
| backend.lifecycle.initialize() | |
| _BACKEND = backend | |
| _BACKEND_KEY = key | |
| return backend | |
| def _cookie_name(request: Request) -> str: | |
| configured = str(_backend().session_cookie.get("name", COOKIE_FALLBACK)) | |
| if request.url.scheme == "https": | |
| return configured | |
| return configured.removeprefix("__Host-") | |
| def _digest(value: str, namespace: str = "value") -> str: | |
| return hashlib.sha256(f"autoslash:{namespace}:{value}".encode()).hexdigest() | |
| def _owner(request: Request) -> tuple[str, str | None]: | |
| backend = _backend() | |
| cookie_name = _cookie_name(request) | |
| token = request.cookies.get(cookie_name) | |
| now = utc_now() | |
| with backend.lifecycle.connection(transaction=True) as connection: | |
| if token and len(token) >= 32: | |
| token_digest = _digest(token, "session") | |
| row = connection.execute( | |
| "SELECT owner_id FROM autoslash_sessions WHERE token_digest=?", | |
| (token_digest,), | |
| ).fetchone() | |
| if row is not None: | |
| connection.execute( | |
| "UPDATE autoslash_sessions SET last_seen_at=? WHERE token_digest=?", | |
| (now, token_digest), | |
| ) | |
| return str(row["owner_id"]), None | |
| token = secrets.token_urlsafe(32) | |
| owner_id = f"owner_{secrets.token_hex(12)}" | |
| connection.execute( | |
| "INSERT INTO autoslash_sessions(token_digest,owner_id,created_at,last_seen_at) " | |
| "VALUES (?,?,?,?)", | |
| (_digest(token, "session"), owner_id, now, now), | |
| ) | |
| return owner_id, token | |
| def _finish(request: Request, response: Response, new_token: str | None) -> Response: | |
| if new_token: | |
| response.set_cookie( | |
| _cookie_name(request), | |
| new_token, | |
| httponly=True, | |
| secure=request.url.scheme == "https", | |
| samesite="lax", | |
| path="/", | |
| ) | |
| response.headers["content-security-policy"] = CONTENT_SECURITY_POLICY | |
| response.headers["x-content-type-options"] = "nosniff" | |
| response.headers["referrer-policy"] = "same-origin" | |
| return response | |
| async def _form_values(request: Request) -> dict[str, list[str]]: | |
| raw = (await request.body()).decode("utf-8", errors="replace") | |
| return parse_qs(raw, keep_blank_values=True) | |
| def _form_value(values: dict[str, list[str]], key: str, default: str = "") -> str: | |
| return values.get(key, [default])[0].strip() | |
| def _safe(value: Any) -> str: | |
| return html.escape(str(value), quote=True) | |
| def _request_id(prefix: str) -> str: | |
| return f"{prefix}-{secrets.token_hex(5).upper()}" | |
| def _advance_draft( | |
| connection: sqlite3.Connection, | |
| table: str, | |
| owner: str, | |
| expected_stage: str, | |
| next_stage: str, | |
| values: dict[str, object], | |
| ) -> bool: | |
| if table not in {"autoslash_quote_drafts", "autoslash_tracking_drafts"}: | |
| raise ValueError("unsupported draft table") | |
| row = connection.execute( | |
| f"SELECT stage FROM {table} WHERE owner_id=?", (owner,) | |
| ).fetchone() | |
| if row is None or row["stage"] != expected_stage: | |
| return False | |
| save_draft(connection, table, owner, next_stage, values) | |
| return True | |
| def _workflow_conflict(title: str, message: str, href: str, view: str) -> HTMLResponse: | |
| response = _information_page( | |
| title, | |
| (message, f'<a class="orange-link" href="{href}">Start again</a>'), | |
| view, | |
| ) | |
| response.status_code = 409 | |
| return response | |
| def _display_date(value: object, *, include_time: object = "") -> str: | |
| raw = str(value) | |
| match = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", raw) | |
| if not match: | |
| return raw | |
| year, month, day = (int(part) for part in match.groups()) | |
| months = ( | |
| "Jan", "Feb", "Mar", "Apr", "May", "Jun", | |
| "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", | |
| ) | |
| label = f"{months[month - 1]} {day}, {year}" | |
| return f"{label} at {include_time}" if include_time else label | |
| def _valid_date(value: str) -> bool: | |
| try: | |
| date.fromisoformat(value) | |
| except ValueError: | |
| return False | |
| return True | |
| def _valid_time(value: str) -> bool: | |
| return re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", value) is not None | |
| def _header() -> str: | |
| return """ | |
| <header class="clone-header"> | |
| <div class="clone-header-inner"> | |
| <a class="brand" href="/" aria-label="AutoSlash home"> | |
| <img src="/static/site/assets/logo.svg" alt="AutoSlash"> | |
| </a> | |
| <nav class="desktop-nav" aria-label="Primary"> | |
| <a href="/">Get a Quote</a><span>|</span> | |
| <a href="/track">Track a Rental</a><span>|</span> | |
| <a href="/coupons">Coupons</a><span>|</span> | |
| <a href="/external-link?destination=reviews">Reviews</a><span>|</span> | |
| <a href="/external-link?destination=blog">Blog</a><span>|</span> | |
| <button class="about-toggle" type="button" aria-expanded="false">About Us⌄</button> | |
| </nav> | |
| <button class="menu-toggle" type="button" aria-expanded="false" aria-controls="mobile-nav"> | |
| <img src="/static/site/assets/icon-mob-hamburger.svg" alt=""><span class="sr-only">Menu</span> | |
| </button> | |
| <a class="help-dot" href="/frequently-asked-questions" aria-label="Help"> | |
| <img src="/static/site/assets/icon-question-mark.svg" alt=""> | |
| </a> | |
| </div> | |
| <nav id="mobile-nav" class="mobile-nav" aria-label="Mobile navigation" hidden> | |
| <a href="/">Get a Quote</a><a href="/track">Track a Rental</a> | |
| <a href="/coupons">Coupons</a><a href="/our-story">Our Story</a> | |
| <a href="/how-we-do-it">How We Do It</a> | |
| <a href="/frequently-asked-questions">FAQ</a><a href="/contact-us">Contact Us</a> | |
| </nav> | |
| <div class="about-menu" hidden> | |
| <a href="/our-story">Our Story</a><a href="/how-we-do-it">How We Do It</a> | |
| <a href="/in-the-news">In the News</a> | |
| <a href="/frequently-asked-questions">FAQ</a><a href="/contact-us">Contact Us</a> | |
| </div> | |
| <a class="mobile-rental-banner" href="/reservations/lookup"> | |
| <small>Need to book a new rental?</small> | |
| <strong>Click here and we'll find you a great deal!</strong> | |
| </a> | |
| </header> | |
| """ | |
| def _footer() -> str: | |
| return """ | |
| <footer class="clone-footer"> | |
| <div><p>Connect with us:</p><div class="social-dots" aria-label="Social links"> | |
| <a href="/external-link?destination=facebook" aria-label="Facebook"><svg viewBox="0 0 320 512" aria-hidden="true"><path d="M279.14 288l14.22-92.66h-88.91v-60.13c0-25.35 12.42-50.06 52.24-50.06h40.42V6.26S260.43 0 225.36 0c-73.22 0-121.08 44.38-121.08 124.72v70.62H22.89V288h81.39v224h100.17V288z"/></svg></a> | |
| <a href="/external-link?destination=twitter" aria-label="Twitter"><svg viewBox="0 0 512 512" aria-hidden="true"><path d="M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z"/></svg></a> | |
| <a href="/external-link?destination=youtube" aria-label="YouTube"><svg viewBox="0 0 576 512" aria-hidden="true"><path d="M549.7 124.1c-6.3-23.8-25-42.5-48.6-48.9C458.8 64 288 64 288 64S117.2 64 74.9 75.2c-23.6 6.4-42.3 25.1-48.6 48.9C15 167 15 256.4 15 256.4s0 89.4 11.3 132.3c6.3 23.8 25 41.7 48.6 48.1C117.2 448 288 448 288 448s170.8 0 213.1-11.2c23.6-6.4 42.3-24.3 48.6-48.1 11.3-42.9 11.3-132.3 11.3-132.3s0-89.4-11.3-132.3zM232 336.5v-160l142.7 80-142.7 80z"/></svg></a> | |
| </div> | |
| <nav><a href="/our-story">Our Story</a><span>|</span><a href="/external-link?destination=blog">Blog</a><span>|</span> | |
| <a href="/external-link?destination=reviews">Reviews</a><span>|</span><a href="/coupons">Coupons</a><span>|</span> | |
| <a href="/frequently-asked-questions">Help</a></nav></div> | |
| <div class="footer-brand"><img src="/static/site/assets/logo.svg" alt="AutoSlash"> | |
| <p><a href="/privacy-policy">Privacy Policy</a><span>|</span><a href="/terms-of-use">Terms of Use</a> | |
| <span>|</span> © AutoSlash 2026</p></div> | |
| </footer> | |
| """ | |
| def _document(title: str, view: str, content: str, *, status_code: int = 200) -> HTMLResponse: | |
| markup = f"""<!doctype html><html lang="en"><head> | |
| <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> | |
| <title>{_safe(title)} | AutoSlash</title> | |
| <link rel="stylesheet" href="/static/site/autoslash.css"> | |
| <link rel="stylesheet" href="/static/site/navigation.css"> | |
| </head><body data-view="{_safe(view)}">{_header()}{content}{_footer()} | |
| <script src="/static/site/autoslash.js" defer></script></body></html>""" | |
| return HTMLResponse(markup, status_code=status_code) | |
| def _field( | |
| label: str, | |
| name: str, | |
| *, | |
| input_type: str = "text", | |
| placeholder: str = "", | |
| value: str = "", | |
| required: bool = True, | |
| ) -> str: | |
| required_attr = " required" if required else "" | |
| number_attr = ' step="0.01"' if input_type == "number" else "" | |
| return ( | |
| f'<label class="field"><span>{_safe(label)}</span>' | |
| f'<input type="{_safe(input_type)}" name="{_safe(name)}" ' | |
| f'placeholder="{_safe(placeholder)}" value="{_safe(value)}"' | |
| f'{number_attr}{required_attr}></label>' | |
| ) | |
| def _select(label: str, name: str, options: tuple[str, ...], prompt: str) -> str: | |
| items = [f'<option value="">{_safe(prompt)}</option>'] | |
| items.extend(f'<option value="{_safe(item)}">{_safe(item)}</option>' for item in options) | |
| return ( | |
| f'<label class="field"><span>{_safe(label)}</span>' | |
| f'<select name="{_safe(name)}" required>{"".join(items)}</select></label>' | |
| ) | |
| def _plain_form_page( | |
| title: str, | |
| intro: str, | |
| action: str, | |
| fields: str, | |
| *, | |
| view: str, | |
| extra: str = "", | |
| ) -> HTMLResponse: | |
| body = f"""<main class="plain-page"><section class="plain-card"> | |
| <h1>{_safe(title)}</h1><p class="plain-intro">{intro}</p> | |
| <form method="post" action="{_safe(action)}" class="public-form">{fields} | |
| <button class="orange-button" type="submit">Submit</button></form>{extra} | |
| </section></main>""" | |
| return _document(title, view, body) | |
| def _tracking_page( | |
| stage: int, | |
| title: str, | |
| action: str, | |
| fields: str, | |
| *, | |
| message: str = "", | |
| ) -> HTMLResponse: | |
| labels = ("Rental Co.", "Date", "Price", "Deals", "Email") | |
| progress = "".join( | |
| f'<li class="{"active" if index <= stage else ""}">{label}</li>' | |
| for index, label in enumerate(labels, start=1) | |
| ) | |
| note = f'<p class="form-message" role="alert">{_safe(message)}</p>' if message else "" | |
| body = f"""<main class="tracking-page"> | |
| <section class="tracking-hero"> | |
| <img class="tracking-car" src="/static/site/assets/car-facing-right-lg@2x.png" alt=""> | |
| <a class="tracking-book-callout" href="/"> | |
| <small>Need to book a new rental?</small> | |
| <strong>Click here and we'll<br>find you a great deal!</strong> | |
| </a> | |
| <section class="tracking-card"> | |
| <ol class="workflow-steps">{progress}</ol> | |
| <form method="post" action="{_safe(action)}" class="tracking-form"> | |
| <h1>{_safe(title)}</h1>{note}{fields} | |
| <button class="orange-button" type="submit">Next</button> | |
| </form> | |
| </section> | |
| <a class="tracking-lookup" href="/reservations/lookup">View/Cancel Existing Reservation</a> | |
| </section> | |
| <section class="tracking-explainer"> | |
| <a class="tracking-video-link" href="/external-link?destination=video" | |
| aria-label="Open the AutoSlash savings video"> | |
| <img class="tracking-video" src="/static/site/assets/pic-video-poster@2x.jpg" | |
| alt="AutoSlash rental savings explainer"> | |
| </a> | |
| <h2>Just 3 easy steps to save on your car rental:</h2> | |
| <div class="tracking-tabs"><a href="/">To request a rental quote</a><span>To track a rental</span></div> | |
| <div class="tracking-steps"> | |
| <article><img src="/static/site/assets/pic-steps-track-1.svg" alt=""><div class="tracking-step-copy"><b>1.</b><p>Tell us the confirmation # <br>and price of your <br>car rental...</p></div></article> | |
| <article><img src="/static/site/assets/pic-steps-track-2.svg" alt=""><div class="tracking-step-copy"><b>2.</b><p>Our super-smart computers (coded <br>by travel geeks) <br>get to work...</p></div></article> | |
| <article><img src="/static/site/assets/pic-steps-track-3.svg" alt=""><div class="tracking-step-copy"><b>3.</b><p>You relax! We <br>email you when <br>the price of your <br>rental drops!</p></div></article> | |
| </div> | |
| </section> | |
| <section class="tracking-community"> | |
| <div><h2>Recent Reviews</h2><a href="/external-link?destination=reviews">Review us</a></div> | |
| <div class="tracking-feed"><h2>AutoSlash Tips</h2><a href="/external-link?destination=blog">Check out our blog</a> | |
| <article><a href="/external-link?destination=blog">Who Owns Hertz Car Rental?</a><i>August 22, 2026</i> | |
| <a href="/external-link?destination=blog">What to Know About Car Rentals in North Carolina</a><i>August 22, 2026</i> | |
| <a href="/external-link?destination=blog">Here’s How to Beat a Pricey Airport Car Rental Rate</a><i>August 22, 2026</i><a class="tracking-card-read-more" href="/external-link?destination=blog">Read more</a></article> | |
| </div> | |
| <div class="tracking-news"><h2>In the News</h2><a href="/external-link?destination=press">See all the press</a> | |
| <article> | |
| <a href="/external-link?destination=press">All About Autoslash: The #1 Tool to Save on Rental Cars!</a><i>July 29, 2024</i> | |
| <a href="/external-link?destination=press">5 ON YOUR SIDE: Real deal rental car advice</a><i>July 19, 2024</i> | |
| <a href="/external-link?destination=press">Beginner’s Guide: Save on Car Rentals with AutoSlash</a><i>May 30, 2024</i><a class="tracking-card-read-more" href="/external-link?destination=press">Read more</a> | |
| </article> | |
| </div> | |
| </section> | |
| <a class="source-chat-button" href="/contact-us" | |
| aria-label="Open AutoSlash support"><span aria-hidden="true"><i></i>Help!</span></a> | |
| </main>""" | |
| return _document("Track a Rental", "track", body) | |
| def _confirmation( | |
| title: str, | |
| message: str, | |
| request_id: str, | |
| view: str, | |
| details: tuple[tuple[str, object], ...] = (), | |
| ) -> HTMLResponse: | |
| summary = "" | |
| if details: | |
| rows = "".join( | |
| f"<div><dt>{_safe(label)}</dt><dd>{_safe(value)}</dd></div>" | |
| for label, value in details | |
| ) | |
| summary = f'<dl class="confirmation-summary">{rows}</dl>' | |
| body = f"""<main class="plain-page"><section class="plain-card confirmation-card"> | |
| <h1>{_safe(title)}</h1><p>{_safe(message)}</p> | |
| {summary} | |
| <p class="request-id">Reference: <strong>{_safe(request_id)}</strong></p> | |
| <div class="local-notice">This offline clone saved the request locally. It did not | |
| contact the source site, a rental company, an email provider, or a payment service.</div> | |
| <p><a class="orange-link" href="/">Get another quote</a> | |
| <a class="text-link" href="/track">Track a rental</a></p> | |
| </section></main>""" | |
| return _document(title, view, body) | |
| def _reference_html(kind: str) -> str: | |
| content = REFERENCE_PAGE_FILES[kind].read_text(encoding="utf-8", errors="ignore") | |
| content = re.sub(r"<script\b[^>]*>.*?</script>", "", content, flags=re.I | re.S) | |
| content = re.sub( | |
| r"<meta\b[^>]*http-equiv\s*=\s*[\"']?content-security-policy[\"']?[^>]*>", | |
| "", | |
| content, | |
| flags=re.I, | |
| ) | |
| content = re.sub( | |
| r"<meta\b[^>]*\bname\s*=\s*[\"']?referrer[\"']?[^>]*>", | |
| "", | |
| content, | |
| flags=re.I, | |
| ) | |
| local_links = { | |
| "/track": "/track", | |
| "/coupons": "/coupons", | |
| "/our-story": "/our-story", | |
| "/how-we-do-it": "/how-we-do-it", | |
| "/frequently-asked-questions": "/frequently-asked-questions", | |
| "/contact-us": "/contact-us", | |
| "/reservations/lookup": "/reservations/lookup", | |
| "/privacy-policy": "/privacy-policy", | |
| "/terms-of-use": "/terms-of-use", | |
| } | |
| for path, local in local_links.items(): | |
| content = re.sub( | |
| rf"https?://(?:www\.)?autoslash\.com{re.escape(path)}(?=[\"'\s<>?#])", | |
| local, | |
| content, | |
| flags=re.I, | |
| ) | |
| content = re.sub( | |
| r"https?://(?:www\.)?autoslash\.com(?P<path>/[^\"'\s<>]*)?", | |
| lambda match: match.group("path") or "/", | |
| content, | |
| flags=re.I, | |
| ) | |
| content = re.sub( | |
| r"\b(href|action)=(?:[\"'][^\"']*(?:https?:)?//[^\"']*[\"']|[^\s>]*(?:https?:)?//[^\s>]*)", | |
| r'\1="/external-link?destination=external"', | |
| content, | |
| flags=re.I, | |
| ) | |
| content = re.sub( | |
| r"url\(\s*[\"']?(?:https?:)?//[^)]*\)", "url(data:,)", content, flags=re.I | |
| ) | |
| content = content.replace("https://", "about:blank#").replace("http://", "about:blank#") | |
| actions = { | |
| "quote-home": "/quote/pickup-location", | |
| "quote-vehicle": "/quote/vehicle", | |
| "quote-memberships": "/quote/memberships", | |
| "quote-contact": "/quote/contact-info", | |
| } | |
| if kind in actions: | |
| content = re.sub( | |
| r"(<form\b[^>]*\baction=)(?:\"[^\"]*\"|'[^']*'|[^\s>]+)", | |
| rf'\1"{actions[kind]}"', | |
| content, | |
| count=1, | |
| flags=re.I, | |
| ) | |
| content = re.sub( | |
| r"/quote/vehicle/[a-f0-9-]+(?:\?[^\"'\s<>]*)?", | |
| "/quote/vehicle", | |
| content, | |
| flags=re.I, | |
| ) | |
| content = re.sub( | |
| r"/quote/memberships/[a-f0-9-]+/(?:true|false)", | |
| "/quote/memberships", | |
| content, | |
| flags=re.I, | |
| ) | |
| content = re.sub( | |
| r"/quote/contact-info/[a-f0-9-]+", | |
| "/quote/contact-info", | |
| content, | |
| flags=re.I, | |
| ) | |
| if kind == "quote-contact": | |
| content = re.sub( | |
| r"(<select\b(?=[^>]*\bname=PointOfSaleCountry\b)[^>]*>)\s*</select>", | |
| r'\1<option value="US" selected>United States</option></select>', | |
| content, | |
| count=1, | |
| flags=re.I, | |
| ) | |
| if "Which of these credit cards do you have?" in content: | |
| content = re.sub( | |
| r'<a\b(?=[^>]*\bclass="[^"]*\bgo-to-step2\b[^"]*")[^>]*>\s*Next\s*</a>', | |
| '<button type="submit" class="go-to-step2 btn">Next</button>', | |
| content, | |
| count=1, | |
| flags=re.I, | |
| ) | |
| view = {"quote-home": "home", "quote-vehicle": "quote", | |
| "quote-memberships": "quote", "quote-contact": "quote"}.get(kind, kind) | |
| content = re.sub( | |
| r"<body([^>]*)>", | |
| lambda match: f'<body{match.group(1)} data-view="{view}" data-reference="true">', | |
| content, | |
| count=1, | |
| flags=re.I, | |
| ) | |
| if kind == "help": | |
| content = content.replace( | |
| "</form>", | |
| '</form><p class="faq-empty-message" role="status" hidden>' | |
| 'No results. No FAQ answers match your search. ' | |
| '<a href="/frequently-asked-questions">Show all questions</a>.</p>', | |
| 1, | |
| ) | |
| if kind == "coupons": | |
| company_matches = re.findall( | |
| r"\bdata-company=(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))", | |
| content, | |
| flags=re.I, | |
| ) | |
| companies = sorted( | |
| {next(part for part in match if part) for match in company_matches} | |
| ) | |
| options = '<option value="All">All Companies</option>' + "".join( | |
| f'<option value="{_safe(company)}">{_safe(company)}</option>' | |
| for company in companies | |
| ) | |
| content = re.sub( | |
| r"<select\b(?=[^>]*\bid=coupon-company-select\b)[^>]*>\s*</select>", | |
| '<select class="custom-select-no-search" id="coupon-company-select" ' | |
| f'aria-label="Filter coupons by company">{options}</select>', | |
| content, | |
| count=1, | |
| flags=re.I, | |
| ) | |
| mobile_trigger = ( | |
| '<a href="#modal-mobile-menu" class="mobile-logo popup-from-top" ' | |
| 'aria-label="Open menu"><img class="mobile-menu-icon" ' | |
| 'src="/static/site/assets/icon-mob-hamburger.svg" alt=""></a>' | |
| ) | |
| content = re.sub( | |
| r'<a href=#modal-mobile-menu class="mobile-logo popup-from-top sf-hidden">\s*</a>', | |
| mobile_trigger, | |
| content, | |
| count=1, | |
| flags=re.I, | |
| ) | |
| mobile_panel = ( | |
| '<div id="modal-mobile-menu" class="modal modal-mobile-menu ' | |
| 'mfp-with-anim mfp-hide sf-hidden" aria-hidden="true">' | |
| '<button type="button" class="mfp-close" aria-label="Close menu">×</button>' | |
| '<nav class="mobile-menu-nav" aria-label="Mobile primary">' | |
| '<a href="/">Get a Quote</a><a href="/track">Track a Rental</a>' | |
| '<a href="/reservations/lookup">View/Cancel Existing Reservation</a>' | |
| '<a href="/coupons">Coupons</a><a href="/our-story">Our Story</a>' | |
| '<a href="/how-we-do-it">How We Do It</a>' | |
| '<a href="/frequently-asked-questions">FAQ</a>' | |
| '<a href="/contact-us">Contact Us</a></nav></div>' | |
| ) | |
| content = re.sub( | |
| r'<div id=modal-mobile-menu class="modal modal-mobile-menu ' | |
| r'mfp-with-anim mfp-hide sf-hidden">\s*</div>', | |
| mobile_panel, | |
| content, | |
| count=1, | |
| flags=re.I, | |
| ) | |
| quote_css = ( | |
| '<link rel="stylesheet" href="/static/site/quote-reference.css">' | |
| if kind.startswith("quote-") else "" | |
| ) | |
| additions = ( | |
| quote_css | |
| + '<link rel="stylesheet" href="/static/site/navigation.css">' | |
| + '<script src="/static/site/reference-interactions.js" defer></script>' | |
| + '<script src="/static/site/autoslash.js" defer></script>' | |
| ) | |
| return content.replace("</head>", additions + "</head>", 1) | |
| def _reference_page(kind: str) -> HTMLResponse: | |
| return HTMLResponse(_reference_html(kind)) | |
| def _captured_quote_step( | |
| action: str, content: str, active_count: int, *, show_next: bool = True | |
| ) -> HTMLResponse: | |
| source = _reference_html("quote-vehicle") | |
| source = source.replace('action="/quote/vehicle"', f'action="{action}"', 1) | |
| pane = source.index("<div class=quote-step-pane>") + len("<div class=quote-step-pane>") | |
| controls = source.index("<div class=nav-controls>", pane) | |
| source = source[:pane] + content + source[controls:] | |
| if not show_next: | |
| source = re.sub( | |
| r"<input type=submit[^>]*value=Next[^>]*>", "", source, count=1, flags=re.I | |
| ) | |
| labels = ("Where", "When", "Vehicle", "Deals", "Your details") | |
| for index, label in enumerate(labels): | |
| pattern = ( | |
| rf'<li class=(?:"quote-steps-nav-item(?: active)?"|' | |
| rf'quote-steps-nav-item(?: active)?)[^>]*>{re.escape(label)}</li>' | |
| ) | |
| replacement = ( | |
| f'<li class="quote-steps-nav-item{" active" if index < active_count else ""}">' | |
| f"{label}</li>" | |
| ) | |
| source = re.sub(pattern, replacement, source, count=1) | |
| return HTMLResponse(source) | |
| app = FastAPI(title="AutoSlash offline clone", docs_url=None, redoc_url=None) | |
| app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") | |
| async def security_boundary(request: Request, call_next: Any) -> Response: | |
| if request.method not in {"GET", "HEAD", "OPTIONS"}: | |
| origin = request.headers.get("origin") | |
| parsed = urlparse(origin or "") | |
| if ( | |
| not origin | |
| or parsed.scheme != request.url.scheme | |
| or parsed.netloc != request.url.netloc | |
| or parsed.path not in {"", "/"} | |
| or parsed.params | |
| or parsed.query | |
| or parsed.fragment | |
| ): | |
| return JSONResponse( | |
| {"detail": "same-origin mutation proof required"}, status_code=403 | |
| ) | |
| response = await call_next(request) | |
| response.headers.setdefault("content-security-policy", CONTENT_SECURITY_POLICY) | |
| response.headers.setdefault("x-content-type-options", "nosniff") | |
| response.headers.setdefault("referrer-policy", "same-origin") | |
| return response | |
| async def websitebench_health() -> dict[str, str]: | |
| with _backend().lifecycle.connection() as connection: | |
| connection.execute("SELECT 1").fetchone() | |
| return {"status": "ok"} | |
| async def healthz() -> dict[str, Any]: | |
| with _backend().lifecycle.connection() as connection: | |
| connection.execute("SELECT 1").fetchone() | |
| return {"ok": True, "site_id": SITE_ID} | |
| async def home(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("quote-home"), token) | |
| async def pickup_location_entry(request: Request) -> Response: | |
| return await home(request) | |
| async def pickup_location(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| location_type = _form_value(values, "location_type", "airport") | |
| local_pickup = _form_value(values, "location") | |
| airport_pickup = _form_value(values, "airport") or _form_value( | |
| values, "AirportId-display" | |
| ) | |
| if location_type == "non-airport" and local_pickup: | |
| pickup = local_pickup | |
| else: | |
| location_type = "airport" | |
| pickup = airport_pickup | |
| if not pickup: | |
| return _finish(request, _reference_page("quote-home"), token) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| connection.execute( | |
| "DELETE FROM autoslash_quote_drafts WHERE owner_id=?", (owner,) | |
| ) | |
| save_draft( | |
| connection, "autoslash_quote_drafts", owner, "where", | |
| {"pickup": pickup, "location_type": location_type}, | |
| ) | |
| content = ( | |
| f'<h2>Do you want to return your rental to the same location?</h2>' | |
| f'<p><em>({_safe(pickup)})</em></p><div class="choice-grid">' | |
| '<button class="nav-control-btn nav-control-next btn" type="submit" ' | |
| 'name="same_location" value="yes">Yes</button>' | |
| '<button class="nav-control-btn nav-control-next btn" type="submit" ' | |
| 'name="same_location" value="no">No</button></div>' | |
| ) | |
| return _finish( | |
| request, | |
| _captured_quote_step("/quote/dropoff-location", content, 1, show_next=False), | |
| token, | |
| ) | |
| async def quote_dropoff_location(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| same = _form_value(values, "same_location", "yes") | |
| dropoff = _form_value(values, "dropoff") | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| draft = read_draft(connection, "autoslash_quote_drafts", owner) | |
| pickup = str(draft.get("pickup", "")) | |
| if same == "no" and not dropoff: | |
| content = ( | |
| "<h2>Where will you return the rental?</h2>" | |
| '<label class="field"><span>Drop-off city or address</span>' | |
| '<input class="input-large" name="dropoff" ' | |
| 'placeholder="city, neighborhood, or address" required></label>' | |
| '<input type="hidden" name="same_location" value="no">' | |
| ) | |
| response = _captured_quote_step("/quote/dropoff-location", content, 1) | |
| return _finish(request, response, token) | |
| destination = pickup if same == "yes" else dropoff | |
| if not _advance_draft( | |
| connection, "autoslash_quote_drafts", owner, "where", "pickup-date", | |
| {"dropoff": destination, "same_location": same}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start your quote again", | |
| "The previous location step is missing or no longer current.", | |
| "/", "quote-workflow-required", | |
| ), | |
| token, | |
| ) | |
| content = ( | |
| "<h2>When will you pick up the rental?</h2>" | |
| '<label class="field"><span>Pickup date</span>' | |
| '<input class="input-large" type="date" name="pickup_date" required></label>' | |
| '<label class="field"><span>Pickup time</span>' | |
| '<input class="input-large" type="time" name="pickup_time" value="12:00" required></label>' | |
| "<p><strong>Non-airport locations are typically open 8am-5pm Mon-Fri, " | |
| "8am-12pm Sat, closed Sun.</strong></p>" | |
| ) | |
| return _finish( | |
| request, _captured_quote_step("/quote/pickup-date", content, 2), token | |
| ) | |
| async def quote_pickup_date_get(request: Request) -> Response: | |
| _, token = _owner(request) | |
| content = ( | |
| "<h2>When will you pick up the rental?</h2>" | |
| '<label class="field"><span>Pickup date</span>' | |
| '<input class="input-large" type="date" name="pickup_date" required></label>' | |
| '<label class="field"><span>Pickup time</span>' | |
| '<input class="input-large" type="time" name="pickup_time" value="12:00" required></label>' | |
| ) | |
| return _finish( | |
| request, _captured_quote_step("/quote/pickup-date", content, 2), token | |
| ) | |
| async def quote_pickup_date(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| pickup_date = _form_value(values, "pickup_date") | |
| pickup_time = _form_value(values, "pickup_time", "12:00") | |
| if not _valid_date(pickup_date) or not _valid_time(pickup_time): | |
| return await quote_pickup_date_get(request) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| if not _advance_draft( | |
| connection, "autoslash_quote_drafts", owner, "pickup-date", "dropoff-date", | |
| {"pickup_date": pickup_date, "pickup_time": pickup_time}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start your quote again", | |
| "Complete the location steps before choosing dates.", | |
| "/", "quote-workflow-required", | |
| ), | |
| token, | |
| ) | |
| content = ( | |
| "<h2>When will you drop off the rental?</h2>" | |
| '<label class="field"><span>Drop-off date</span>' | |
| '<input class="input-large" type="date" name="dropoff_date" required></label>' | |
| '<label class="field"><span>Drop-off time</span>' | |
| '<input class="input-large" type="time" name="dropoff_time" value="12:00" required></label>' | |
| ) | |
| return _finish( | |
| request, _captured_quote_step("/quote/dropoff-date", content, 2), token | |
| ) | |
| async def quote_dropoff_date(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| dropoff_date = _form_value(values, "dropoff_date") | |
| dropoff_time = _form_value(values, "dropoff_time", "12:00") | |
| with _backend().lifecycle.connection() as connection: | |
| draft = read_draft(connection, "autoslash_quote_drafts", owner) | |
| pickup_date = str(draft.get("pickup_date", "")) | |
| if ( | |
| not _valid_date(dropoff_date) | |
| or not _valid_time(dropoff_time) | |
| or not _valid_date(pickup_date) | |
| or dropoff_date < pickup_date | |
| ): | |
| response = _captured_quote_step( | |
| "/quote/dropoff-date", | |
| "<h2>When will you drop off the rental?</h2>" | |
| '<p class="form-message">Select a drop-off date after the pickup date.</p>' | |
| '<input class="input-large" type="date" name="dropoff_date" required>', | |
| 2, | |
| ) | |
| return _finish(request, response, token) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| if not _advance_draft( | |
| connection, "autoslash_quote_drafts", owner, "dropoff-date", "vehicle", | |
| {"dropoff_date": dropoff_date, "dropoff_time": dropoff_time}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start your quote again", | |
| "Complete the pickup-date step before choosing a drop-off date.", | |
| "/", "quote-workflow-required", | |
| ), | |
| token, | |
| ) | |
| return _finish(request, _reference_page("quote-vehicle"), token) | |
| async def quote_vehicle(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("quote-vehicle"), token) | |
| async def quote_vehicle_post(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| vehicle = _form_value(values, "CarClass") | |
| if vehicle not in VEHICLE_LABELS: | |
| return _finish(request, _reference_page("quote-vehicle"), token) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| if not _advance_draft( | |
| connection, "autoslash_quote_drafts", owner, "vehicle", "deals", | |
| {"vehicle_class": vehicle}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start your quote again", | |
| "Complete the location and date steps before choosing a vehicle.", | |
| "/", "quote-workflow-required", | |
| ), | |
| token, | |
| ) | |
| return _finish(request, _reference_page("quote-memberships"), token) | |
| async def quote_memberships(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("quote-memberships"), token) | |
| async def quote_memberships_post(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| deals = values.get("AffiliationIds", []) | |
| if not deals or any(deal not in AFFILIATION_LABELS for deal in deals): | |
| return _finish(request, _reference_page("quote-memberships"), token) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| if not _advance_draft( | |
| connection, "autoslash_quote_drafts", owner, "deals", "contact", | |
| {"affiliation_ids": deals}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start your quote again", | |
| "Choose a vehicle before adding memberships and discounts.", | |
| "/", "quote-workflow-required", | |
| ), | |
| token, | |
| ) | |
| return _finish(request, _reference_page("quote-contact"), token) | |
| async def quote_contact_info(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("quote-contact"), token) | |
| async def quote_contact_info_post(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| first = _form_value(values, "FirstName") | |
| last = _form_value(values, "LastName") | |
| email = _form_value(values, "Email").casefold() | |
| confirm = _form_value(values, "ConfirmEmail").casefold() | |
| license_country = _form_value(values, "PointOfSaleCountry") | |
| if not first or not last or not EMAIL_RE.fullmatch(email) or email != confirm: | |
| return _finish(request, _reference_page("quote-contact"), token) | |
| request_id = _request_id("ASQ") | |
| backend = _backend() | |
| with backend.lifecycle.connection(transaction=True) as connection: | |
| draft = connection.execute( | |
| "SELECT stage,payload_json FROM autoslash_quote_drafts WHERE owner_id=?", | |
| (owner,), | |
| ).fetchone() | |
| required = { | |
| "pickup", "location_type", "dropoff", "same_location", | |
| "pickup_date", "pickup_time", "dropoff_date", "dropoff_time", | |
| "vehicle_class", "affiliation_ids", | |
| } | |
| payload = json.loads(draft["payload_json"]) if draft is not None else {} | |
| if draft is None or draft["stage"] != "contact" or not required <= payload.keys(): | |
| response = _information_page( | |
| "Complete your quote first", | |
| ( | |
| "Complete the earlier quote steps before submitting contact information.", | |
| "Return to Get a Quote to choose locations, dates, vehicle, and deals.", | |
| ), | |
| "quote-workflow-required", | |
| ) | |
| response.status_code = 409 | |
| return _finish(request, response, token) | |
| if license_country not in COUNTRY_LABELS: | |
| return _finish(request, _reference_page("quote-contact"), token) | |
| payload.update({ | |
| "first_name": first, | |
| "last_name": last, | |
| "email": email, | |
| "license_country": license_country, | |
| }) | |
| connection.execute( | |
| "INSERT INTO autoslash_quote_requests" | |
| "(request_id,owner_id,payload_json,status,created_at) VALUES (?,?,?,?,?)", | |
| (request_id, owner, json.dumps(payload, sort_keys=True), "received", utc_now()), | |
| ) | |
| backend.mail.enqueue( | |
| "quote-request", email, {"request_id": request_id}, | |
| idempotency_key=f"quote:{request_id}", simulation=True, connection=connection, | |
| ) | |
| connection.execute( | |
| "DELETE FROM autoslash_quote_drafts WHERE owner_id=?", (owner,) | |
| ) | |
| response = RedirectResponse("/quote/confirmation", status_code=303) | |
| return _finish(request, response, token) | |
| async def quote_confirmation(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| with _backend().lifecycle.connection() as connection: | |
| row = connection.execute( | |
| "SELECT request_id,payload_json FROM autoslash_quote_requests " | |
| "WHERE owner_id=? ORDER BY created_at DESC,rowid DESC LIMIT 1", | |
| (owner,), | |
| ).fetchone() | |
| if row is None: | |
| return _finish(request, RedirectResponse("/", status_code=303), token) | |
| payload = json.loads(row["payload_json"]) | |
| response = _confirmation( | |
| "Thanks! We're working on your quote.", | |
| "Your quote request has been received. No credit card is required.", | |
| str(row["request_id"]), | |
| "quote-confirmation", | |
| ( | |
| ("Pickup", payload["pickup"]), | |
| ("Drop-off", payload["dropoff"]), | |
| ( | |
| "Pickup date", | |
| _display_date(payload["pickup_date"], include_time=payload["pickup_time"]), | |
| ), | |
| ( | |
| "Drop-off date", | |
| _display_date(payload["dropoff_date"], include_time=payload["dropoff_time"]), | |
| ), | |
| ("Vehicle", VEHICLE_LABELS.get(payload["vehicle_class"], payload["vehicle_class"])), | |
| ( | |
| "Cards and discounts", | |
| ", ".join( | |
| AFFILIATION_LABELS.get(item, item) | |
| for item in payload["affiliation_ids"] | |
| ), | |
| ), | |
| ("Primary driver", f'{payload["first_name"]} {payload["last_name"]}'), | |
| ( | |
| "Driver's license issued by", | |
| COUNTRY_LABELS.get(payload["license_country"], payload["license_country"]), | |
| ), | |
| ), | |
| ) | |
| return _finish(request, response, token) | |
| async def track(request: Request) -> Response: | |
| _, token = _owner(request) | |
| fields = ( | |
| _select("Company", "CompanyId", COMPANIES, "select your rental company") | |
| + _field( | |
| "Confirmation Number", "TrackingConfirmationNumber", | |
| placeholder="rental confirmation number", | |
| ) | |
| ) | |
| return _finish( | |
| request, | |
| _tracking_page( | |
| 1, "Enter your rental company and confirmation number:", | |
| "/price-tracking/confirmation", fields, | |
| ), | |
| token, | |
| ) | |
| async def tracking_confirmation(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| company = _form_value(values, "CompanyId") | |
| confirmation = _form_value( | |
| values, "TrackingConfirmationNumber" | |
| ) or _form_value(values, "ConfirmationNumber") | |
| if company not in COMPANIES or not confirmation: | |
| response = _tracking_page( | |
| 1, "Enter your rental company and confirmation number:", | |
| "/price-tracking/confirmation", | |
| _select("Company", "CompanyId", COMPANIES, "select your rental company") | |
| + _field( | |
| "Confirmation Number", "TrackingConfirmationNumber", | |
| placeholder="rental confirmation number", | |
| ), | |
| message="Choose a rental company and enter your confirmation number.", | |
| ) | |
| return _finish(request, response, token) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| connection.execute( | |
| "DELETE FROM autoslash_tracking_drafts WHERE owner_id=?", (owner,) | |
| ) | |
| save_draft( | |
| connection, "autoslash_tracking_drafts", owner, "date", | |
| {"company": company, "confirmation": confirmation}, | |
| ) | |
| fields = _field("Pickup date", "pickup_date", input_type="date") + _field( | |
| "Drop-off date", "dropoff_date", input_type="date" | |
| ) | |
| return _finish( | |
| request, | |
| _tracking_page(2, "When is your rental?", "/price-tracking/date", fields), | |
| token, | |
| ) | |
| async def tracking_date(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| pickup_date = _form_value(values, "pickup_date") | |
| dropoff_date = _form_value(values, "dropoff_date") | |
| if ( | |
| not _valid_date(pickup_date) | |
| or not _valid_date(dropoff_date) | |
| or dropoff_date < pickup_date | |
| ): | |
| response = _tracking_page( | |
| 2, "When is your rental?", "/price-tracking/date", | |
| _field("Pickup date", "pickup_date", input_type="date") | |
| + _field("Drop-off date", "dropoff_date", input_type="date"), | |
| message="Enter a valid pickup and drop-off date.", | |
| ) | |
| return _finish(request, response, token) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| if not _advance_draft( | |
| connection, "autoslash_tracking_drafts", owner, "date", "price", | |
| {"pickup_date": pickup_date, "dropoff_date": dropoff_date}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start price tracking again", | |
| "Enter the rental company and confirmation number before the dates.", | |
| "/track", "tracking-workflow-required", | |
| ), | |
| token, | |
| ) | |
| fields = _field( | |
| "Total rental price", "total_price", input_type="number", placeholder="0.00" | |
| ) + _field( | |
| "Currency", "currency", value="USD", required=True | |
| ) | |
| return _finish( | |
| request, | |
| _tracking_page( | |
| 3, "What price did you book?", "/price-tracking/price", fields | |
| ), | |
| token, | |
| ) | |
| async def tracking_price(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| total = _form_value(values, "total_price") | |
| try: | |
| valid_total = 0 < float(total) < 100000 | |
| except ValueError: | |
| valid_total = False | |
| if not valid_total: | |
| response = _tracking_page( | |
| 3, "What price did you book?", "/price-tracking/price", | |
| _field("Total rental price", "total_price", input_type="number"), | |
| message="Enter the total price shown on your reservation.", | |
| ) | |
| return _finish(request, response, token) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| if not _advance_draft( | |
| connection, "autoslash_tracking_drafts", owner, "price", "deals", | |
| {"total_price": total, "currency": "USD"}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start price tracking again", | |
| "Enter the reservation dates before its total price.", | |
| "/track", "tracking-workflow-required", | |
| ), | |
| token, | |
| ) | |
| fields = ( | |
| '<fieldset class="deal-options"><legend>Which discounts may apply?</legend>' | |
| '<label><input type="checkbox" name="deals" value="AAA"> AAA</label>' | |
| '<label><input type="checkbox" name="deals" value="AARP"> AARP</label>' | |
| '<label><input type="checkbox" name="deals" value="USAA"> USAA</label>' | |
| '<label><input type="checkbox" name="deals" value="none"> None of these</label>' | |
| "</fieldset>" | |
| ) | |
| return _finish( | |
| request, | |
| _tracking_page( | |
| 4, "Tell us about your eligible discounts:", | |
| "/price-tracking/deals", fields, | |
| ), | |
| token, | |
| ) | |
| async def tracking_deals(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| if not _advance_draft( | |
| connection, "autoslash_tracking_drafts", owner, "deals", "email", | |
| {"deals": values.get("deals", [])}, | |
| ): | |
| return _finish( | |
| request, | |
| _workflow_conflict( | |
| "Start price tracking again", | |
| "Enter the booked price before selecting eligible discounts.", | |
| "/track", "tracking-workflow-required", | |
| ), | |
| token, | |
| ) | |
| fields = _field( | |
| "Email", "email", input_type="email", placeholder="ex. janedoe@example.com" | |
| ) + _field( | |
| "Confirm Email", "confirm_email", input_type="email", placeholder="confirm email" | |
| ) | |
| return _finish( | |
| request, | |
| _tracking_page( | |
| 5, "Where should we send price-drop alerts?", | |
| "/price-tracking/email", fields, | |
| ), | |
| token, | |
| ) | |
| async def tracking_email(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| email = _form_value(values, "email").casefold() | |
| confirm = _form_value(values, "confirm_email").casefold() | |
| if not EMAIL_RE.fullmatch(email) or email != confirm: | |
| response = _tracking_page( | |
| 5, "Where should we send price-drop alerts?", | |
| "/price-tracking/email", | |
| _field("Email", "email", input_type="email") | |
| + _field("Confirm Email", "confirm_email", input_type="email"), | |
| message="Enter the same valid email address twice.", | |
| ) | |
| return _finish(request, response, token) | |
| request_id = _request_id("AST") | |
| backend = _backend() | |
| with backend.lifecycle.connection(transaction=True) as connection: | |
| draft = connection.execute( | |
| "SELECT stage,payload_json FROM autoslash_tracking_drafts WHERE owner_id=?", | |
| (owner,), | |
| ).fetchone() | |
| required = { | |
| "company", "confirmation", "pickup_date", "dropoff_date", | |
| "total_price", "currency", "deals", | |
| } | |
| payload = json.loads(draft["payload_json"]) if draft is not None else {} | |
| if draft is None or draft["stage"] != "email" or not required <= payload.keys(): | |
| response = _information_page( | |
| "Complete price tracking first", | |
| ( | |
| "Complete the earlier tracking steps before submitting an email.", | |
| "Return to Track a Rental to add the reservation, dates, price, and deals.", | |
| ), | |
| "tracking-workflow-required", | |
| ) | |
| response.status_code = 409 | |
| return _finish(request, response, token) | |
| payload["email"] = email | |
| connection.execute( | |
| "INSERT INTO autoslash_tracking_requests" | |
| "(request_id,owner_id,payload_json,status,created_at) VALUES (?,?,?,?,?)", | |
| (request_id, owner, json.dumps(payload, sort_keys=True), "watching", utc_now()), | |
| ) | |
| backend.mail.enqueue( | |
| "price-tracking", email, {"request_id": request_id}, | |
| idempotency_key=f"tracking:{request_id}", simulation=True, | |
| connection=connection, | |
| ) | |
| connection.execute( | |
| "DELETE FROM autoslash_tracking_drafts WHERE owner_id=?", (owner,) | |
| ) | |
| response = RedirectResponse("/price-tracking/complete", status_code=303) | |
| return _finish(request, response, token) | |
| async def tracking_complete(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| with _backend().lifecycle.connection() as connection: | |
| row = connection.execute( | |
| "SELECT request_id,payload_json FROM autoslash_tracking_requests " | |
| "WHERE owner_id=? ORDER BY created_at DESC,rowid DESC LIMIT 1", | |
| (owner,), | |
| ).fetchone() | |
| if row is None: | |
| return _finish(request, RedirectResponse("/track", status_code=303), token) | |
| payload = json.loads(row["payload_json"]) | |
| response = _confirmation( | |
| "We'll watch for lower prices.", | |
| "If a lower rate appears, AutoSlash notifies you. You decide whether to " | |
| "rebook and cancel the old reservation; no automatic rebooking occurs.", | |
| str(row["request_id"]), | |
| "tracking-confirmation", | |
| ( | |
| ("Rental company", payload["company"]), | |
| ("Confirmation number", payload["confirmation"]), | |
| ("Pickup date", _display_date(payload["pickup_date"])), | |
| ("Drop-off date", _display_date(payload["dropoff_date"])), | |
| ("Booked total", f'${float(payload["total_price"]):.2f} {payload["currency"]}'), | |
| ("Eligible discounts", ", ".join(payload["deals"]) or "None selected"), | |
| ), | |
| ) | |
| return _finish(request, response, token) | |
| async def reservation_lookup(request: Request) -> Response: | |
| _, token = _owner(request) | |
| response = _plain_form_page( | |
| "Reservation Lookup", | |
| 'View or cancel an existing reservation. ' | |
| '<a href="/reservations/forgot">Don\'t remember your Trip ID?</a>', | |
| "/reservations/lookup", | |
| _field( | |
| "Trip ID or Confirmation Number", "confirmation", | |
| placeholder="from your confirmation email", | |
| ) | |
| + _field("Email", "email", input_type="email", placeholder="ex. janedoe@example.com"), | |
| view="reservation-lookup", | |
| extra='<p><a href="/external-link?destination=priceline">Booked with Priceline?</a></p>', | |
| ) | |
| return _finish(request, response, token) | |
| async def reservation_lookup_post(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| confirmation = _form_value(values, "confirmation") | |
| email = _form_value(values, "email").casefold() | |
| if not confirmation or not EMAIL_RE.fullmatch(email): | |
| return await reservation_lookup(request) | |
| request_id = _request_id("ASL") | |
| with _backend().lifecycle.connection(transaction=True) as connection: | |
| connection.execute( | |
| "INSERT INTO autoslash_lookup_requests" | |
| "(request_id,owner_id,confirmation_digest,email_digest,status,created_at) " | |
| "VALUES (?,?,?,?,?,?)", | |
| ( | |
| request_id, owner, _digest(confirmation, "confirmation"), | |
| _digest(email, "email"), "not-found-local", utc_now(), | |
| ), | |
| ) | |
| response = _confirmation( | |
| "We couldn't find a local reservation.", | |
| "This offline review database contains no source-site reservations. " | |
| "Check the Trip ID and email or request a Trip ID reminder.", | |
| request_id, | |
| "reservation-lookup", | |
| ) | |
| return _finish(request, response, token) | |
| async def forgot_trip(request: Request) -> Response: | |
| _, token = _owner(request) | |
| response = _plain_form_page( | |
| "Forgot your Trip ID?", | |
| "Enter the email address used for your AutoSlash quote or tracked rental.", | |
| "/reservations/forgot", | |
| _field("Email", "email", input_type="email", placeholder="ex. janedoe@example.com"), | |
| view="forgot-trip", | |
| ) | |
| return _finish(request, response, token) | |
| async def forgot_trip_post(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| email = _form_value(values, "email").casefold() | |
| if not EMAIL_RE.fullmatch(email): | |
| return await forgot_trip(request) | |
| request_id = _request_id("ASR") | |
| backend = _backend() | |
| with backend.lifecycle.connection(transaction=True) as connection: | |
| backend.mail.enqueue( | |
| "trip-id-recovery", email, {"request_id": request_id}, | |
| idempotency_key=f"recovery:{owner}:{request_id}", | |
| simulation=True, connection=connection, | |
| ) | |
| response = _confirmation( | |
| "Check your email.", | |
| "If this address matches a local record, recovery instructions were placed " | |
| "in the local-only outbox. The public response does not reveal a match.", | |
| request_id, | |
| "forgot-trip", | |
| ) | |
| return _finish(request, response, token) | |
| async def contact_us(request: Request) -> Response: | |
| _, token = _owner(request) | |
| fields = ( | |
| _field("Name", "name", placeholder="ex. Jane Doe") | |
| + _field("Email", "email", input_type="email", placeholder="ex. janedoe@example.com") | |
| + _field("Confirm Email", "confirm_email", input_type="email", placeholder="confirm email") | |
| + _field("Subject", "subject", placeholder="ex. tracking help") | |
| + '<label class="field"><span>Description</span>' | |
| '<textarea name="description" required></textarea></label>' | |
| ) | |
| response = _plain_form_page( | |
| "Contact AutoSlash Support", | |
| "Fill out the form below or email us directly at support@autoslash.com.", | |
| "/contact-us", | |
| fields, | |
| view="contact", | |
| ) | |
| return _finish(request, response, token) | |
| async def contact_us_post(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| values = await _form_values(request) | |
| name = _form_value(values, "name") | |
| email = _form_value(values, "email").casefold() | |
| confirm = _form_value(values, "confirm_email").casefold() | |
| subject = _form_value(values, "subject") | |
| description = _form_value(values, "description") | |
| if ( | |
| not name or not EMAIL_RE.fullmatch(email) or email != confirm | |
| or not subject or not description | |
| ): | |
| return await contact_us(request) | |
| request_id = _request_id("ASC") | |
| backend = _backend() | |
| with backend.lifecycle.connection(transaction=True) as connection: | |
| connection.execute( | |
| "INSERT INTO autoslash_support_requests" | |
| "(request_id,owner_id,name,email,subject,description,status,created_at) " | |
| "VALUES (?,?,?,?,?,?,?,?)", | |
| (request_id, owner, name, email, subject, description, "received", utc_now()), | |
| ) | |
| backend.mail.enqueue( | |
| "contact-request", email, {"request_id": request_id}, | |
| idempotency_key=f"contact:{request_id}", | |
| simulation=True, connection=connection, | |
| ) | |
| response = _confirmation( | |
| "Thanks for contacting us.", | |
| "Your support request was saved in the local review environment.", | |
| request_id, | |
| "contact", | |
| ) | |
| return _finish(request, response, token) | |
| async def help_page(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("help"), token) | |
| async def coupons(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("coupons"), token) | |
| async def our_story(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("story"), token) | |
| async def how_we_do_it(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish(request, _reference_page("how"), token) | |
| def _information_page(title: str, paragraphs: tuple[str, ...], view: str) -> HTMLResponse: | |
| content = "".join(f"<p>{_safe(paragraph)}</p>" for paragraph in paragraphs) | |
| return _document( | |
| title, | |
| view, | |
| f'<main class="plain-page"><article class="plain-card info-card">' | |
| f"<h1>{_safe(title)}</h1>{content}</article></main>", | |
| ) | |
| async def in_the_news(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish( | |
| request, | |
| _information_page( | |
| "In the News", | |
| ("AutoSlash press links open outside the first-party site.", | |
| "External destinations are intentionally not contacted by this offline clone."), | |
| "news", | |
| ), | |
| token, | |
| ) | |
| async def privacy_policy(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish( | |
| request, | |
| _information_page( | |
| "AUTOSLASH PRIVACY POLICY", | |
| ( | |
| "The offline clone stores submitted synthetic review data only in its " | |
| "site-bound local database.", | |
| "No source-site, email, analytics, advertising, or payment request is sent.", | |
| ), | |
| "privacy", | |
| ), | |
| token, | |
| ) | |
| async def terms_of_use(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish( | |
| request, | |
| _information_page( | |
| "Site Terms and Conditions of Use", | |
| ( | |
| "This offline implementation reproduces the public review surface.", | |
| "It does not book, cancel, rebook, charge, or contact a real service.", | |
| ), | |
| "terms", | |
| ), | |
| token, | |
| ) | |
| async def coupon_detail( | |
| request: Request, company: str, coupon_id: str, slug: str | |
| ) -> Response: | |
| _, token = _owner(request) | |
| title = slug.replace("-", " ").title() | |
| return _finish( | |
| request, | |
| _information_page( | |
| title, | |
| ( | |
| f"{company.title()} coupon code: {coupon_id.upper()}", | |
| "Use Get a Quote to include eligible discounts. This page does not " | |
| "contact a rental company.", | |
| ), | |
| "coupon-detail", | |
| ), | |
| token, | |
| ) | |
| async def external_link(request: Request, destination: str = "external") -> Response: | |
| _, token = _owner(request) | |
| return _finish( | |
| request, | |
| _information_page( | |
| "External link", | |
| ( | |
| f"{destination.title()} is outside the offline AutoSlash clone.", | |
| "Runtime network access is disabled, so this destination was not opened.", | |
| ), | |
| "external-link", | |
| ), | |
| token, | |
| ) | |
| async def sign_in_notice(request: Request) -> Response: | |
| _, token = _owner(request) | |
| return _finish( | |
| request, | |
| _information_page( | |
| "Reservation Lookup", | |
| ( | |
| "The verified anonymous source journey uses Trip ID and email lookup.", | |
| "No local password account is invented for this offline clone.", | |
| ), | |
| "reservation-lookup", | |
| ), | |
| token, | |
| ) | |
| async def session_summary(request: Request) -> Response: | |
| owner, token = _owner(request) | |
| with _backend().lifecycle.connection() as connection: | |
| quote_count = int( | |
| connection.execute( | |
| "SELECT COUNT(*) FROM autoslash_quote_requests WHERE owner_id=?", | |
| (owner,), | |
| ).fetchone()[0] | |
| ) | |
| tracking_count = int( | |
| connection.execute( | |
| "SELECT COUNT(*) FROM autoslash_tracking_requests WHERE owner_id=?", | |
| (owner,), | |
| ).fetchone()[0] | |
| ) | |
| response = JSONResponse( | |
| {"site_id": SITE_ID, "quote_requests": quote_count, | |
| "tracking_requests": tracking_count} | |
| ) | |
| return _finish(request, response, token) | |
| async def not_found(request: Request, path: str) -> Response: | |
| del path | |
| _, token = _owner(request) | |
| body = """<main class="not-found"><div> | |
| <img class="not-found-car" src="/static/site/assets/car-facing-right-lg@2x.png" alt=""> | |
| <h1>Page Not Found</h1> | |
| <p>We're sorry, this page no longer exists.</p> | |
| <p>Please visit our <a href="/">home page</a> if you are not redirected in 5 seconds.</p> | |
| </div></main>""" | |
| return _finish( | |
| request, _document("Page not found", "not-found", body, status_code=404), token | |
| ) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run( | |
| app, | |
| host=os.environ.get("HOST", "127.0.0.1"), | |
| port=int(os.environ.get("PORT", "3000")), | |
| log_level="warning", | |
| ) | |