403 lines
20 KiB
Python
403 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only EFA queries. Python 3.10+, standard library, no credentials."""
|
|
import argparse
|
|
import html
|
|
import json
|
|
import re
|
|
import sys
|
|
from datetime import datetime, timedelta
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import urlencode
|
|
from urllib.request import Request, urlopen
|
|
from zoneinfo import ZoneInfo
|
|
|
|
BASE = "https://www.efa.de/efa/"
|
|
BERLIN = ZoneInfo("Europe/Berlin")
|
|
KNOWN = {"rastatt": "de:08216:1844", "rastatt bahnhof": "de:08216:1844",
|
|
"karlsruhe": "de:08212:90", "karlsruhe hbf": "de:08212:90", "karlsruhe hauptbahnhof": "de:08212:90"}
|
|
REQUEST_WARNINGS = []
|
|
|
|
|
|
class EfaError(Exception):
|
|
pass
|
|
|
|
|
|
def clean(value):
|
|
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]*>", " ", str(value or "")))).strip()
|
|
|
|
|
|
def iso(value):
|
|
if not value:
|
|
return None
|
|
try:
|
|
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
return dt.astimezone(BERLIN) if dt.tzinfo else None
|
|
except (ValueError, TypeError):
|
|
return None
|
|
|
|
|
|
def local(value):
|
|
dt = iso(value)
|
|
return dt.isoformat() if dt else None
|
|
|
|
|
|
def request(endpoint, params):
|
|
params = dict(params, outputFormat="rapidJSON", language="de")
|
|
url = BASE + endpoint + "?" + urlencode(params)
|
|
req = Request(url, headers={"Accept": "application/json", "User-Agent": "efa-bahn/1.0"})
|
|
try:
|
|
with urlopen(req, timeout=30) as response:
|
|
body = response.read(8 * 1024 * 1024 + 1)
|
|
if len(body) > 8 * 1024 * 1024:
|
|
raise EfaError("EFA-Antwort zu gross; Anfrage eingrenzen.")
|
|
data = json.loads(body)
|
|
except HTTPError as exc:
|
|
raise EfaError(f"EFA HTTP {exc.code}: {url}") from exc
|
|
except (URLError, TimeoutError, OSError, ValueError) as exc:
|
|
raise EfaError(f"EFA-Anfrage fehlgeschlagen: {exc}; URL: {url}") from exc
|
|
if not isinstance(data, dict):
|
|
raise EfaError("Unerwartetes EFA-Antwortformat.")
|
|
errors = [m for m in data.get("systemMessages", [])
|
|
if isinstance(m, dict) and str(m.get("type", "")).lower() in ("error", "fatal")]
|
|
if errors:
|
|
# A failed broker sub-provider can coexist with valid stop results.
|
|
# Only tolerate the observed STOPFINDER/-8011 case, never general errors.
|
|
partial = (endpoint == "XML_STOPFINDER_REQUEST" and data.get("locations")
|
|
and all(m.get("module") == "BROKER" and str(m.get("code")) == "-8011" for m in errors))
|
|
if partial:
|
|
REQUEST_WARNINGS.append({"endpoint": endpoint, "messages": errors,
|
|
"note": "Partial station-search response; usable locations returned, search may be incomplete."})
|
|
else:
|
|
raise EfaError("EFA systemMessages: " + json.dumps(errors, ensure_ascii=False))
|
|
return data
|
|
|
|
|
|
def stops(name):
|
|
data = request("XML_STOPFINDER_REQUEST", {"commonMacro": "stopfinder", "type_sf": "stop", "name_sf": name})
|
|
return [{"id": x.get("id"), "name": x.get("name"),
|
|
"place": (x.get("parent") or {}).get("name"), "is_best": x.get("isBest", False)}
|
|
for x in data.get("locations", []) if x.get("id")]
|
|
|
|
|
|
def station(name):
|
|
if name.lower() in KNOWN:
|
|
return {"id": KNOWN[name.lower()], "name": name}
|
|
if name.startswith("de:") or name.isdigit():
|
|
return {"id": name, "name": name}
|
|
# For a train request a bare city means its main station. Preserve explicit
|
|
# station names; never silently pick a forecourt or a different station.
|
|
query = name if re.search(r"\b(hbf|hauptbahnhof|bahnhof|bf)\b", name, re.I) else name + " Hauptbahnhof"
|
|
query = re.sub(r"\bhbf\b", "Hauptbahnhof", query, flags=re.I)
|
|
options = stops(query)
|
|
if not options:
|
|
raise EfaError(f"Bahnhof nicht gefunden: {name}")
|
|
normalize = lambda s: re.sub(r"\s+", " ", re.sub(r"[,()]", " ", str(s))).strip().casefold()
|
|
exact = [x for x in options if normalize(x["name"]) == normalize(query)]
|
|
if len(exact) == 1:
|
|
return exact[0]
|
|
if len(options) == 1:
|
|
return options[0]
|
|
# Do not silently choose a forecourt, underground station or another locality.
|
|
raise EfaError("Bahnhof mehrdeutig; passende ID mit 'stops' ermitteln: "
|
|
+ json.dumps(options[:10], ensure_ascii=False))
|
|
|
|
|
|
def messages(items):
|
|
result = []
|
|
for item in items or []:
|
|
links = item.get("infoLinks") or []
|
|
if not links:
|
|
links = [{"title": item.get("title"), "content": item.get("content")}]
|
|
for link in links:
|
|
result.append({"id": item.get("id"), "title": clean(link.get("title") or link.get("urlText")),
|
|
"text": clean(link.get("content")), "url": link.get("url"),
|
|
"validity": (item.get("timestamps") or {}).get("validity", []),
|
|
"additional_links": link.get("additionalLinks", [])})
|
|
return result
|
|
|
|
|
|
def normalized_platform(value):
|
|
return re.sub(r"^(gleis|bstg\.?|bahnsteig|platform|track)\s*", "", str(value or "").strip(), flags=re.I).casefold()
|
|
|
|
|
|
def status(raw, point, prefix):
|
|
props = point.get("properties") or {}
|
|
statuses = list(raw.get("realtimeStatus") or []) + list(props.get("realtimeStatus") or [])
|
|
cancelled = raw.get("isCancelled")
|
|
point_cancel = "DEPARTURE_CANCELLED" if prefix == "departure" else "ARRIVAL_CANCELLED"
|
|
if point_cancel in statuses or point.get("isCancelled") is True:
|
|
cancelled = True
|
|
planned = point.get(prefix + "TimePlanned")
|
|
estimated = point.get(prefix + "TimeEstimated")
|
|
p, e = iso(planned), iso(estimated)
|
|
monitored = raw.get("isRealtimeControlled", point.get("isRealtimeControlled"))
|
|
realtime_confirmed = monitored is True or "MONITORED" in statuses
|
|
# EFA may copy tomorrow's scheduled time into the estimated field. Do not
|
|
# turn that fallback into an assertion of punctuality.
|
|
delay = round((e - p).total_seconds() / 60) if p and e and realtime_confirmed else None
|
|
reported = props.get("platformName")
|
|
scheduled = props.get("plannedPlatformName")
|
|
different = bool(reported and scheduled and normalized_platform(reported) != normalized_platform(scheduled))
|
|
flag = (raw.get("properties") or {}).get("platformChange") == "changed"
|
|
return {"planned": local(planned), "estimated": local(estimated) if realtime_confirmed else None,
|
|
"estimated_unconfirmed": local(estimated) if not realtime_confirmed else None,
|
|
"delay_minutes": delay, "realtime_confirmed": realtime_confirmed,
|
|
"is_realtime_controlled": monitored,
|
|
"cancelled": cancelled if isinstance(cancelled, bool) else None,
|
|
"cancellation_scope": "this_stop_or_departure" if cancelled is True else None,
|
|
"platform_planned": scheduled, "platform_reported": reported,
|
|
"platform_changed": True if different or flag else (False if reported and scheduled else None),
|
|
"realtime_status": statuses}
|
|
|
|
|
|
def transport(raw):
|
|
t = raw.get("transportation") or {}
|
|
props = t.get("properties") or {}
|
|
return {"name": t.get("name"), "line": t.get("number"),
|
|
"train_type": props.get("trainType"), "train_number": props.get("trainNumber"),
|
|
"direction": (t.get("destination") or {}).get("name"),
|
|
"product": (t.get("product") or {}).get("name")}
|
|
|
|
|
|
def board(stop, when, limit=10, train=None):
|
|
data = request("XML_DM_REQUEST", {"commonMacro": "dm", "type_dm": "any", "name_dm": stop["id"],
|
|
"mode": "direct", "useRealtime": 1, "limit": 200,
|
|
"itdDate": when.strftime("%Y%m%d"), "itdTime": when.strftime("%H%M")})
|
|
result = []
|
|
for event in data.get("stopEvents", []):
|
|
info = transport(event)
|
|
if train and re.sub(r"\s+", "", train).casefold() not in {
|
|
re.sub(r"\s+", "", str(info.get(k) or "")).casefold()
|
|
for k in ("train_number", "line", "name")}:
|
|
continue
|
|
planned = iso(event.get("departureTimePlanned"))
|
|
if not planned or planned < when:
|
|
continue
|
|
point = dict(event.get("location") or {})
|
|
point.update({k: v for k, v in event.items() if k.startswith("departureTime")})
|
|
result.append(dict(info, station=point.get("name"),
|
|
departure=status(event, point, "departure"),
|
|
hints=[clean(h.get("content")) for h in event.get("hints", [])],
|
|
messages=messages(event.get("infos"))))
|
|
result.sort(key=lambda x: x["departure"]["planned"])
|
|
return result[:limit]
|
|
|
|
|
|
def journeys(origin, destination, when, limit, regional):
|
|
data = request("XML_TRIP_REQUEST2", {"commonMacro": "trip", "type_origin": "any", "name_origin": origin["id"],
|
|
"type_destination": "any", "name_destination": destination["id"],
|
|
"itdDate": when.strftime("%Y%m%d"), "itdTime": when.strftime("%H%M"),
|
|
"itdTripDateTimeDepArr": "dep", "useRealtime": 1})
|
|
result = []
|
|
for journey in data.get("journeys", []):
|
|
raw_legs = journey.get("legs") or []
|
|
if not raw_legs:
|
|
continue
|
|
legs = []
|
|
for leg in raw_legs:
|
|
start, end = leg.get("origin") or {}, leg.get("destination") or {}
|
|
legs.append(dict(transport(leg), origin=start.get("name"), destination=end.get("name"),
|
|
departure=status(leg, start, "departure"), arrival=status(leg, end, "arrival"),
|
|
hints=[clean(h.get("content")) for h in leg.get("hints", [])],
|
|
messages=messages(leg.get("infos"))))
|
|
# Walking legs may have no train type. Inspect every motorised leg.
|
|
if regional and any(((x["train_type"] or "").upper() in {"ICE", "IC", "EC", "ECE", "TGV", "RJ", "RJX", "NJ", "EN", "FLX"}
|
|
and not re.match(r"^(RE|RB|S)\s*\d", str(x["line"] or ""), re.I))
|
|
or (r.get("transportation") or {}).get("product", {}).get("class") == 16
|
|
for x, r in zip(legs, raw_legs)):
|
|
continue
|
|
dep = iso(legs[0]["departure"]["planned"])
|
|
arr = iso(legs[-1]["arrival"]["planned"])
|
|
if not dep or dep < when or not arr or arr < dep:
|
|
continue
|
|
result.append({"departure_planned": dep.isoformat(), "arrival_planned": arr.isoformat(),
|
|
"duration_minutes": round((arr - dep).total_seconds() / 60),
|
|
"interchanges": journey.get("interchanges"), "legs": legs,
|
|
"messages": messages(journey.get("infos"))})
|
|
result.sort(key=lambda x: x["departure_planned"])
|
|
return result[:limit]
|
|
|
|
|
|
def alerts(query, when, limit):
|
|
data = request("XML_ADDINFO_REQUEST", {"commonMacro": "addinfo", "filterPublicationStatus": "current"})
|
|
info = data.get("infos") or {}
|
|
if not isinstance(info, dict):
|
|
raise EfaError("Unerwartetes EFA-Meldungsformat.")
|
|
result = []
|
|
for item in info.get("current", []):
|
|
affected = item.get("affected") or {}
|
|
# Exclude metadata and IDs from free-text matching.
|
|
searchable = " ".join([clean(x.get("title")) + " " + clean(x.get("content")) for x in item.get("infoLinks", [])]
|
|
+ [clean(x.get("name")) for x in affected.get("lines", []) + affected.get("stops", [])])
|
|
if query.casefold() not in searchable.casefold():
|
|
continue
|
|
periods = (item.get("timestamps") or {}).get("validity") or []
|
|
relevant = not periods or any((not iso(p.get("from")) or iso(p.get("from")) <= when)
|
|
and (not iso(p.get("to")) or iso(p.get("to")) >= when) for p in periods)
|
|
if not relevant:
|
|
continue
|
|
result.append({"id": item.get("id"), "messages": messages([item]),
|
|
"affected_lines": [{"name": x.get("name"), "id": x.get("id")} for x in affected.get("lines", [])],
|
|
"affected_stops": [{"name": x.get("name"), "id": x.get("id")} for x in affected.get("stops", [])]})
|
|
return {"matches": result[:limit], "matching_count": len(result),
|
|
"coverage": "Only messages published by this EFA endpoint. Text may specify additional dates/times."}
|
|
|
|
|
|
def when_from(args):
|
|
now = datetime.now(BERLIN)
|
|
day = now.date() if args.date == "today" else ((now + timedelta(days=1)).date() if args.date == "tomorrow"
|
|
else datetime.strptime(args.date, "%Y-%m-%d").date())
|
|
clock = datetime.strptime(args.time or now.strftime("%H:%M"), "%H:%M").time()
|
|
return datetime.combine(day, clock, BERLIN)
|
|
|
|
|
|
WEEKDAYS = ("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag")
|
|
|
|
|
|
def date_label(value):
|
|
dt = iso(value)
|
|
return f"{WEEKDAYS[dt.weekday()]}, {dt:%d.%m.%Y}" if dt else "Datum unbekannt"
|
|
|
|
|
|
def time_label(value):
|
|
dt = iso(value)
|
|
return dt.strftime("%H:%M") if dt else "unbekannt"
|
|
|
|
|
|
def status_text(value):
|
|
parts = []
|
|
if value.get("cancelled") is True:
|
|
parts.append("AUSFALL an diesem Halt/Abschnitt")
|
|
if value.get("estimated"):
|
|
parts.append("Prognose " + time_label(value["estimated"]))
|
|
if value.get("delay_minutes") is not None:
|
|
parts.append(f"Verspätung {value['delay_minutes']:+d} Min.")
|
|
if value.get("platform_changed"):
|
|
parts.append(f"Gleisänderung: gemeldet {value.get('platform_reported') or 'unbekannt'}, "
|
|
f"geplant {value.get('platform_planned') or 'unbekannt'}")
|
|
else:
|
|
platform = value.get("platform_planned") or value.get("platform_reported")
|
|
if platform:
|
|
label = str(platform) if re.match(r"^gleis\b", str(platform), re.I) else f"Gleis {platform}"
|
|
parts.append(f"{label} ({'geplant' if value.get('platform_planned') else 'gemeldet'})")
|
|
if not value.get("realtime_confirmed"):
|
|
parts.append("keine bestätigten Echtzeitdaten")
|
|
return "; ".join(parts)
|
|
|
|
|
|
def message_lines(items):
|
|
return ["Meldung: " + ": ".join(str(m[k]) for k in ("title", "text") if m.get(k))
|
|
for m in items or []]
|
|
|
|
|
|
def render_text(output):
|
|
"""Deterministic facts for small models; no additional network calls."""
|
|
if not output["ok"]:
|
|
return "EFA-Abfrage fehlgeschlagen: " + output["error"]
|
|
lines = ["Quelle: EFA | Abfrage: " + str(output["queried_at"])]
|
|
if output.get("requested_from"):
|
|
lines.append("Gesucht ab: " + date_label(output["requested_from"]) + " "
|
|
+ time_label(output["requested_from"]) + " (Europe/Berlin)")
|
|
if "journeys" in output:
|
|
if not output["journeys"]:
|
|
lines.append("Keine passende Verbindung in den gelieferten Ergebnissen gefunden.")
|
|
for i, journey in enumerate(output["journeys"], 1):
|
|
transfers = journey.get("interchanges")
|
|
lines.append(f"Verbindung {i}: {time_label(journey['departure_planned'])} → "
|
|
f"{time_label(journey['arrival_planned'])}, {journey['duration_minutes']} Min., "
|
|
+ (f"{transfers} Umstiege" if transfers is not None else "Umstiege unbekannt"))
|
|
for leg in journey["legs"]:
|
|
name = leg.get("name") or leg.get("line") or leg.get("product") or "Abschnitt"
|
|
number = leg.get("train_number")
|
|
lines.append(f" {name}" + (f" (Zug {number})" if number else "")
|
|
+ (f", Richtung {leg['direction']}" if leg.get("direction") else ""))
|
|
lines.append(f" {leg['origin']} {time_label(leg['departure']['planned'])} → "
|
|
f"{leg['destination']} {time_label(leg['arrival']['planned'])} (Fahrplan)")
|
|
lines.append(" Abfahrt: " + status_text(leg["departure"]))
|
|
lines.append(" Ankunft: " + status_text(leg["arrival"]))
|
|
lines.extend(" " + line for line in message_lines(leg.get("messages")))
|
|
lines.extend(" Hinweis: " + h for h in leg.get("hints", []) if h)
|
|
lines.extend(message_lines(journey.get("messages")))
|
|
if "departures" in output:
|
|
if not output["departures"]:
|
|
lines.append("Keine passende Abfahrt in den gelieferten Ergebnissen gefunden.")
|
|
for event in output["departures"]:
|
|
lines.append(f"{event.get('name') or event.get('line') or 'Zug'} "
|
|
f"(Zug {event.get('train_number') or 'unbekannt'}), "
|
|
f"Richtung {event.get('direction') or 'unbekannt'}: "
|
|
f"{time_label(event['departure']['planned'])} (Fahrplan); "
|
|
+ status_text(event["departure"]))
|
|
lines.extend(message_lines(event.get("messages")))
|
|
lines.extend("Hinweis: " + h for h in event.get("hints", []) if h)
|
|
if "stops" in output:
|
|
lines.extend(f"{x['id']}: {x['name']}" for x in output["stops"])
|
|
if not output["stops"]:
|
|
lines.append("Keine Bahnhofstreffer gefunden.")
|
|
if "alerts" in output:
|
|
found = output["alerts"]
|
|
lines.append(f"Passende Meldungen: {found['matching_count']} (angezeigt: {len(found['matches'])})")
|
|
for item in found["matches"]:
|
|
lines.extend(message_lines(item["messages"]))
|
|
for m in item["messages"]:
|
|
if m.get("validity"):
|
|
lines.append("Gültigkeitszeiträume: " + json.dumps(m["validity"], ensure_ascii=False))
|
|
if m.get("url"):
|
|
lines.append("Link: " + m["url"])
|
|
lines.append("Meldungsabdeckung unvollständig/unbestätigt. Keine Treffer schließen Baustellen oder Störungen NICHT aus. Zeitfenster im Meldungstext prüfen.")
|
|
if output.get("source_warnings"):
|
|
lines.append("Quellenhinweis: Stationssuche lieferte gültige Treffer mit Teilfehler; Trefferliste möglicherweise unvollständig.")
|
|
lines.append("Fehlende Echtzeitdaten bedeuten nicht pünktlich, verkehrend oder störungsfrei. Keine zusätzlichen Angaben zu Tickets oder Fahrradmitnahme ableiten.")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
p = sub.add_parser("stops", help="Resolve station names; choose an ID if ambiguous")
|
|
p.add_argument("--query", required=True)
|
|
p.add_argument("--format", choices=("json", "text"), default="json")
|
|
for name in ("departures", "journeys", "alerts"):
|
|
p = sub.add_parser(name)
|
|
p.add_argument("--format", choices=("json", "text"), default="json")
|
|
p.add_argument("--date", default="today", help="today, tomorrow, YYYY-MM-DD")
|
|
p.add_argument("--time", help="Europe/Berlin HH:MM; default current local time")
|
|
p.add_argument("--limit", type=int, choices=range(1, 21), default=5, metavar="1..20")
|
|
if name == "departures":
|
|
p.add_argument("--station", required=True)
|
|
p.add_argument("--train", help="Optional exact train number or line, e.g. 4700 or RE2")
|
|
elif name == "journeys":
|
|
p.add_argument("--origin", required=True)
|
|
p.add_argument("--destination", required=True)
|
|
p.add_argument("--regional-only", action="store_true")
|
|
else:
|
|
p.add_argument("--query", required=True, help="Station, line or route fragment")
|
|
args = parser.parse_args()
|
|
output = {"ok": True, "source": BASE, "queried_at": datetime.now(BERLIN).isoformat(),
|
|
"warning": "Missing realtime data does not mean punctual, operating or disruption-free."}
|
|
try:
|
|
if args.command == "stops":
|
|
output["stops"] = stops(args.query)
|
|
else:
|
|
when = when_from(args)
|
|
output["requested_from"] = when.isoformat()
|
|
output["requested_date_label"] = date_label(when.isoformat())
|
|
if args.command == "departures":
|
|
stop = station(args.station)
|
|
output.update(station=stop, departures=board(stop, when, args.limit, args.train))
|
|
elif args.command == "journeys":
|
|
origin, dest = station(args.origin), station(args.destination)
|
|
output.update(origin=origin, destination=dest,
|
|
journeys=journeys(origin, dest, when, args.limit, args.regional_only))
|
|
else:
|
|
output["alerts"] = alerts(args.query, when, args.limit)
|
|
except (EfaError, ValueError) as exc:
|
|
output.update(ok=False, error=str(exc))
|
|
if REQUEST_WARNINGS:
|
|
output["source_warnings"] = REQUEST_WARNINGS
|
|
print(render_text(output) if args.format == "text" else json.dumps(output, ensure_ascii=False, indent=2))
|
|
return 0 if output["ok"] else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|