No description
  • Python 99.9%
  • Mako 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-10-16 22:01:25 +02:00
src/eurocrap Fix double trains joining in Brussels 2026-10-16 22:01:25 +02:00
tests Fix double trains joining in Brussels 2026-10-16 22:01:25 +02:00
.env.example docs: finish persistence operations 2026-08-24 22:18:52 +02:00
.gitignore Track gitignore 2026-08-20 22:35:50 +02:00
eurocrap.example.toml docs: finish persistence operations 2026-08-24 22:18:52 +02:00
pyproject.toml feat: add database configuration 2026-08-24 18:48:00 +02:00
README.md Intensive checks right before departure. Fix #4 2026-09-25 21:16:01 +02:00
uv.lock feat: add database configuration 2026-08-24 18:48:00 +02:00

eurocrap

Look up a Eurostar service by date and train number.

A small Python app (src layout) with one CLI, eurocrap, dispatching to a few modules under src/eurocrap/ (the data sources live under eurocrap.providers.<kind>.<operator>):

  • eurocrap.providers.gtfs — GTFS / GTFS-RT providers behind one abstract base (GtfsProvider): the join/lookup logic is shared, each provider only supplies the feeds.

    • .eurostar — the official open data. Pulls the static GTFS timetable and the GTFS-RT TripUpdates feed published by Eurostar on transport.data.gouv.fr, caches them on disk, and joins the scheduled stops for a service with its realtime overlay (per-stop delays, expected times, assigned platform/track, cancellations). No antibot/WAF.
    • .nl — the Dutch national feed (openOV / OVapi: gtfs.ovapi.nl static + gtfs.openov.nl/gtfs-rt/trainUpdates.pb), which carries the Eurostar services running through the Netherlands (Amsterdam ⇄ London / Paris / Marne-la-Vallée, agency IFF:NS_INT). The national stop_times.txt is ~1 GB, so the provider filters the feed to its Eurostar routes while loading, then reuses the same machinery. A different realtime source, so it often shows a different live picture than .eurostar.

    eurocrap gtfs queries all available providers and prints each result, collapsing ones that agree; --provider eurostar|nl restricts to one.

  • eurocrap.providers.scrape — page-scraping providers, behind eurocrap scrape. Unlike gtfs's providers they don't share a result shape, so nothing is merged/diffed — each requested provider just prints its own [name]-prefixed section.

    • .eurostar — curl_cffi with TLS/JA3 impersonation, no browser. Parses the server-rendered __NEXT_DATA__ blob from the public timetable page (which honours ?date=YYYY-MM-DD), avoiding the WAF-protected JSON API. Returns the service status and the per-stop schedule with realtime times (scheduled vs expected arrival/departure, per-stop delays and cancellations) scraped from the page. Override the impersonation target with EUROSTAR_IMPERSONATE=chrome131 if needed.
    • .sncf — same curl_cffi impersonation approach, against the Gares & Connexions live departures/arrivals board for Paris Nord (garesetconnexions.sncf, DataDome), falling back to the TER live board (ter.sncf.com, Cloudflare — a different antibot vendor) if blocked. Unlike .eurostar, this board reports only one station's worth of realtime info per train — platform, delay and actual time — not the whole journey, so it's shown only on the stop that is Paris Nord. It also only ever has data for today (no date parameter on either board), so it's silently skipped for any other date or a route that doesn't touch Paris Nord. Override the impersonation target with SNCF_IMPERSONATE=chrome131 if needed.
    • .irail — keyless iRail live boards for Belgian stops (UIC codes starting 88) on today's EUR service. It requests arrival and departure boards at most 3 times/s, caches them for 30 s, and uses stale cached data when iRail rate-limits or has a transient network failure.
    • .db — bahnhof.de arrival and departure boards for German stops (UIC/EVA codes starting 80) on today's Eurostar service. It dynamically discovers the site's current live-board action, then reports delays, cancellations, and platforms for matching stations.
  • eurocrap.scheduler — an APScheduler job that periodically fetches a configured iCal feed, finds the Eurostar train events in it (extracting each train number from the event details), and schedules a one-shot check one hour before departure that reports the train's situation from both gtfs and scrape. Configured with pydantic-settings (env / .env / eurocrap.toml). Optional scheduler extra.

Install with uv

uv sync                      # gtfs + scrape modules
uv sync --extra scheduler    # + the iCal scheduler

No project checkout? Run a module straight from a one-off env:

uv run --with gtfs-realtime-bindings python -m eurocrap gtfs 9007 2026-06-20
uv run --with curl_cffi --with gtfs-realtime-bindings python -m eurocrap scrape 9007 2026-06-20

Usage

# One CLI, sub-commands (also: `python -m eurocrap ...`). All take <train_number> <day>.
eurocrap gtfs   9381 2026-06-16                      # all GTFS providers; shows diffs
eurocrap gtfs   9381 2026-06-16 --provider nl        # just the Dutch feed
eurocrap gtfs   9117 2026-06-13 --json
eurocrap gtfs   9117 2026-06-13 --refresh            # bypass the on-disk cache
eurocrap scrape 9007 2026-06-20                      # all applicable scrape providers
eurocrap scrape 9117 2026-06-20 --json
eurocrap scrape 9007 2026-06-20 --provider sncf      # just the Paris Nord live board
eurocrap scrape 9007 $(date +%F) --provider irail    # Belgian iRail live boards
eurocrap scrape 9414 $(date +%F) --provider db       # German bahnhof.de live boards
eurocrap scrape 9007 2026-06-20 --provider eurostar --provider sncf

# Per-command console scripts also exist:
eurocrap-gtfs 9117 2026-06-13                     # all providers
eurocrap-gtfs 9381 2026-06-16 --provider nl       # Dutch national feed only

scrape's eurostar provider derives the route (the origin/destination UIC codes the timetable page needs) from the train number via the static GTFS — the train's first and last scheduled stops — so it takes only the train number and date. The resolved route is shown in the header line (as route_long_name), matching gtfs. Its sncf provider is skipped automatically (not an error) unless <date> is today and the route touches Paris Nord; pass --provider sncf on a train/date that doesn't qualify to see why it was skipped. Its irail and db providers follow the same today-only rule and only query Belgian or German stations present in the Eurostar GTFS route.

Scheduler (serve)

Database setup

On first run, install the scheduler dependencies and create the database schema:

uv sync --extra scheduler
eurocrap db upgrade

For an existing installation, import its old cache files once, then verify the database before starting the service:

eurocrap db import-legacy
eurocrap db check
eurocrap serve

The default database is $XDG_DATA_HOME/eurocrap/eurocrap.sqlite3 (normally ~/.local/share/eurocrap/eurocrap.sqlite3). The legacy files under $XDG_CACHE_HOME/eurocrap (normally ~/.cache/eurocrap) remain untouched by the import. The database owns tracked trips, manual state, resolved train numbers, notification status-change history, and delivery state; it does not retain raw iCalendar files.

At startup, stored trips are loaded and their checks are armed before the first network refresh. If a later feed refresh fails, the last committed snapshot is kept.

Back up the SQLite database for tracked-trip and notification state. GTFS downloads in the cache can be fetched again. While the database is live in WAL mode, use SQLite's online backup command instead of copying only the main database file:

sqlite3 "${XDG_DATA_HOME:-$HOME/.local/share}/eurocrap/eurocrap.sqlite3" ".backup /path/to/eurocrap.sqlite3"

For a stopped service, run sqlite3 eurocrap.sqlite3 "PRAGMA wal_checkpoint(TRUNCATE);" before copying the database. Restore by stopping the service and replacing the database with that copy, then run eurocrap db check. Exclude GTFS caches from backups: delete $EUROCRAP_CACHE_DIR to rebuild them. Retired gtfs_sncb_static.zip and gtfs_sncb_rt.pb cache files are unused and may be removed manually.

To inspect old notification history, run the safe dry run below; append --yes only when ready to delete matching rows:

eurocrap maintenance purge-history --older-than 30d
eurocrap maintenance purge-history --older-than 30d --yes
eurocrap serve            # loop: refresh feed, schedule checks, serve web UI
eurocrap serve --once     # fetch once, list matched train events, exit
eurocrap serve --ical-url https://… --interval 15   # ad-hoc overrides
eurocrap serve --host 0.0.0.0 --port 8080           # web UI bind (default 127.0.0.1:8080)
eurocrap serve --include-past                       # also keep past trips
eurocrap serve --window-days 30                     # only events within 30 days

By default only future trips are kept (parsed, scheduled, and listed); pass --include-past (or set include_past = true) to include past trips too. Only events departing within window_days (default 89) are parsed at all.

Note: the scheduler only looks at trips within the next 89 days (window_days, the GTFS cutoff — just inside Eurostar's rolling ~90-day GTFS window). Eurostar's GTFS is a rolling ~90-day window, so trips further out can't be resolved against the schedule (status, route, per-train detail) anyway — they'd fall back to slow per-event booking lookups and have no GTFS detail page. Trips beyond the window are simply skipped.

Notification status changes and delivery outcomes are stored in the database. Failed deliveries retry for up to 24 hours after the status change. Delivery is at-least-once: if the process crashes after a provider accepts a message but before its delivery row is marked sent, the retry can send a duplicate. Delivery rows store only their channel; email and SMS destinations come from current notification configuration, so changing settings also changes where pending deliveries go.

While running, it also serves a minimal web UI (bottle):

  • / — upcoming trips from the iCal feed: train number (linking to its detail page), departure/arrival times, current status (from GTFS), and — in the status cell — the trains immediately before (↑) and after (↓) on the same route, with their times and status.
  • /<day>/<train_number> — full per-stop detail for that train on that day (GTFS schedule + realtime), e.g. /2026-06-15/9393, plus an adjacent trains table (the train before/after on the same corridor) at the bottom.

The "train before / after" is the service that passes the same start station before/after this one and also serves the same end station — i.e. the neighbouring departure on the corridor — looked up from GTFS + GTFS-RT.

On each refresh it scans the feed for Eurostar trips, pulls the train number out of each event (e.g. EUROSTAR 9368 in the description), and schedules a one-shot job 1 h before departure. That job looks the train up via both gtfs and scrape and logs the situation — see the TODO(notification) in scheduler.py:check_train to plug in real alerting. When an event has no train number in its text (some, e.g. eurostar.com entries, carry only a booking reference), the number is recovered from the GTFS by matching the route + departure time and, failing that, from the booking itself: eurocrap.booking does a two-step gateway fetch — GET the customer-dashboard page for the PNR to read the short-lived Bearer token from its __NEXT_DATA__, then POST the bookingBySession GraphQL query to site-api.eurostar.com/gateway (via the stealth curl_cffi client) for the booking's legs. Anything still unresolved is skipped.

A resolved train number is stored with its tracked trip, so an unchanged event isn't re-resolved on the next refresh — the GTFS match and (especially) the booking-page scrape only run when an event is new or changed (e.g. rebooked). Live status, however, is recomputed from GTFS every refresh.

Notifications

Get notified when a trip is cancelled / delayed / not scheduled (on first sighting, including the scheduler's first run) or whenever a trip's status changes between refreshes. Two independent channels:

  • Email — set notify_email (env EUROCRAP_NOTIFY_EMAIL). Sent through the system's sendmail (the MTA mail uses), no SMTP config needed.
  • SMS — set notify_sms_user + notify_sms_apikey (your Free Mobile account ID and API key). Sent via the Free Mobile SMS API.

Enable either, both, or neither. The database retains status history and delivery state, so restarts don't re-send unchanged alerts. A legacy $EUROCRAP_CACHE_DIR/notify_state.json is only an input to eurocrap db import-legacy; runtime notifications do not read it.

One hour before departure, a separate summary covers the tracked train and its immediately previous/next trains on the same corridor, including scheduled and expected departure, delay and platform where available. Until expected arrival, GTFS status updates run every minute; Eurostar timetable scraping runs every train_check_interval_minutes (default 5), only for tracked trains. Changed scraped departure delays generate alerts unless GTFS already reports that delay. Manual additions receive the same monitoring. Unlike GTFS status-change alerts, the pre-departure summary and scraped-delay alerts are sent directly: delivery failures are logged, not queued for retry, and scraped-delay baselines are reset on restart.

Configuration

Configure the feed URL and interval (no flags needed) via any of, in decreasing precedence: environment variables, a .env file, or a TOML config file. Copy .env.example → .env or eurocrap.example.toml → eurocrap.toml:

# eurocrap.toml
ical_url = "https://example.com/calendar.ics"
fetch_interval_minutes = 30
train_check_interval_minutes = 5
# or via the environment / .env (note the EUROCRAP_ prefix)
EUROCRAP_ICAL_URL=https://example.com/calendar.ics
EUROCRAP_FETCH_INTERVAL_MINUTES=30
EUROCRAP_TRAIN_CHECK_INTERVAL_MINUTES=5

Point EUROCRAP_CONFIG at a different TOML path if you don't want ./eurocrap.toml. Set data_dir / EUROCRAP_DATA_DIR to move the default SQLite database, or database_url / EUROCRAP_DATABASE_URL to use another database. Set cache_dir / EUROCRAP_CACHE_DIR to move GTFS downloads and other cached feed data; it does not hold runtime notification state.

Operations and security

Use mode 0700 for configuration and data directories, and mode 0600 for the config, .env, and SQLite files where supported. Rotate any calendar, database, notification, or other credentials exposed during the persistence audit. Scheduler logs redact calendar URL userinfo, query strings, and fragments; do not put database URLs with credentials in logs or support reports.

Keep the web UI bound to loopback unless a reverse proxy protects it. Any public route that mutates state must require reverse-proxy authentication and CSRF protection.

As a library

from eurocrap.providers.gtfs.eurostar import lookup_train

trip = lookup_train("2026-06-13", "9117")  # -> TripResult
for stop in trip.stops:
    print(stop.stop_name, stop.scheduled_departure, stop.expected_departure)

lookup_train(day, train_number) returns a TripResult (route, per-stop schedule, and the realtime overlay). Feeds are cached under $EUROCRAP_CACHE_DIR (default $XDG_CACHE_HOME/eurocrap, i.e. ~/.cache/eurocrap); static feed ~6 h TTL, realtime ~30 s.

Exit codes (scraping commands): 0 match, 1 network error, 2 antibot block, 3 train not found. The gtfs command uses 0/1/3 (no antibot).

Development

uv sync --extra scheduler   # all deps incl. the dev group (ruff, mypy, pytest)
uv run ruff check src tests
uv run mypy
uv run pytest               # the unit-test suite under tests/

The test suite (tests/) is fully offline and deterministic: a synthetic in-memory GTFS zip + GTFS-RT protobuf stand in for the live feeds, and every network call (downloads, scraping, sendmail, SMS, the booking gateway) is monkeypatched. Run it before/after changes as the consolidated regression check.