From 92825787880d7f86f4574b7d634895938d022743 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 19 Nov 2023 22:38:51 +0100 Subject: [PATCH 01/66] Structural changes --- .gitea/workflows/tests.yml | 34 ++++++++ .gitignore | 15 ++-- pyproject.toml | 69 ++++++++++++++++ requirements.txt => requirements/_.txt | 0 requirements/dev.txt | 12 +++ setup.cfg | 3 - setup.py | 36 -------- {pyrmv => src/pyrmv}/__init__.py | 2 +- {pyrmv => src/pyrmv}/classes/Board.py | 0 {pyrmv => src/pyrmv}/classes/Client.py | 0 {pyrmv => src/pyrmv}/classes/Gis.py | 0 {pyrmv => src/pyrmv}/classes/Journey.py | 0 {pyrmv => src/pyrmv}/classes/Leg.py | 0 {pyrmv => src/pyrmv}/classes/Message.py | 0 {pyrmv => src/pyrmv}/classes/Stop.py | 0 {pyrmv => src/pyrmv}/classes/Ticket.py | 0 {pyrmv => src/pyrmv}/classes/Trip.py | 0 {pyrmv => src/pyrmv}/classes/__init__.py | 0 {pyrmv => src/pyrmv}/const/__init__.py | 0 {pyrmv => src/pyrmv}/const/product.py | 0 {pyrmv => src/pyrmv}/enums/__init__.py | 0 .../pyrmv}/enums/aff_journey_mode.py | 0 .../pyrmv}/enums/aff_journey_stop_mode.py | 0 {pyrmv => src/pyrmv}/enums/auto_name.py | 0 {pyrmv => src/pyrmv}/enums/board_type.py | 0 {pyrmv => src/pyrmv}/enums/filter_mode.py | 0 {pyrmv => src/pyrmv}/enums/lang.py | 0 {pyrmv => src/pyrmv}/enums/location_type.py | 0 {pyrmv => src/pyrmv}/enums/product.py | 0 {pyrmv => src/pyrmv}/enums/rt_mode.py | 0 {pyrmv => src/pyrmv}/enums/search_mode.py | 0 {pyrmv => src/pyrmv}/enums/selection_mode.py | 0 {pyrmv => src/pyrmv}/errors/__init__.py | 0 {pyrmv => src/pyrmv}/errors/api_errors.py | 0 {pyrmv => src/pyrmv}/errors/int_errors.py | 0 {pyrmv => src/pyrmv}/errors/not_ready.py | 0 {pyrmv => src/pyrmv}/errors/ps_errors.py | 0 {pyrmv => src/pyrmv}/errors/sot_errors.py | 0 {pyrmv => src/pyrmv}/errors/svc_errors.py | 0 {pyrmv => src/pyrmv}/errors/unknown_error.py | 0 {pyrmv => src/pyrmv}/raw/__init__.py | 0 {pyrmv => src/pyrmv}/raw/board_arrival.py | 0 {pyrmv => src/pyrmv}/raw/board_departure.py | 0 {pyrmv => src/pyrmv}/raw/him_search.py | 0 {pyrmv => src/pyrmv}/raw/journey_detail.py | 0 {pyrmv => src/pyrmv}/raw/stop_by_coords.py | 0 {pyrmv => src/pyrmv}/raw/stop_by_name.py | 0 {pyrmv => src/pyrmv}/raw/trip_find.py | 0 {pyrmv => src/pyrmv}/raw/trip_recon.py | 0 {pyrmv => src/pyrmv}/utility/__init__.py | 0 .../pyrmv}/utility/find_exception.py | 0 .../pyrmv}/utility/weekdays_bitmask.py | 0 test.py | 82 ------------------- test_colors.py | 19 ----- tox.ini | 22 +++++ 55 files changed, 144 insertions(+), 150 deletions(-) create mode 100644 .gitea/workflows/tests.yml create mode 100644 pyproject.toml rename requirements.txt => requirements/_.txt (100%) create mode 100644 requirements/dev.txt delete mode 100644 setup.cfg delete mode 100644 setup.py rename {pyrmv => src/pyrmv}/__init__.py (97%) rename {pyrmv => src/pyrmv}/classes/Board.py (100%) rename {pyrmv => src/pyrmv}/classes/Client.py (100%) rename {pyrmv => src/pyrmv}/classes/Gis.py (100%) rename {pyrmv => src/pyrmv}/classes/Journey.py (100%) rename {pyrmv => src/pyrmv}/classes/Leg.py (100%) rename {pyrmv => src/pyrmv}/classes/Message.py (100%) rename {pyrmv => src/pyrmv}/classes/Stop.py (100%) rename {pyrmv => src/pyrmv}/classes/Ticket.py (100%) rename {pyrmv => src/pyrmv}/classes/Trip.py (100%) rename {pyrmv => src/pyrmv}/classes/__init__.py (100%) rename {pyrmv => src/pyrmv}/const/__init__.py (100%) rename {pyrmv => src/pyrmv}/const/product.py (100%) rename {pyrmv => src/pyrmv}/enums/__init__.py (100%) rename {pyrmv => src/pyrmv}/enums/aff_journey_mode.py (100%) rename {pyrmv => src/pyrmv}/enums/aff_journey_stop_mode.py (100%) rename {pyrmv => src/pyrmv}/enums/auto_name.py (100%) rename {pyrmv => src/pyrmv}/enums/board_type.py (100%) rename {pyrmv => src/pyrmv}/enums/filter_mode.py (100%) rename {pyrmv => src/pyrmv}/enums/lang.py (100%) rename {pyrmv => src/pyrmv}/enums/location_type.py (100%) rename {pyrmv => src/pyrmv}/enums/product.py (100%) rename {pyrmv => src/pyrmv}/enums/rt_mode.py (100%) rename {pyrmv => src/pyrmv}/enums/search_mode.py (100%) rename {pyrmv => src/pyrmv}/enums/selection_mode.py (100%) rename {pyrmv => src/pyrmv}/errors/__init__.py (100%) rename {pyrmv => src/pyrmv}/errors/api_errors.py (100%) rename {pyrmv => src/pyrmv}/errors/int_errors.py (100%) rename {pyrmv => src/pyrmv}/errors/not_ready.py (100%) rename {pyrmv => src/pyrmv}/errors/ps_errors.py (100%) rename {pyrmv => src/pyrmv}/errors/sot_errors.py (100%) rename {pyrmv => src/pyrmv}/errors/svc_errors.py (100%) rename {pyrmv => src/pyrmv}/errors/unknown_error.py (100%) rename {pyrmv => src/pyrmv}/raw/__init__.py (100%) rename {pyrmv => src/pyrmv}/raw/board_arrival.py (100%) rename {pyrmv => src/pyrmv}/raw/board_departure.py (100%) rename {pyrmv => src/pyrmv}/raw/him_search.py (100%) rename {pyrmv => src/pyrmv}/raw/journey_detail.py (100%) rename {pyrmv => src/pyrmv}/raw/stop_by_coords.py (100%) rename {pyrmv => src/pyrmv}/raw/stop_by_name.py (100%) rename {pyrmv => src/pyrmv}/raw/trip_find.py (100%) rename {pyrmv => src/pyrmv}/raw/trip_recon.py (100%) rename {pyrmv => src/pyrmv}/utility/__init__.py (100%) rename {pyrmv => src/pyrmv}/utility/find_exception.py (100%) rename {pyrmv => src/pyrmv}/utility/weekdays_bitmask.py (100%) delete mode 100644 test.py delete mode 100644 test_colors.py create mode 100644 tox.ini diff --git a/.gitea/workflows/tests.yml b/.gitea/workflows/tests.yml new file mode 100644 index 0000000..3bb6bde --- /dev/null +++ b/.gitea/workflows/tests.yml @@ -0,0 +1,34 @@ +name: Tests + +on: + push: + branches: + - dev + - main + tags-ignore: + - v* + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + container: catthehacker/ubuntu:act-latest + strategy: + matrix: + python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + env: + AGENT_TOOLSDIRECTORY: /opt/hostedtoolcache + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install tox tox-gh-actions + - name: Test with tox + run: tox + diff --git a/.gitignore b/.gitignore index 84e89d4..b34c603 100644 --- a/.gitignore +++ b/.gitignore @@ -154,12 +154,9 @@ cython_debug/ # Custom -.pypirc -tests -test.bat -test_key.json -build.* -cleanup.* -publish.* -publish-release.* -.vscode \ No newline at end of file +.vscode/ +.venv_linux/ +.venv_windows/ + +# Module-related +tests/output/ \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..4445954 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,69 @@ +[build-system] +requires = ["setuptools>=52.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "pyrmv" +dynamic = ["version", "dependencies", "optional-dependencies"] +authors = [{ name = "Profitroll", email = "profitroll@end-play.xyz" }] +maintainers = [{ name = "Profitroll", email = "profitroll@end-play.xyz" }] +description = "Small module that makes your journey with RMV REST API somehow easier." +readme = "README.md" +requires-python = ">=3.8" +license = { text = "GPL3" } +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Topic :: Software Development :: Libraries :: Python Modules", + "Topic :: Utilities", +] + +[project.urls] +Homepage = "https://git.end-play.xyz/profitroll/PythonRMV" +Source = "https://git.end-play.xyz/profitroll/PythonRMV" +Tracker = "https://git.end-play.xyz/profitroll/PythonRMV/issues" +Documentation = "https://git.end-play.xyz/profitroll/PythonRMV/wiki" + + +[tool.setuptools.dynamic] +version = { attr = "pyrmv.__version__" } +dependencies = { file = "requirements/_.txt" } + +[tool.setuptools.dynamic.optional-dependencies] +dev = { file = "requirements/dev.txt" } + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.black] +target-version = ['py38', 'py39', 'py310', 'py311'] + +[tool.isort] +profile = "black" + +[tool.pytest.ini_options] +minversion = "6.0" +python_files = ["test_*.py"] +pythonpath = "." +testpaths = ["tests"] + +[tool.mypy] +namespace_packages = true +install_types = true +strict = true +show_error_codes = true + +[tool.pylint.main] +extension-pkg-whitelist = ["ujson"] +py-version = 3.8 + +[tool.coverage.run] +source = ["libbot"] diff --git a/requirements.txt b/requirements/_.txt similarity index 100% rename from requirements.txt rename to requirements/_.txt diff --git a/requirements/dev.txt b/requirements/dev.txt new file mode 100644 index 0000000..4e999c4 --- /dev/null +++ b/requirements/dev.txt @@ -0,0 +1,12 @@ +black==23.11.0 +build==1.0.3 +isort==5.12.0 +mypy==1.7.0 +pylint==3.0.2 +pytest-asyncio==0.22.0 +pytest-cov==4.1.0 +pytest==7.4.3 +tox==4.11.3 +twine==4.0.2 +types-aiofiles==23.2.0.0 +types-ujson==5.8.0.1 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index fe869c8..0000000 --- a/setup.cfg +++ /dev/null @@ -1,3 +0,0 @@ -[metadata] -description_file=README.md -license_files=LICENSE \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 77cff13..0000000 --- a/setup.py +++ /dev/null @@ -1,36 +0,0 @@ -from setuptools import setup - -setup( - name="pyrmv", - version="0.3.5", - author="Profitroll", - description="Small module that makes your journey with RMV REST API somehow easier.", - long_description="Small module that makes your journey with RMV REST API somehow easier. Based fully on official RMV API reference and HAFAS documentation.\n\n## Requirements\n\n* RMV API key (Get it [here](https://opendata.rmv.de/site/start.html))\n* Python3 (Tested versions are 3.7.9 and 3.9.13)\n* git (Only for installation from source)\n\n## Installation\n\nIf you have everything listed in [requirements](#requirements), then let's begin.\n\n### Variant 1\n\n1. `python -m pip install pyrmv`\n\n### Variant 2\n\n1. `git clone https://git.end-play.xyz/profitroll/PythonRMV.git`\n2. `cd PythonRMV`\n3. `python setup.py install`\n\n## Usage\n\n```py\nimport pyrmv\n\n# Define a Client with API key\nclient = pyrmv.Client(\"AcessId\")\n\n# Get origin's and destination's location\norigin = client.stop_by_name(\"Frankfurt Hauptbahnhof\", max_number=3)[0]\ndestination = client.stop_by_coords(50.099613, 8.685449, max_number=3)[0]\n\n# Find a trip by locations got\ntrip = client.trip_find(origin_id=origin.id, dest_id=destination.id)\n```\n\n## Frequently Asked Questions\n\n* [Why are there raw versions and formatted ones?](#why-are-there-raw-versions-and-formatted-ones)\n* [Some methods work slightly different](#some-methods-work-slightly-different)\n\n### Why are there raw versions and formatted ones?\n\nFor the purposes of my projects I don't really need all the stuff RMV gives (even though it's not much).\nI only need some specific things. However I do understand that in some cases other users may find\nthose methods quite useful so I implemented them as well.\n\n### Some methods work slightly different\n\nCan be. Not all function arguments written may work perfectly because I simply did not test each and\nevery request. Some of arguments may be irrelevant in my use-case and the others are used quite rare at all.\nJust [make an issue](https://git.end-play.xyz/profitroll/PythonRMV/issues/new) and I'll implement it correct when I'll have some free time.\n\n## To-Do\n\n### General\n\n* [ ] Docs in Wiki\n* [ ] Tickets", - long_description_content_type="text/markdown", - author_email="profitroll@end-play.xyz", - url="https://git.end-play.xyz/profitroll/PythonRMV", - project_urls={ - "Bug Tracker": "https://git.end-play.xyz/profitroll/PythonRMV/issues", - "Documentation": "https://git.end-play.xyz/profitroll/PythonRMV/wiki", - "Source Code": "https://git.end-play.xyz/profitroll/PythonRMV.git", - }, - packages=[ - "pyrmv", - "pyrmv.raw", - "pyrmv.const", - "pyrmv.enums", - "pyrmv.errors", - "pyrmv.utility", - "pyrmv.classes", - ], - install_requires=["requests", "xmltodict", "isodate"], - classifiers=[ - "Development Status :: 3 - Alpha", - "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", - "Operating System :: OS Independent", - "Programming Language :: Python :: 3", - "Topic :: Software Development :: Libraries :: Python Modules", - "Topic :: Utilities", - ], -) diff --git a/pyrmv/__init__.py b/src/pyrmv/__init__.py similarity index 97% rename from pyrmv/__init__.py rename to src/pyrmv/__init__.py index b107229..8ecd27d 100644 --- a/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -21,7 +21,7 @@ trip = client.trip_find(origin_id=origin.id, dest_id=destination.id) """ __name__ = "pyrmv" -__version__ = "0.3.5" +__version__ = "0.3.6" __license__ = "MIT License" __author__ = "Profitroll" diff --git a/pyrmv/classes/Board.py b/src/pyrmv/classes/Board.py similarity index 100% rename from pyrmv/classes/Board.py rename to src/pyrmv/classes/Board.py diff --git a/pyrmv/classes/Client.py b/src/pyrmv/classes/Client.py similarity index 100% rename from pyrmv/classes/Client.py rename to src/pyrmv/classes/Client.py diff --git a/pyrmv/classes/Gis.py b/src/pyrmv/classes/Gis.py similarity index 100% rename from pyrmv/classes/Gis.py rename to src/pyrmv/classes/Gis.py diff --git a/pyrmv/classes/Journey.py b/src/pyrmv/classes/Journey.py similarity index 100% rename from pyrmv/classes/Journey.py rename to src/pyrmv/classes/Journey.py diff --git a/pyrmv/classes/Leg.py b/src/pyrmv/classes/Leg.py similarity index 100% rename from pyrmv/classes/Leg.py rename to src/pyrmv/classes/Leg.py diff --git a/pyrmv/classes/Message.py b/src/pyrmv/classes/Message.py similarity index 100% rename from pyrmv/classes/Message.py rename to src/pyrmv/classes/Message.py diff --git a/pyrmv/classes/Stop.py b/src/pyrmv/classes/Stop.py similarity index 100% rename from pyrmv/classes/Stop.py rename to src/pyrmv/classes/Stop.py diff --git a/pyrmv/classes/Ticket.py b/src/pyrmv/classes/Ticket.py similarity index 100% rename from pyrmv/classes/Ticket.py rename to src/pyrmv/classes/Ticket.py diff --git a/pyrmv/classes/Trip.py b/src/pyrmv/classes/Trip.py similarity index 100% rename from pyrmv/classes/Trip.py rename to src/pyrmv/classes/Trip.py diff --git a/pyrmv/classes/__init__.py b/src/pyrmv/classes/__init__.py similarity index 100% rename from pyrmv/classes/__init__.py rename to src/pyrmv/classes/__init__.py diff --git a/pyrmv/const/__init__.py b/src/pyrmv/const/__init__.py similarity index 100% rename from pyrmv/const/__init__.py rename to src/pyrmv/const/__init__.py diff --git a/pyrmv/const/product.py b/src/pyrmv/const/product.py similarity index 100% rename from pyrmv/const/product.py rename to src/pyrmv/const/product.py diff --git a/pyrmv/enums/__init__.py b/src/pyrmv/enums/__init__.py similarity index 100% rename from pyrmv/enums/__init__.py rename to src/pyrmv/enums/__init__.py diff --git a/pyrmv/enums/aff_journey_mode.py b/src/pyrmv/enums/aff_journey_mode.py similarity index 100% rename from pyrmv/enums/aff_journey_mode.py rename to src/pyrmv/enums/aff_journey_mode.py diff --git a/pyrmv/enums/aff_journey_stop_mode.py b/src/pyrmv/enums/aff_journey_stop_mode.py similarity index 100% rename from pyrmv/enums/aff_journey_stop_mode.py rename to src/pyrmv/enums/aff_journey_stop_mode.py diff --git a/pyrmv/enums/auto_name.py b/src/pyrmv/enums/auto_name.py similarity index 100% rename from pyrmv/enums/auto_name.py rename to src/pyrmv/enums/auto_name.py diff --git a/pyrmv/enums/board_type.py b/src/pyrmv/enums/board_type.py similarity index 100% rename from pyrmv/enums/board_type.py rename to src/pyrmv/enums/board_type.py diff --git a/pyrmv/enums/filter_mode.py b/src/pyrmv/enums/filter_mode.py similarity index 100% rename from pyrmv/enums/filter_mode.py rename to src/pyrmv/enums/filter_mode.py diff --git a/pyrmv/enums/lang.py b/src/pyrmv/enums/lang.py similarity index 100% rename from pyrmv/enums/lang.py rename to src/pyrmv/enums/lang.py diff --git a/pyrmv/enums/location_type.py b/src/pyrmv/enums/location_type.py similarity index 100% rename from pyrmv/enums/location_type.py rename to src/pyrmv/enums/location_type.py diff --git a/pyrmv/enums/product.py b/src/pyrmv/enums/product.py similarity index 100% rename from pyrmv/enums/product.py rename to src/pyrmv/enums/product.py diff --git a/pyrmv/enums/rt_mode.py b/src/pyrmv/enums/rt_mode.py similarity index 100% rename from pyrmv/enums/rt_mode.py rename to src/pyrmv/enums/rt_mode.py diff --git a/pyrmv/enums/search_mode.py b/src/pyrmv/enums/search_mode.py similarity index 100% rename from pyrmv/enums/search_mode.py rename to src/pyrmv/enums/search_mode.py diff --git a/pyrmv/enums/selection_mode.py b/src/pyrmv/enums/selection_mode.py similarity index 100% rename from pyrmv/enums/selection_mode.py rename to src/pyrmv/enums/selection_mode.py diff --git a/pyrmv/errors/__init__.py b/src/pyrmv/errors/__init__.py similarity index 100% rename from pyrmv/errors/__init__.py rename to src/pyrmv/errors/__init__.py diff --git a/pyrmv/errors/api_errors.py b/src/pyrmv/errors/api_errors.py similarity index 100% rename from pyrmv/errors/api_errors.py rename to src/pyrmv/errors/api_errors.py diff --git a/pyrmv/errors/int_errors.py b/src/pyrmv/errors/int_errors.py similarity index 100% rename from pyrmv/errors/int_errors.py rename to src/pyrmv/errors/int_errors.py diff --git a/pyrmv/errors/not_ready.py b/src/pyrmv/errors/not_ready.py similarity index 100% rename from pyrmv/errors/not_ready.py rename to src/pyrmv/errors/not_ready.py diff --git a/pyrmv/errors/ps_errors.py b/src/pyrmv/errors/ps_errors.py similarity index 100% rename from pyrmv/errors/ps_errors.py rename to src/pyrmv/errors/ps_errors.py diff --git a/pyrmv/errors/sot_errors.py b/src/pyrmv/errors/sot_errors.py similarity index 100% rename from pyrmv/errors/sot_errors.py rename to src/pyrmv/errors/sot_errors.py diff --git a/pyrmv/errors/svc_errors.py b/src/pyrmv/errors/svc_errors.py similarity index 100% rename from pyrmv/errors/svc_errors.py rename to src/pyrmv/errors/svc_errors.py diff --git a/pyrmv/errors/unknown_error.py b/src/pyrmv/errors/unknown_error.py similarity index 100% rename from pyrmv/errors/unknown_error.py rename to src/pyrmv/errors/unknown_error.py diff --git a/pyrmv/raw/__init__.py b/src/pyrmv/raw/__init__.py similarity index 100% rename from pyrmv/raw/__init__.py rename to src/pyrmv/raw/__init__.py diff --git a/pyrmv/raw/board_arrival.py b/src/pyrmv/raw/board_arrival.py similarity index 100% rename from pyrmv/raw/board_arrival.py rename to src/pyrmv/raw/board_arrival.py diff --git a/pyrmv/raw/board_departure.py b/src/pyrmv/raw/board_departure.py similarity index 100% rename from pyrmv/raw/board_departure.py rename to src/pyrmv/raw/board_departure.py diff --git a/pyrmv/raw/him_search.py b/src/pyrmv/raw/him_search.py similarity index 100% rename from pyrmv/raw/him_search.py rename to src/pyrmv/raw/him_search.py diff --git a/pyrmv/raw/journey_detail.py b/src/pyrmv/raw/journey_detail.py similarity index 100% rename from pyrmv/raw/journey_detail.py rename to src/pyrmv/raw/journey_detail.py diff --git a/pyrmv/raw/stop_by_coords.py b/src/pyrmv/raw/stop_by_coords.py similarity index 100% rename from pyrmv/raw/stop_by_coords.py rename to src/pyrmv/raw/stop_by_coords.py diff --git a/pyrmv/raw/stop_by_name.py b/src/pyrmv/raw/stop_by_name.py similarity index 100% rename from pyrmv/raw/stop_by_name.py rename to src/pyrmv/raw/stop_by_name.py diff --git a/pyrmv/raw/trip_find.py b/src/pyrmv/raw/trip_find.py similarity index 100% rename from pyrmv/raw/trip_find.py rename to src/pyrmv/raw/trip_find.py diff --git a/pyrmv/raw/trip_recon.py b/src/pyrmv/raw/trip_recon.py similarity index 100% rename from pyrmv/raw/trip_recon.py rename to src/pyrmv/raw/trip_recon.py diff --git a/pyrmv/utility/__init__.py b/src/pyrmv/utility/__init__.py similarity index 100% rename from pyrmv/utility/__init__.py rename to src/pyrmv/utility/__init__.py diff --git a/pyrmv/utility/find_exception.py b/src/pyrmv/utility/find_exception.py similarity index 100% rename from pyrmv/utility/find_exception.py rename to src/pyrmv/utility/find_exception.py diff --git a/pyrmv/utility/weekdays_bitmask.py b/src/pyrmv/utility/weekdays_bitmask.py similarity index 100% rename from pyrmv/utility/weekdays_bitmask.py rename to src/pyrmv/utility/weekdays_bitmask.py diff --git a/test.py b/test.py deleted file mode 100644 index f2f9085..0000000 --- a/test.py +++ /dev/null @@ -1,82 +0,0 @@ -from datetime import datetime, timedelta -from os import makedirs -from typing import Any -from ujson import loads, dumps, JSONDecodeError -from test_colors import * - -import pyrmv - -try: - with open("test_key.json", mode="r", encoding="utf-8") as file: - key = loads(file.read())["key"] - file.close() -except FileNotFoundError: - key = input("File 'test_key.json' does not exist. Enter your RMV API key to continue: ").strip() - key_save = input("To skip entering your key every time I can save your apikey here. Should I do that? (Y/n) > ").strip().lower() - if key_save == "y": - try: - with open("test_key.json", mode="w", encoding="utf-8") as file: - file.write(dumps({"key": key})) - file.close() - except Exception as exp: - print(f"Could not save 'test_key.json' with your apikey due to {exp}", flush=True) - else: - print("To skip entering your key every time create file 'test_key.json' with your apikey as a value for 'key' dict key.", flush=True) - - -def test(name: str, data: Any, raw: bool = False) -> None: - - makedirs("tests", exist_ok=True) - - if isinstance(data, dict): - if "errorCode" in data: - print(f"{BBLACK}[{BRED}ER{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}did not go well. ErrorCode is {BRED}{data['errorCode']}{RESET}. Check {CYAN}tests/{name}.json {RESET}for more information.", flush=True) - else: - print(f"{BBLACK}[{BGREEN}OK{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}seems to be alright.", flush=True) - - if raw: - - try: - with open(f"tests/{name}.json", "w", encoding="utf-8") as file: - file.write(dumps(data, indent=4, ensure_ascii=False)) - file.close() - except JSONDecodeError: - print(f"{BBLACK}[{BRED}ER{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}did not go well. ErrorCode is {BRED}{data['errorCode']}{RESET}. Check {CYAN}tests/{name}.json {RESET}for more information.", flush=True) - - else: - - with open(f"tests/{name}.txt", "w", encoding="utf-8") as file: - if isinstance(data, list): - list_2 = [] - for item in data: - list_2.append(str(item)+"\n") - file.writelines(list_2) - else: - file.write(str(data)) - file.close() - - if data in ["", "\n"]: - print(f"{BBLACK}[{BRED}ER{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}did not go well. ErrorCode is {BRED}{data['errorCode']}{RESET}. Check {CYAN}tests/{name}.txt {RESET}for more information.", flush=True) # type: ignore - else: - print(f"{BBLACK}[{BGREEN}OK{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}is not empty, so might be fine. Check {CYAN}tests/{name}.txt {RESET}for more information.", flush=True) - -client = pyrmv.Client(key) - -test("raw_board_arrival", pyrmv.raw.board_arrival(key, id="A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@X=8783648@Y=50083822@U=80@L=3008012@", maxJourneys=5), raw=True) -test("raw_board_departure", pyrmv.raw.board_departure(key, id="A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@X=8783648@Y=50083822@U=80@L=3008012@", maxJourneys=5), raw=True) -test("raw_him_search", pyrmv.raw.him_search(key, dateE=datetime.now()+timedelta(days=10), timeE=datetime.now()+timedelta(days=10), minprio=2, trainnames=["S9"]), raw=True) -test("raw_journey_detail", pyrmv.raw.journey_detail(key, id="2|#VN#1#ST#1664906549#PI#0#ZI#12709#TA#0#DA#61022#1S#3008007#1T#1248#LS#3008043#LT#1323#PU#80#RT#1#CA#1aE#ZE#101#ZB#Bus 101 #PC#6#FR#3008007#FT#1248#TO#3008043#TT#1323#"), raw=True) -test("raw_stop_by_name", pyrmv.raw.stop_by_name(key, "Groß Karben", maxNo=3), raw=True) -test("raw_stop_by_coords", pyrmv.raw.stop_by_coords(key, 50.131140, 8.733362, radius=300, maxNo=3), raw=True) -test("raw_trip_find", pyrmv.raw.trip_find(key, originCoordLat="50.084659", originCoordLong="8.785948", destCoordLat=50.1233048, destCoordLong=8.6129742, trafficMessages=True, numF=3), raw=True) -test("raw_trip_recon", pyrmv.raw.trip_recon(key, ctx="¶HKI¶G@F$A=2@O=50.084659, 8.785948@X=8785948@Y=50084659@u=0@a=128@$A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@L=3008012@a=128@$202210061243$202210061247$$$1$$$$$$§T$A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@L=3008012@a=128@$A=1@O=Offenbach (Main)-Zentrum Marktplatz/Frankf. Straße@L=3002510@a=128@$202210061247$202210061300$Bus 101 $$1$$$$$$§W$A=1@O=Offenbach (Main)-Zentrum Marktplatz/Frankf. Straße@L=3002510@a=128@$A=1@O=Offenbach (Main)-Zentrum Marktplatz@L=3011265@a=128@$202210061300$202210061304$$$1$$$$$$§T$A=1@O=Offenbach (Main)-Zentrum Marktplatz@L=3011265@a=128@$A=1@O=Frankfurt (Main) Taunusanlage@L=3000011@a=128@$202210061306$202210061319$ S2$$1$$$$$$§T$A=1@O=Frankfurt (Main) Taunusanlage@L=3000011@a=128@$A=1@O=Frankfurt (Main) Rödelheim Bahnhof@L=3001217@a=128@$202210061322$202210061333$ S5$$1$$$$$$§G@F$A=1@O=Frankfurt (Main) Rödelheim Bahnhof@L=3001217@a=128@$A=2@O=50.123304, 8.612974@X=8612974@Y=50123304@u=0@a=128@$202210061333$202210061344$$$1$$$$$$¶GP¶ft@0@2000@120@1@100@1@@0@@@@@false@0@-1@0@-1@-1@$f@$f@$f@$f@$f@$§bt@0@2000@120@1@100@1@@0@@@@@false@0@-1@0@-1@-1@$f@$f@$f@$f@$f@$§tt@0@2000@120@1@100@1@@0@@@@@false@0@-1@0@-1@-1@$f@$f@$f@$f@$f@$§¶KRCC¶#VE#1#"), raw=True) - -test("board_arrival", client.board_arrival("A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@", journeys_max=5)) -test("board_departure", client.board_departure("A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@", journeys_max=5, retrieve_stops=False)) -test("him_search", client.him_search(date_end=datetime.now()+timedelta(days=10), priority_min=2, train_names=["S9"])) -test("journey_detail", client.journey_detail("2|#VN#1#ST#1664906549#PI#0#ZI#12709#TA#0#DA#61022#1S#3008007#1T#1248#LS#3008043#LT#1323#PU#80#RT#1#CA#1aE#ZE#101#ZB#Bus 101 #PC#6#FR#3008007#FT#1248#TO#3008043#TT#1323#", real_time_mode=pyrmv.enums.RealTimeMode.FULL)) -test("stop_by_coords", client.stop_by_coords(50.131140, 8.733362, radius=300, max_number=3)) -test("stop_by_id", client.stop_by_id("A=1@O=Offenbach (Main)-Zentrum Marktplatz/Frankf. Straße@X=8764456@Y=50105181@U=80@L=3002510@")) -test("stop_by_name", client.stop_by_name("Groß Karben", max_number=3)) -test("trip_find", client.trip_find(origin_coord_lat="50.084659", origin_coord_lon="8.785948", destination_coord_lat=50.1233048, destination_coord_lon=8.6129742, messages=True)) -test("trip_recon", client.trip_recon( client.trip_find(origin_coord_lat="50.084659", origin_coord_lon="8.785948", destination_coord_lat=50.1233048, destination_coord_lon=8.6129742, messages=True, trips_after_time=1)[0] )) \ No newline at end of file diff --git a/test_colors.py b/test_colors.py deleted file mode 100644 index c4e99eb..0000000 --- a/test_colors.py +++ /dev/null @@ -1,19 +0,0 @@ -RESET = '\u001b[0m' -BLACK = '\u001b[30m' -RED = '\u001b[31m' -GREEN = '\u001b[32m' -YELLOW = '\u001b[33m' -BLUE = '\u001b[34m' -MAGENTA = '\u001b[35m' -CYAN = '\u001b[36m' -WHITE = '\u001b[37m' -BBLACK = '\u001b[30;1m' -BRED = '\u001b[31;1m' -BGREEN = '\u001b[32;1m' -BYELLOW = '\u001b[33;1m' -BBLUE = '\u001b[34;1m' -BMAGENTA = '\u001b[35;1m' -BCYAN = '\u001b[36;1m' -BWHITE = '\u001b[37;1m' -ULINE = '\u001b[4m' -REVERSE = '\u001b[7m' \ No newline at end of file diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..32050e0 --- /dev/null +++ b/tox.ini @@ -0,0 +1,22 @@ +[tox] +minversion = 3.8.0 +envlist = py37, py38, py39, py310, py311 +isolated_build = true + +[gh-actions] +python = + 3.7: py37 + 3.8: py38 + 3.9: py39 + 3.10: py310 + 3.11: py311 + +[testenv] +setenv = + PYTHONPATH = {toxinidir} +deps = + -r{toxinidir}/requirements/_.txt + -r{toxinidir}/requirements/dev.txt +commands = + pytest --basetemp={envtmpdir} --cov=cringepredictor --cov-report term-missing + -- 2.39.2 From 97335574638410ff5a093586cbf078eebe148269 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 19 Nov 2023 23:05:48 +0100 Subject: [PATCH 02/66] Added a few basic tests --- .gitea/workflows/tests.yml | 2 ++ tests/conftest.py | 15 +++++++++++++++ tests/test_client.py | 8 ++++++++ tests/test_raw.py | 7 +++++++ tox.ini | 2 +- 5 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 tests/conftest.py create mode 100644 tests/test_client.py create mode 100644 tests/test_raw.py diff --git a/.gitea/workflows/tests.yml b/.gitea/workflows/tests.yml index 3bb6bde..3bd100f 100644 --- a/.gitea/workflows/tests.yml +++ b/.gitea/workflows/tests.yml @@ -18,6 +18,8 @@ jobs: python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] steps: + env: + RMV_TOKEN: ${{ secrets.RMV_TOKEN }} - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..8fff836 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,15 @@ +from os import environ + +import pytest + +from pyrmv import Client + + +@pytest.fixture() +def api_token() -> str: + return environ.get("RMV_TOKEN") + + +@pytest.fixture() +def api_client(api_token: str) -> Client: + return Client(api_token) diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000..071a465 --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,8 @@ +import pytest + +from pyrmv import Client +from pyrmv.classes import Stop + + +def test_stop_by_name(api_client: Client): + assert isinstance(api_client.stop_by_name("Hauptwache", max_number=1)[0], Stop) diff --git a/tests/test_raw.py b/tests/test_raw.py new file mode 100644 index 0000000..f95b19e --- /dev/null +++ b/tests/test_raw.py @@ -0,0 +1,7 @@ +import pytest + +from pyrmv.raw import stop_by_name + + +def test_stop_by_name(api_token: str): + assert isinstance(stop_by_name(api_token, "Hauptwache", maxNo=1), dict) diff --git a/tox.ini b/tox.ini index 32050e0..85167c2 100644 --- a/tox.ini +++ b/tox.ini @@ -18,5 +18,5 @@ deps = -r{toxinidir}/requirements/_.txt -r{toxinidir}/requirements/dev.txt commands = - pytest --basetemp={envtmpdir} --cov=cringepredictor --cov-report term-missing + pytest --basetemp={envtmpdir} --cov=pyrmv --cov-report term-missing -- 2.39.2 From b0b874bfc8a9d4167ea9fcebee4187616aa49ab6 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 19 Nov 2023 23:08:09 +0100 Subject: [PATCH 03/66] env fix --- .gitea/workflows/tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitea/workflows/tests.yml b/.gitea/workflows/tests.yml index 3bd100f..4f511c3 100644 --- a/.gitea/workflows/tests.yml +++ b/.gitea/workflows/tests.yml @@ -18,8 +18,6 @@ jobs: python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] steps: - env: - RMV_TOKEN: ${{ secrets.RMV_TOKEN }} - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 @@ -32,5 +30,7 @@ jobs: python -m pip install --upgrade pip pip install tox tox-gh-actions - name: Test with tox + env: + RMV_TOKEN: ${{ secrets.RMV_TOKEN }} run: tox -- 2.39.2 From fa4f7b83ecd199e53a8c034b1307e3297d28e1ae Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 19 Nov 2023 23:47:41 +0100 Subject: [PATCH 04/66] Drop support for Python 3.7 (due to EOL) --- .gitea/workflows/tests.yml | 2 +- README.md | 2 +- pyproject.toml | 3 +-- tox.ini | 5 +++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.gitea/workflows/tests.yml b/.gitea/workflows/tests.yml index 4f511c3..7c680f2 100644 --- a/.gitea/workflows/tests.yml +++ b/.gitea/workflows/tests.yml @@ -15,7 +15,7 @@ jobs: container: catthehacker/ubuntu:act-latest strategy: matrix: - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] + python-version: ["3.8", "3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v3 diff --git a/README.md b/README.md index 6654d17..979f8e2 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Small module that makes your journey with RMV REST API somehow easier. Based ful ## Requirements * RMV API key (Get it [here](https://opendata.rmv.de/site/start.html)) -* Python3 (Tested versions are 3.7.9 and 3.9.13) +* Python 3.8+ * git (Only for installation from source) ## Installation diff --git a/pyproject.toml b/pyproject.toml index 4445954..40287a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,7 +17,6 @@ classifiers = [ "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", @@ -66,4 +65,4 @@ extension-pkg-whitelist = ["ujson"] py-version = 3.8 [tool.coverage.run] -source = ["libbot"] +source = ["pyrmv"] diff --git a/tox.ini b/tox.ini index 85167c2..e4c6404 100644 --- a/tox.ini +++ b/tox.ini @@ -1,11 +1,10 @@ [tox] minversion = 3.8.0 -envlist = py37, py38, py39, py310, py311 +envlist = py38, py39, py310, py311 isolated_build = true [gh-actions] python = - 3.7: py37 3.8: py38 3.9: py39 3.10: py310 @@ -14,6 +13,8 @@ python = [testenv] setenv = PYTHONPATH = {toxinidir} +passenv = + RMV_TOKEN deps = -r{toxinidir}/requirements/_.txt -r{toxinidir}/requirements/dev.txt -- 2.39.2 From f31fa65d7817453763a6e4ba054dde4ddd447e36 Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 24 Nov 2023 11:21:02 +0100 Subject: [PATCH 05/66] Small refactor and isort+black formatting --- README.md | 7 +- pyproject.toml | 1 + src/pyrmv/classes/Board.py | 89 ++-- src/pyrmv/classes/Client.py | 628 +++++++++++++---------- src/pyrmv/classes/Gis.py | 14 +- src/pyrmv/classes/Journey.py | 20 +- src/pyrmv/classes/Leg.py | 50 +- src/pyrmv/classes/Message.py | 62 +-- src/pyrmv/classes/Stop.py | 44 +- src/pyrmv/classes/Trip.py | 35 +- src/pyrmv/classes/__init__.py | 4 +- src/pyrmv/const/__init__.py | 1 + src/pyrmv/const/product.py | 2 +- src/pyrmv/enums/__init__.py | 14 +- src/pyrmv/enums/aff_journey_mode.py | 4 +- src/pyrmv/enums/aff_journey_stop_mode.py | 4 +- src/pyrmv/enums/auto_name.py | 7 +- src/pyrmv/enums/board_type.py | 13 +- src/pyrmv/enums/filter_mode.py | 8 +- src/pyrmv/enums/lang.py | 44 +- src/pyrmv/enums/location_type.py | 10 +- src/pyrmv/enums/product.py | 6 +- src/pyrmv/enums/rt_mode.py | 4 +- src/pyrmv/enums/search_mode.py | 4 +- src/pyrmv/enums/selection_mode.py | 6 +- src/pyrmv/errors/__init__.py | 7 + src/pyrmv/errors/api_errors.py | 12 +- src/pyrmv/errors/int_errors.py | 7 +- src/pyrmv/errors/not_ready.py | 3 +- src/pyrmv/errors/ps_errors.py | 3 +- src/pyrmv/errors/sot_errors.py | 11 +- src/pyrmv/errors/svc_errors.py | 30 +- src/pyrmv/errors/unknown_error.py | 2 +- src/pyrmv/raw/__init__.py | 2 +- src/pyrmv/raw/board_arrival.py | 72 ++- src/pyrmv/raw/board_departure.py | 72 ++- src/pyrmv/raw/him_search.py | 107 ++-- src/pyrmv/raw/journey_detail.py | 50 +- src/pyrmv/raw/stop_by_coords.py | 60 +-- src/pyrmv/raw/stop_by_name.py | 60 ++- src/pyrmv/raw/trip_find.py | 231 ++++----- src/pyrmv/raw/trip_recon.py | 85 ++- src/pyrmv/utility/__init__.py | 2 + src/pyrmv/utility/find_exception.py | 46 +- src/pyrmv/utility/weekdays_bitmask.py | 15 +- 45 files changed, 1035 insertions(+), 923 deletions(-) diff --git a/README.md b/README.md index 979f8e2..6345086 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,9 @@ -# PythonRMV +

PythonRMV

+ +

+License: MIT +Code style: black +

Small module that makes your journey with RMV REST API somehow easier. Based fully on official RMV API reference and HAFAS documentation. diff --git a/pyproject.toml b/pyproject.toml index 40287a7..499db6e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,6 +44,7 @@ where = ["src"] [tool.black] target-version = ['py38', 'py39', 'py310', 'py311'] +line-length = 94 [tool.isort] profile = "black" diff --git a/src/pyrmv/classes/Board.py b/src/pyrmv/classes/Board.py index 70d3429..a52a1d5 100644 --- a/src/pyrmv/classes/Board.py +++ b/src/pyrmv/classes/Board.py @@ -1,94 +1,99 @@ from datetime import datetime +from typing import Any, Mapping + from pyrmv.classes.Message import Message -class LineArrival(): - def __init__(self, data, client, retrieve_stops: bool = True): +class LineArrival: + def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) self.status = data["JourneyStatus"] self.messages = [] - if "Messages" in data: - self.messages.extend( - Message(message) for message in data["Messages"]["Message"] - ) self.name = data["name"] self.type = data["type"] self.stop_name = data["stop"] self.stop_id = data["stopid"] self.stop_id_ext = data["stopExtId"] - if retrieve_stops: - self.stop = client.stop_by_id(self.stop_id) - else: - self.stop = None + self.stop = client.stop_by_id(self.stop_id) if retrieve_stops else None self.stop = client.stop_by_id(self.stop_id) self.time = datetime.strptime(data["time"], "%H:%M:%S") self.date = datetime.strptime(data["date"], "%Y-%m-%d") + self.reachable = data["reachable"] + self.origin = data["origin"] + self.origin = data["origin"] + + if "Messages" in data: + self.messages.extend(Message(message) for message in data["Messages"]["Message"]) + if ("rtTime" in data) and ("rtDate" in data): self.time_real_time = datetime.strptime(data["rtTime"], "%H:%M:%S") self.date_real_time = datetime.strptime(data["rtDate"], "%Y-%m-%d") - self.reachable = data["reachable"] - self.origin = data["origin"] + else: + self.time_real_time = None + self.date_real_time = None def __str__(self) -> str: - return f"{self.name} coming from {self.origin} at {self.time.time()} {self.date.date()}" + return ( + f"{self.name} coming from {self.origin} at {self.time.time()} {self.date.date()}" + ) -class LineDeparture(): - def __init__(self, data, client, retrieve_stops: bool = True): +class LineDeparture: + def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) self.status = data["JourneyStatus"] self.messages = [] - if "Messages" in data: - self.messages.extend( - Message(message) for message in data["Messages"]["Message"] - ) self.name = data["name"] self.type = data["type"] self.stop_name = data["stop"] self.stop_id = data["stopid"] self.stop_id_ext = data["stopExtId"] - if retrieve_stops: - self.stop = client.stop_by_id(self.stop_id) - else: - self.stop = None + self.stop = client.stop_by_id(self.stop_id) if retrieve_stops else None self.time = datetime.strptime(data["time"], "%H:%M:%S") self.date = datetime.strptime(data["date"], "%Y-%m-%d") - if ("rtTime" in data) and ("rtDate" in data): - self.time_real_time = datetime.strptime(data["rtTime"], "%H:%M:%S") - self.date_real_time = datetime.strptime(data["rtDate"], "%Y-%m-%d") self.reachable = data["reachable"] self.direction = data["direction"] self.direction_flag = data["directionFlag"] - - def __str__(self) -> str: - return f"{self.name} heading {self.direction} at {self.time.time()} {self.date.date()}" - -class BoardArrival(list): - def __init__(self, data: dict, client, retrieve_stops: bool = True): + if "Messages" in data: + self.messages.extend(Message(message) for message in data["Messages"]["Message"]) + + if ("rtTime" in data) and ("rtDate" in data): + self.time_real_time = datetime.strptime(data["rtTime"], "%H:%M:%S") + self.date_real_time = datetime.strptime(data["rtDate"], "%Y-%m-%d") + else: + self.time_real_time = None + self.date_real_time = None + + def __str__(self) -> str: + return ( + f"{self.name} heading {self.direction} at {self.time.time()} {self.date.date()}" + ) + + +class BoardArrival(list): + def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): super().__init__([]) + if "Arrival" not in data: return + for line in data["Arrival"]: self.append(LineArrival(line, client, retrieve_stops=retrieve_stops)) def __str__(self) -> str: - lines = [] - for line in self: - lines.append(str(line)) - return "Arrival board\n" + "\n".join(lines) + return "Arrival board\n" + "\n".join([str(line) for line in self]) + class BoardDeparture(list): - - def __init__(self, data: dict, client, retrieve_stops: bool = True): + def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): super().__init__([]) + if "Departure" not in data: return + for line in data["Departure"]: self.append(LineDeparture(line, client, retrieve_stops=retrieve_stops)) def __str__(self) -> str: - lines = [] - for line in self: - lines.append(str(line)) - return "Departure board\n" + "\n".join(lines) \ No newline at end of file + return "Departure board\n" + "\n".join([str(line) for line in self]) diff --git a/src/pyrmv/classes/Client.py b/src/pyrmv/classes/Client.py index a625026..8676f76 100644 --- a/src/pyrmv/classes/Client.py +++ b/src/pyrmv/classes/Client.py @@ -1,24 +1,26 @@ from datetime import datetime, timedelta from typing import List, OrderedDict, Union + from pyrmv.classes import * from pyrmv.enums import * from pyrmv.raw import board_arrival as raw_board_arrival from pyrmv.raw.board_departure import board_departure as raw_board_departure +from pyrmv.raw.him_search import him_search as raw_him_search from pyrmv.raw.journey_detail import journey_detail as raw_journey_detail -from pyrmv.raw.stop_by_name import stop_by_name as raw_stop_by_name from pyrmv.raw.stop_by_coords import stop_by_coords as raw_stop_by_coords +from pyrmv.raw.stop_by_name import stop_by_name as raw_stop_by_name from pyrmv.raw.trip_find import trip_find as raw_trip_find from pyrmv.raw.trip_recon import trip_recon as raw_trip_recon -from pyrmv.raw.him_search import him_search as raw_him_search -from pyrmv.utility.find_exception import find_exception +from pyrmv.utility import find_exception try: from typing import Literal except ImportError: from typing_extensions import Literal -class Client(): - """The main class in the whole module. Is used to use all non-raw methods. + +class Client: + """The main class in the whole module. Is used to use all non-raw methods. More detailed docs for each method can be found by using IDE's docstring highlighting system or in project's wiki ([can be found here](https://git.end-play.xyz/profitroll/PythonRMV/wiki)) @@ -63,27 +65,33 @@ class Client(): # Find a trip and reconstruct it trip = client.trip_find(origin_coord_lat="50.084659", origin_coord_lon="8.785948", destination_coord_lat=50.1233048, destination_coord_lon=8.6129742, messages=True)[0] trip_recon = client.trip_recon(trip)[0] - ``` - """ + ``` + """ def __init__(self, access_id: str) -> None: self.access_id = access_id - def board_arrival(self, - id: Union[str, None] = None, - id_ext: Union[str, None] = None, - direction: Union[str, Stop, StopTrip, None] = None, - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, - duration: Union[int, timedelta] = 60, - journeys_max: int = -1, - operators: Union[str, list, None] = None, - lines: Union[str, list, None] = None, - passlist: bool = False, - board_type: Literal[BoardArrivalType.ARR, BoardArrivalType.ARR_EQUIVS, BoardArrivalType.ARR_MAST, BoardArrivalType.ARR_STATION] = BoardArrivalType.ARR, - retrieve_stops: bool = True - ) -> BoardArrival: - """Method returns a board with arriving transport. + def board_arrival( + self, + id: Union[str, None] = None, + id_ext: Union[str, None] = None, + direction: Union[str, Stop, StopTrip, None] = None, + date: Union[str, datetime, None] = None, + time: Union[str, datetime, None] = None, + duration: Union[int, timedelta] = 60, + journeys_max: int = -1, + operators: Union[str, list, None] = None, + lines: Union[str, list, None] = None, + passlist: bool = False, + board_type: Literal[ + BoardArrivalType.ARR, + BoardArrivalType.ARR_EQUIVS, + BoardArrivalType.ARR_MAST, + BoardArrivalType.ARR_STATION, + ] = BoardArrivalType.ARR, + retrieve_stops: bool = True, + ) -> BoardArrival: + """Method returns a board with arriving transport. More detailed request is available as `raw.board_arrival()`, however returns `dict` instead of `Board`. @@ -105,14 +113,14 @@ class Client(): * BoardArrival: Instance of `BoardArrival` object. """ - if (isinstance(direction, Stop) or isinstance(direction, StopTrip)): + if isinstance(direction, Stop) or isinstance(direction, StopTrip): direction = direction.id board_raw = raw_board_arrival( accessId=self.access_id, id=id, extId=id_ext, - direction=direction, # type: ignore + direction=direction, # type: ignore date=date, time=time, duration=duration, @@ -120,28 +128,34 @@ class Client(): operators=operators, lines=lines, passlist=passlist, - boardType=board_type.code + boardType=board_type.code, ) find_exception(board_raw) return BoardArrival(board_raw, self, retrieve_stops=retrieve_stops) - def board_departure(self, - id: Union[str, None] = None, - id_ext: Union[str, None] = None, - direction: Union[str, Stop, StopTrip, None] = None, - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, - duration: Union[int, timedelta] = 60, - journeys_max: int = -1, - operators: Union[str, list, None] = None, - lines: Union[str, list, None] = None, - passlist: bool = False, - board_type: Literal[BoardDepartureType.DEP, BoardDepartureType.DEP_EQUIVS, BoardDepartureType.DEP_MAST, BoardDepartureType.DEP_STATION] = BoardDepartureType.DEP, - retrieve_stops: bool = True - ) -> BoardDeparture: - """Method returns a board with departing transport. + def board_departure( + self, + id: Union[str, None] = None, + id_ext: Union[str, None] = None, + direction: Union[str, Stop, StopTrip, None] = None, + date: Union[str, datetime, None] = None, + time: Union[str, datetime, None] = None, + duration: Union[int, timedelta] = 60, + journeys_max: int = -1, + operators: Union[str, list, None] = None, + lines: Union[str, list, None] = None, + passlist: bool = False, + board_type: Literal[ + BoardDepartureType.DEP, + BoardDepartureType.DEP_EQUIVS, + BoardDepartureType.DEP_MAST, + BoardDepartureType.DEP_STATION, + ] = BoardDepartureType.DEP, + retrieve_stops: bool = True, + ) -> BoardDeparture: + """Method returns a board with departing transport. More detailed request is available as `raw.board_departure()`, however returns `dict` instead of `Board`. @@ -163,14 +177,14 @@ class Client(): * BoardDeparture: Instance of `BoardDeparture` object. """ - if (isinstance(direction, Stop) or isinstance(direction, StopTrip)): + if isinstance(direction, (Stop, StopTrip)): direction = direction.id board_raw = raw_board_departure( accessId=self.access_id, id=id, extId=id_ext, - direction=direction, # type: ignore + direction=direction, # type: ignore date=date, time=time, duration=duration, @@ -178,41 +192,53 @@ class Client(): operators=operators, lines=lines, passlist=passlist, - boardType=board_type.code + boardType=board_type.code, ) find_exception(board_raw) return BoardDeparture(board_raw, self, retrieve_stops=retrieve_stops) - def him_search(self, - date_begin: Union[str, datetime, None] = None, - date_end: Union[str, datetime, None] = None, - time_begin: Union[str, datetime, None] = None, - time_end: Union[str, datetime, None] = None, - weekdays: Union[str, OrderedDict[str, bool], None] = None, - ids: Union[list, None] = None, - operators: Union[list, None] = None, - categories: Union[list, None] = None, - channels: Union[list, None] = None, - companies: Union[list, None] = None, - lines: Union[list, None] = None, - line_ids: Union[list, None] = None, - stations: Union[list, List[Stop], None] = None, - station_from: Union[str, Stop, None] = None, - station_to: Union[str, Stop, None] = None, - both_ways: Union[bool, None] = None, - train_names: Union[list, None] = None, - search_mode: Union[Literal[SearchMode.MATCH, SearchMode.NOMATCH, SearchMode.TFMATCH], None] = None, - affected_journey_mode: Union[Literal[AffectedJourneyMode.ALL, AffectedJourneyMode.OFF], None] = None, - affected_journey_stop_mode: Union[Literal[AffectedJourneyStopMode.ALL, AffectedJourneyStopMode.IMP, AffectedJourneyStopMode.OFF], None] = None, - priority_min: Union[int, None] = None, - priority_max: Union[int, None] = None - ) -> List[Message]: + def him_search( + self, + date_begin: Union[str, datetime, None] = None, + date_end: Union[str, datetime, None] = None, + time_begin: Union[str, datetime, None] = None, + time_end: Union[str, datetime, None] = None, + weekdays: Union[str, OrderedDict[str, bool], None] = None, + ids: Union[list, None] = None, + operators: Union[list, None] = None, + categories: Union[list, None] = None, + channels: Union[list, None] = None, + companies: Union[list, None] = None, + lines: Union[list, None] = None, + line_ids: Union[list, None] = None, + stations: Union[list, List[Stop], None] = None, + station_from: Union[str, Stop, None] = None, + station_to: Union[str, Stop, None] = None, + both_ways: Union[bool, None] = None, + train_names: Union[list, None] = None, + search_mode: Union[ + Literal[SearchMode.MATCH, SearchMode.NOMATCH, SearchMode.TFMATCH], None + ] = None, + affected_journey_mode: Union[ + Literal[AffectedJourneyMode.ALL, AffectedJourneyMode.OFF], None + ] = None, + affected_journey_stop_mode: Union[ + Literal[ + AffectedJourneyStopMode.ALL, + AffectedJourneyStopMode.IMP, + AffectedJourneyStopMode.OFF, + ], + None, + ] = None, + priority_min: Union[int, None] = None, + priority_max: Union[int, None] = None, + ) -> List[Message]: """The him_search method will deliver a list of HIM messages if matched by the given criteria as - well as affected products if any. + well as affected products if any. - More detailed request is available as `raw.him_search()`, however returns `dict` instead of `List[Message]`. + More detailed request is available as `raw.him_search()`, however returns `dict` instead of `List[Message]`. ### Args: * date_begin (`Union[str, datetime]`, optional): Sets the event period start date. Defaults to `None`. @@ -240,7 +266,7 @@ class Client(): ### Returns: * List[Message]: List of `Message` objects. Empty list if none found. - """ + """ if isinstance(station_from, Stop): station_from = station_from.ext_id @@ -257,20 +283,13 @@ class Client(): new_stations.append(stop) stations = new_stations - if search_mode == None: - search_mode = None - else: - search_mode = search_mode.code - - if affected_journey_mode == None: - affected_journey_mode = None - else: - affected_journey_mode = affected_journey_mode.code - - if affected_journey_stop_mode == None: - affected_journey_stop_mode = None - else: - affected_journey_stop_mode = affected_journey_stop_mode.code + search_mode = None if search_mode is None else search_mode.code + affected_journey_mode = ( + None if affected_journey_mode is None else affected_journey_mode.code + ) + affected_journey_stop_mode = ( + None if affected_journey_stop_mode is None else affected_journey_stop_mode.code + ) messages = [] messages_raw = raw_him_search( @@ -288,38 +307,47 @@ class Client(): lines=lines, lineids=line_ids, stations=stations, - fromstation=station_from, # type: ignore - tostation=station_to, # type: ignore + fromstation=station_from, # type: ignore + tostation=station_to, # type: ignore bothways=both_ways, trainnames=train_names, - searchmode=search_mode, # type: ignore - affectedJourneyMode=affected_journey_mode, # type: ignore - affectedJourneyStopMode=affected_journey_stop_mode, # type: ignore + searchmode=search_mode, # type: ignore + affectedJourneyMode=affected_journey_mode, # type: ignore + affectedJourneyStopMode=affected_journey_stop_mode, # type: ignore maxprio=priority_max, - minprio=priority_min + minprio=priority_min, ) find_exception(messages_raw) if "Message" in messages_raw: - for message in messages_raw["Message"]: - messages.append(Message(message)) + messages.extend(Message(message) for message in messages_raw["Message"]) return messages - def journey_detail(self, - id: str, - date: Union[str, datetime, None] = None, - real_time_mode: Union[Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT], None] = None, - from_id: Union[str, None] = None, - from_index: Union[int, None] = None, - to_id: Union[str, None] = None, - to_index: Union[int, None] = None - ) -> Journey: + def journey_detail( + self, + id: str, + date: Union[str, datetime, None] = None, + real_time_mode: Union[ + Literal[ + RealTimeMode.FULL, + RealTimeMode.INFOS, + RealTimeMode.OFF, + RealTimeMode.REALTIME, + RealTimeMode.SERVER_DEFAULT, + ], + None, + ] = None, + from_id: Union[str, None] = None, + from_index: Union[int, None] = None, + to_id: Union[str, None] = None, + to_index: Union[int, None] = None, + ) -> Journey: """The journey_detail method will deliver information about the complete route of a vehicle. The journey identifier is part of a trip or `board_departure()` response. It contains a list of all stops/stations of this journey including all departure and arrival times (with real-time data if available) and additional information like - specific attributes about facilities and other texts. + specific attributes about facilities and other texts. More detailed request is available as `raw.journey_detail()`, however returns `dict` instead of `Journey`. @@ -334,40 +362,58 @@ class Client(): ### Returns: * Journey: Instance of `Journey` object. - """ + """ - if real_time_mode == None: - real_time_mode = None - else: - real_time_mode = real_time_mode.code + real_time_mode = None if real_time_mode is None else real_time_mode.code journey_raw = raw_journey_detail( accessId=self.access_id, id=id, date=date, - rtMode=real_time_mode, # type: ignore + rtMode=real_time_mode, # type: ignore fromId=from_id, fromIdx=from_index, toId=to_id, - toIdx=to_index + toIdx=to_index, ) find_exception(journey_raw) return Journey(journey_raw) - def stop_by_coords(self, - coords_lat: Union[str, float], - coords_lon: Union[str, float], - - lang: Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR] = Language.EN, - radius: Union[int, float] = 1000, - max_number: int = 10, - stop_type: Literal[LocationType.S, LocationType.P, LocationType.SP, LocationType.SE, LocationType.SPE] = LocationType.S, - selection_mode: Union[Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N], None] = None, - ) -> List[Stop]: + def stop_by_coords( + self, + coords_lat: Union[str, float], + coords_lon: Union[str, float], + lang: Literal[ + Language.DE, + Language.DA, + Language.EN, + Language.ES, + Language.FR, + Language.HU, + Language.IT, + Language.NL, + Language.NO, + Language.PL, + Language.SV, + Language.TR, + ] = Language.EN, + radius: Union[int, float] = 1000, + max_number: int = 10, + stop_type: Literal[ + LocationType.S, + LocationType.P, + LocationType.SP, + LocationType.SE, + LocationType.SPE, + ] = LocationType.S, + selection_mode: Union[ + Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N], None + ] = None, + ) -> List[Stop]: """Method returns a list of stops around a given center coordinate. - The returned results are ordered by their distance to the center coordinate. + The returned results are ordered by their distance to the center coordinate. More detailed request is available as `raw.stop_by_coords()`, however returns `dict` instead of `List[Stop]`. @@ -382,12 +428,9 @@ class Client(): ### Returns: * List[Stop]: List of `Stop` objects. Empty list if none found. - """ + """ - if selection_mode == None: - selection_mode = None - else: - selection_mode = selection_mode.code + selection_mode = None if selection_mode is None else selection_mode.code stops = [] stops_raw = raw_stop_by_coords( @@ -398,7 +441,7 @@ class Client(): radius=radius, maxNo=max_number, stopType=stop_type.code, - locationSelectionMode=selection_mode # type: ignore + locationSelectionMode=selection_mode, # type: ignore ) find_exception(stops_raw) @@ -412,59 +455,96 @@ class Client(): return stops - def stop_by_id(self, - query: str, - lang: Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR] = Language.EN, - ) -> Union[Stop, None]: + def stop_by_id( + self, + query: str, + lang: Literal[ + Language.DE, + Language.DA, + Language.EN, + Language.ES, + Language.FR, + Language.HU, + Language.IT, + Language.NL, + Language.NO, + Language.PL, + Language.SV, + Language.TR, + ] = Language.EN, + ) -> Union[Stop, None]: """Method can be used to get Stop object whilst only having id available. ### Args: * query (`str`): Search for that token. * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`. - + ### Returns: * Union[Stop, None]: Instance of `Stop` object or `None` if not found. - """ + """ stops_raw = raw_stop_by_name( - accessId=self.access_id, - inputString=query, - lang=lang.code, - maxNo=1 + accessId=self.access_id, inputString=query, lang=lang.code, maxNo=1 ) find_exception(stops_raw) - if len(stops_raw["stopLocationOrCoordLocation"]) > 0: - stop = stops_raw["stopLocationOrCoordLocation"][0] + if len(stops_raw["stopLocationOrCoordLocation"]) <= 0: + return None - if "StopLocation" in stop: - return Stop(stop["StopLocation"]) - elif "CoordLocation" in stop: - return Stop(stop["CoordLocation"]) - else: - return None + stop = stops_raw["stopLocationOrCoordLocation"][0] + + if "StopLocation" in stop: + return Stop(stop["StopLocation"]) + elif "CoordLocation" in stop: + return Stop(stop["CoordLocation"]) else: return None - def stop_by_name(self, - query: str, - lang: Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR] = Language.EN, - max_number: int = 10, - stop_type: Literal[LocationType.A, LocationType.ALL, LocationType.AP, LocationType.P, LocationType.S, LocationType.SA, LocationType.SP] = LocationType.ALL, - selection_mode: Union[Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N], None] = None, - coord_lat: Union[str, float, None] = None, - coord_lon: Union[str, float, None] = None, - radius: Union[int, float] = 1000, - refine_id: Union[str, None] = None, - stations: Union[str, list, None] = None, - filter_mode: Literal[FilterMode.DIST_PERI, FilterMode.EXCL_PERI, FilterMode.SLCT_PERI] = FilterMode.DIST_PERI - ) -> List[Stop]: + def stop_by_name( + self, + query: str, + lang: Literal[ + Language.DE, + Language.DA, + Language.EN, + Language.ES, + Language.FR, + Language.HU, + Language.IT, + Language.NL, + Language.NO, + Language.PL, + Language.SV, + Language.TR, + ] = Language.EN, + max_number: int = 10, + stop_type: Literal[ + LocationType.A, + LocationType.ALL, + LocationType.AP, + LocationType.P, + LocationType.S, + LocationType.SA, + LocationType.SP, + ] = LocationType.ALL, + selection_mode: Union[ + Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N], None + ] = None, + coord_lat: Union[str, float, None] = None, + coord_lon: Union[str, float, None] = None, + radius: Union[int, float] = 1000, + refine_id: Union[str, None] = None, + stations: Union[str, list, None] = None, + filter_mode: Literal[ + FilterMode.DIST_PERI, FilterMode.EXCL_PERI, FilterMode.SLCT_PERI + ] = FilterMode.DIST_PERI, + ) -> List[Stop]: """Method can be used to perform a pattern matching of a user input and to retrieve a list of possible matches in the journey planner database. Possible matches might be stops/stations, - points of interest and addresses. + points of interest and addresses. - More detailed request is available as `raw.stop_by_name()`, however returns `dict` instead of `List[Stop]`. + More detailed request is available as `raw.stop_by_name()`, however returns `dict` instead of `List[Stop]`. ### Args: * query (`str`): Search for that token. @@ -481,12 +561,9 @@ class Client(): ### Returns: * List[Stop]: List of `Stop` objects. Empty list if none found. - """ + """ - if selection_mode == None: - selection_mode = None - else: - selection_mode = selection_mode.code + selection_mode = None if selection_mode is None else selection_mode.code stops = [] stops_raw = raw_stop_by_name( @@ -495,13 +572,13 @@ class Client(): lang=lang.code, maxNo=max_number, stopType=stop_type.code, - locationSelectionMode=selection_mode, # type: ignore + locationSelectionMode=selection_mode, # type: ignore coordLat=coord_lat, coordLong=coord_lon, radius=radius, refineId=refine_id, stations=stations, - filterMode=filter_mode.code + filterMode=filter_mode.code, ) find_exception(stops_raw) @@ -515,71 +592,78 @@ class Client(): return stops - def trip_find(self, - lang: Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR] = Language.EN, - - origin_id: Union[str, None] = None, - origin_id_ext: Union[str, None] = None, - origin_coord_lat: Union[str, float, None] = None, - origin_coord_lon: Union[str, float, None] = None, - origin_coord_name: Union[str, None] = None, - - destination_id: Union[str, None] = None, - destination_id_ext: Union[str, None] = None, - destination_coord_lat: Union[str, float, None] = None, - destination_coord_lon: Union[str, float, None] = None, - destination_coord_name: Union[str, None] = None, - - via: Union[str, None] = None, - via_id: Union[str, None] = None, - via_gis: Union[str, None] = None, - via_wait_time: int = 0, - - avoid: Union[str, None] = None, - avoid_id: Union[str, None] = None, - - change_time_percent: int = 100, - change_time_min: Union[int, None] = None, - change_time_max: Union[int, None] = None, - change_time_add: Union[int, None] = None, - change_max: Union[int, None] = None, - - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, - - search_arrival: bool = False, - - trips_after_time: Union[int, None] = None, - trips_before_time: Union[int, None] = None, - - context: Union[str, None] = None, - - passlist: bool = False, - operators: Union[str, list, None] = None, - - lines: Union[str, list, None] = None, - lineids: Union[str, list, None] = None, - - iv_include: bool = False, - iv_only: bool = False, - - bike_carriage: bool = False, - - passing_points: bool = False, - - real_time_mode: Union[Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT], None] = None, - - include_earlier: bool = False, - ict_alternatives: bool = False, - tariff: Union[bool, None] = None, - messages: bool = False, - frequency: bool = True - ) -> List[Trip]: + def trip_find( + self, + lang: Literal[ + Language.DE, + Language.DA, + Language.EN, + Language.ES, + Language.FR, + Language.HU, + Language.IT, + Language.NL, + Language.NO, + Language.PL, + Language.SV, + Language.TR, + ] = Language.EN, + origin_id: Union[str, None] = None, + origin_id_ext: Union[str, None] = None, + origin_coord_lat: Union[str, float, None] = None, + origin_coord_lon: Union[str, float, None] = None, + origin_coord_name: Union[str, None] = None, + destination_id: Union[str, None] = None, + destination_id_ext: Union[str, None] = None, + destination_coord_lat: Union[str, float, None] = None, + destination_coord_lon: Union[str, float, None] = None, + destination_coord_name: Union[str, None] = None, + via: Union[str, None] = None, + via_id: Union[str, None] = None, + via_gis: Union[str, None] = None, + via_wait_time: int = 0, + avoid: Union[str, None] = None, + avoid_id: Union[str, None] = None, + change_time_percent: int = 100, + change_time_min: Union[int, None] = None, + change_time_max: Union[int, None] = None, + change_time_add: Union[int, None] = None, + change_max: Union[int, None] = None, + date: Union[str, datetime, None] = None, + time: Union[str, datetime, None] = None, + search_arrival: bool = False, + trips_after_time: Union[int, None] = None, + trips_before_time: Union[int, None] = None, + context: Union[str, None] = None, + passlist: bool = False, + operators: Union[str, list, None] = None, + lines: Union[str, list, None] = None, + lineids: Union[str, list, None] = None, + iv_include: bool = False, + iv_only: bool = False, + bike_carriage: bool = False, + passing_points: bool = False, + real_time_mode: Union[ + Literal[ + RealTimeMode.FULL, + RealTimeMode.INFOS, + RealTimeMode.OFF, + RealTimeMode.REALTIME, + RealTimeMode.SERVER_DEFAULT, + ], + None, + ] = None, + include_earlier: bool = False, + ict_alternatives: bool = False, + tariff: Union[bool, None] = None, + messages: bool = False, + frequency: bool = True, + ) -> List[Trip]: """The trip service calculates a trip from a specified origin to a specified destination. These might be stop/station IDs or coordinates based on addresses and points of interest validated by the location service or coordinates freely defined by the client. - More detailed request is available as `raw.trip_find()`, however returns `dict` instead of `List[Trip]`. + More detailed request is available as `raw.trip_find()`, however returns `dict` instead of `List[Trip]`. ### Args: * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`. @@ -627,105 +711,94 @@ class Client(): ### Returns: * List[Trip]: List of `Trip` objects. Empty list if none found. - """ + """ - if real_time_mode == None: - real_time_mode = None - else: - real_time_mode = real_time_mode.code + real_time_mode = None if real_time_mode is None else real_time_mode.code trips = [] trips_raw = raw_trip_find( - accessId=self.access_id, lang=lang.code, - originId=origin_id, originExtId=origin_id_ext, originCoordLat=origin_coord_lat, originCoordLong=origin_coord_lon, originCoordName=origin_coord_name, - destId=destination_id, destExtId=destination_id_ext, destCoordLat=destination_coord_lat, destCoordLong=destination_coord_lon, destCoordName=destination_coord_name, - via=via, viaId=via_id, viaGis=via_gis, viaWaitTime=via_wait_time, - avoid=avoid, avoidId=avoid_id, - changeTimePercent=change_time_percent, minChangeTime=change_time_min, maxChangeTime=change_time_max, addChangeTime=change_time_add, maxChange=change_max, - date=date, time=time, - searchForArrival=search_arrival, - numF=trips_after_time, numB=trips_before_time, - context=context, - passlist=passlist, operators=operators, - lines=lines, lineids=lineids, - includeIv=iv_include, ivOnly=iv_only, - bikeCarriage=bike_carriage, - showPassingPoints=passing_points, - - rtMode=real_time_mode, # type: ignore - + rtMode=real_time_mode, # type: ignore includeEarlier=include_earlier, withICTAlternatives=ict_alternatives, tariff=tariff, trafficMessages=messages, - withFreq=frequency + withFreq=frequency, ) find_exception(trips_raw) if "Trip" in trips_raw: - for trip in trips_raw["Trip"]: - trips.append(Trip(trip)) + trips.extend(Trip(trip) for trip in trips_raw["Trip"]) return trips - def trip_recon(self, - context: Union[str, Trip], - date: Union[str, datetime, None] = None, - match_real_time: Union[bool, None] = None, - enable_replacements: Union[bool, None] = None, - arrival_dev_lower: Union[int, None] = None, - arrival_dev_upper: Union[int, None] = None, - departure_dev_lower: Union[int, None] = None, - departure_dev_upper: Union[int, None] = None, - passlist: bool = False, - passing_points: bool = False, - real_time_mode: Union[Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT], None] = None, - tariff: Union[bool, None] = None, - messages: bool = False - ) -> List[Trip]: + def trip_recon( + self, + context: Union[str, Trip], + date: Union[str, datetime, None] = None, + match_real_time: Union[bool, None] = None, + enable_replacements: Union[bool, None] = None, + arrival_dev_lower: Union[int, None] = None, + arrival_dev_upper: Union[int, None] = None, + departure_dev_lower: Union[int, None] = None, + departure_dev_upper: Union[int, None] = None, + passlist: bool = False, + passing_points: bool = False, + real_time_mode: Union[ + Literal[ + RealTimeMode.FULL, + RealTimeMode.INFOS, + RealTimeMode.OFF, + RealTimeMode.REALTIME, + RealTimeMode.SERVER_DEFAULT, + ], + None, + ] = None, + tariff: Union[bool, None] = None, + messages: bool = False, + ) -> List[Trip]: """Reconstructing a trip can be achieved using the reconstruction context provided by any trip result in the `ctx_recon` attribute of `Trip` object. The result will be a true copy of the original trip search result given - that the underlying data did not change. + that the underlying data did not change. - More detailed request is available as `raw.trip_recon()`, however returns `dict` instead of `List[Trip]`. + More detailed request is available as `raw.trip_recon()`, however returns `dict` instead of `List[Trip]`. ### Args: * context (`Union[str, Journey]`): Specifies the reconstruction context. @@ -744,20 +817,20 @@ class Client(): ### Returns: * List[Trip]: List of `Trip` objects. Empty list if none found. - """ - + """ + if real_time_mode == None: real_time_mode = None else: real_time_mode = real_time_mode.code - + if isinstance(context, Trip): context = context.ctx_recon trips = [] trips_raw = raw_trip_recon( accessId=self.access_id, - ctx=context, # type: ignore + ctx=context, # type: ignore date=date, matchRtType=match_real_time, enableReplacements=enable_replacements, @@ -767,7 +840,7 @@ class Client(): depU=departure_dev_upper, passlist=passlist, showPassingPoints=passing_points, - rtMode=real_time_mode, # type: ignore + rtMode=real_time_mode, # type: ignore tariff=tariff, trafficMessages=messages, ) @@ -775,7 +848,6 @@ class Client(): find_exception(trips_raw) if "Trip" in trips_raw: - for trip in trips_raw["Trip"]: - trips.append(Trip(trip)) + trips.extend(Trip(trip) for trip in trips_raw["Trip"]) - return trips \ No newline at end of file + return trips diff --git a/src/pyrmv/classes/Gis.py b/src/pyrmv/classes/Gis.py index b0c3990..ff972b6 100644 --- a/src/pyrmv/classes/Gis.py +++ b/src/pyrmv/classes/Gis.py @@ -1,11 +1,13 @@ +from typing import Any, Mapping + from isodate import parse_duration -class Gis(): - """Gis object.""" - - def __init__(self, ref: str, route: dict): - + +class Gis: + """Gis object.""" + + def __init__(self, ref: str, route: Mapping[str, Any]): self.ref = ref self.dist = route["dist"] self.duration = parse_duration(route["durS"]) - self.geo = route["dirGeo"] \ No newline at end of file + self.geo = route["dirGeo"] diff --git a/src/pyrmv/classes/Journey.py b/src/pyrmv/classes/Journey.py index 2f08d7e..a2deca4 100644 --- a/src/pyrmv/classes/Journey.py +++ b/src/pyrmv/classes/Journey.py @@ -1,22 +1,22 @@ -from pyrmv.classes.Stop import Stop +from typing import Any, Mapping + from pyrmv.classes.Message import Message +from pyrmv.classes.Stop import Stop -class Journey(): - """Journey object.""" - def __init__(self, data: dict): +class Journey: + """Journey object.""" + + def __init__(self, data: Mapping[str, Any]): self.stops = [] self.ref = data["ref"] self.direction = data["Directions"]["Direction"][0]["value"] self.direction_flag = data["Directions"]["Direction"][0]["flag"] + self.stops.extend(Stop(stop) for stop in data["Stops"]["Stop"]) self.messages = [] - self.stops.extend(Stop(stop) for stop in data["Stops"]["Stop"]) - if "Messages" in data: - self.messages.extend( - Message(message) for message in data["Messages"]["Message"] - ) + self.messages.extend(Message(message) for message in data["Messages"]["Message"]) def __str__(self) -> str: - return f"Journey with total of {len(self.stops)} stops and {len(self.messages)} messages heading {self.direction} ({self.direction_flag})" \ No newline at end of file + return f"Journey with total of {len(self.stops)} stops and {len(self.messages)} messages heading {self.direction} ({self.direction_flag})" diff --git a/src/pyrmv/classes/Leg.py b/src/pyrmv/classes/Leg.py index 7de63bc..be3594d 100644 --- a/src/pyrmv/classes/Leg.py +++ b/src/pyrmv/classes/Leg.py @@ -1,43 +1,29 @@ +from typing import Any, Mapping + +from isodate import parse_duration + from pyrmv.classes.Gis import Gis from pyrmv.classes.Message import Message from pyrmv.classes.Stop import StopTrip -from isodate import parse_duration -class Leg(): - """Trip leg object.""" - - def __init__(self, data: dict): +class Leg: + """Trip leg object.""" + + def __init__(self, data: Mapping[str, Any]): self.origin = StopTrip(data["Origin"]) self.destination = StopTrip(data["Destination"]) - - if "GisRef" in data: - self.gis = Gis(data["GisRef"]["ref"], data["GisRoute"]) - else: - self.gis = None - + self.gis = ( + None if "GisRef" not in data else Gis(data["GisRef"]["ref"], data["GisRoute"]) + ) + self.messages = [] self.index = data["idx"] self.name = data["name"] self.type = data["type"] - - if "direction" in data: - self.direction = data["direction"] - else: - self.direction = None - - self.messages = [] - if "Messages" in data: - for message in data["Messages"]["Message"]: - self.messages.append(Message(message)) - - if "number" in data: - self.number = data["number"] - else: - self.number = None - + self.direction = data.get("direction") + self.number = data.get("number") self.duration = parse_duration(data["duration"]) - - if "dist" in data: - self.distance = data["dist"] - else: - self.distance = None \ No newline at end of file + self.distance = data.get("dist") + + if "Messages" in data: + self.messages.extend(Message(message) for message in data["Messages"]["Message"]) diff --git a/src/pyrmv/classes/Message.py b/src/pyrmv/classes/Message.py index f93754d..4b151bc 100644 --- a/src/pyrmv/classes/Message.py +++ b/src/pyrmv/classes/Message.py @@ -1,25 +1,29 @@ -from pyrmv.classes.Stop import Stop from datetime import datetime +from typing import Any, Mapping + from isodate import parse_duration -class Url(): - """Traffic message channel url object.""" +from pyrmv.classes.Stop import Stop - def __init__(self, data: dict) -> None: + +class Url: + """Traffic message channel url object.""" + + def __init__(self, data: Mapping[str, Any]) -> None: self.name = data["name"] self.url = data["url"] def __str__(self) -> str: return f"{self.name}: {self.url}" -class Channel(): - """Traffic message channel object.""" - def __init__(self, data: dict) -> None: +class Channel: + """Traffic message channel object.""" + + def __init__(self, data: Mapping[str, Any]) -> None: self.name = data["name"] url = [] - for link in url: - url.append(Url(link)) + url.extend(Url(link) for link in url) self.url = url self.time_start = datetime.strptime(data["validFromTime"], "%H:%M:%S") self.date_start = datetime.strptime(data["validFromDate"], "%Y-%m-%d") @@ -30,30 +34,17 @@ class Channel(): return f"{self.name}: from {self.time_start} {self.date_start} until {self.time_end} {self.date_end}" -class Message(): - """Traffic message object.""" - - def __init__(self, data: dict) -> None: +class Message: + """Traffic message object.""" + def __init__(self, data: Mapping[str, Any]) -> None: self.affected_stops = [] - if "affectedStops" in data: - for stop in data["affectedStops"]["StopLocation"]: - self.affected_stops.append(Stop(stop)) - - if "validFromStop" in data: - self.valid_from_stop = Stop(data["validFromStop"]) - else: - self.valid_from_stop = None - - if "validToStop" in data: - self.valid_to_stop = Stop(data["validToStop"]) - else: - self.valid_to_stop = None - + self.valid_from_stop = ( + None if "validFromStop" not in data else Stop(data["validFromStop"]) + ) + self.valid_to_stop = None if "validToStop" not in data else Stop(data["validToStop"]) self.channels = [] - for channel in data["channel"]: - self.channels.append(Channel(channel)) - + self.channels.extend(Channel(channel) for channel in data["channel"]) self.id = data["id"] self.active = data["act"] self.head = data["head"] @@ -74,11 +65,12 @@ class Message(): self.date_modified = datetime.strptime(data["modDate"], "%Y-%m-%d") self.daily_start = datetime.strptime(data["dailyStartingAt"], "%H:%M:%S") self.daily_duration = parse_duration(data["dailyDuration"]) + self.base_type = data["baseType"] if "baseType" in data else None - if "baseType" in data: - self.base_type = data["baseType"] - else: - self.base_type = None + if "affectedStops" in data: + self.affected_stops.extend( + Stop(stop) for stop in data["affectedStops"]["StopLocation"] + ) def __str__(self) -> str: - return f"{self.base_type} message with priority {self.products} valid from {self.time_start.time()} {self.date_start.date()} until {self.time_end.time()} {self.date_end.date()}: {self.head} - {self.lead}" \ No newline at end of file + return f"{self.base_type} message with priority {self.products} valid from {self.time_start.time()} {self.date_start.date()} until {self.time_end.time()} {self.date_end.date()}: {self.head} - {self.lead}" diff --git a/src/pyrmv/classes/Stop.py b/src/pyrmv/classes/Stop.py index fbd1d77..e197e1c 100644 --- a/src/pyrmv/classes/Stop.py +++ b/src/pyrmv/classes/Stop.py @@ -1,54 +1,32 @@ from datetime import datetime -class Stop(): - """Stop object.""" - - def __init__(self, data: dict): +class Stop: + """Stop object.""" + def __init__(self, data: dict): self.name = data["name"] self.id = data["id"] - - if "extId" in data: - self.ext_id = data["extId"] - else: - self.ext_id = None - - if "description" in data: - self.description = data["description"] - else: - self.description = None - + self.ext_id = data.get("extId") + self.description = data.get("description") self.lon = data["lon"] self.lat = data["lat"] - - if "routeIdx" in data: - self.route_index = data["routeIdx"] - else: - self.route_index = None - - if "arrTrack" in data: - self.track_arrival = data["arrTrack"] - else: - self.track_arrival = None - - if "depTrack" in data: - self.track_departure = data["depTrack"] - else: - self.track_departure = None + self.route_index = data.get("routeIdx") + self.track_arrival = data.get("arrTrack") + self.track_departure = data.get("depTrack") def __str__(self) -> str: return f"Stop {self.name} at {self.lon}, {self.lat}" + class StopTrip(Stop): - """Trip stop object. It's like a Stop object, but with a date and time.""" + """Trip stop object. It's like a Stop object, but with a date and time.""" def __init__(self, data: dict): - self.type = data["type"] self.date = datetime.strptime(data["date"], "%Y-%m-%d") self.time = datetime.strptime(data["time"], "%H:%M:%S") super().__init__(data) def __str__(self) -> str: - return f"Stop {self.name} at {self.lon}, {self.lat} at {self.time.time()} {self.date.date()}" \ No newline at end of file + return f"Stop {self.name} at {self.lon}, {self.lat} at {self.time.time()} {self.date.date()}" diff --git a/src/pyrmv/classes/Trip.py b/src/pyrmv/classes/Trip.py index 7422d12..809d85e 100644 --- a/src/pyrmv/classes/Trip.py +++ b/src/pyrmv/classes/Trip.py @@ -1,37 +1,28 @@ -from pyrmv.classes.Leg import Leg -from pyrmv.classes.Stop import StopTrip from isodate import parse_duration -class Trip(): - """Trip object.""" - +from pyrmv.classes.Leg import Leg +from pyrmv.classes.Stop import StopTrip + + +class Trip: + """Trip object.""" + def __init__(self, data: dict): - self.raw_data = data self.origin = StopTrip(data["Origin"]) self.destination = StopTrip(data["Destination"]) - self.legs = [] - for leg in data["LegList"]["Leg"]: - self.legs.append(Leg(leg)) - + self.legs.extend(Leg(leg) for leg in data["LegList"]["Leg"]) self.calculation = data["calculation"] self.index = data["idx"] self.id = data["tripId"] self.ctx_recon = data["ctxRecon"] self.duration = parse_duration(data["duration"]) - - if "rtDuration" in data: - self.real_time_duration = parse_duration(data["rtDuration"]) - else: - self.real_time_duration = None - + self.real_time_duration = ( + None if "rtDuration" not in data else parse_duration(data["rtDuration"]) + ) self.checksum = data["checksum"] - - if "transferCount" in data: - self.transfer_count = data["transferCount"] - else: - self.transfer_count = 0 + self.transfer_count = data.get("transferCount", 0) def __str__(self) -> str: - return f"Trip from {self.origin.name} to {self.destination.name} lasting {self.duration} ({self.real_time_duration}) with {len(self.legs)} legs and {self.transfer_count} transfers" \ No newline at end of file + return f"Trip from {self.origin.name} to {self.destination.name} lasting {self.duration} ({self.real_time_duration}) with {len(self.legs)} legs and {self.transfer_count} transfers" diff --git a/src/pyrmv/classes/__init__.py b/src/pyrmv/classes/__init__.py index c0d5e4b..ab6bb04 100644 --- a/src/pyrmv/classes/__init__.py +++ b/src/pyrmv/classes/__init__.py @@ -1,9 +1,9 @@ from .Board import BoardArrival, BoardDeparture, LineArrival, LineDeparture +from .Client import Client from .Gis import Gis from .Journey import Journey from .Leg import Leg -from .Message import Message, Channel, Url +from .Message import Channel, Message, Url from .Stop import Stop, StopTrip from .Ticket import Ticket from .Trip import Trip -from .Client import Client \ No newline at end of file diff --git a/src/pyrmv/const/__init__.py b/src/pyrmv/const/__init__.py index e69de29..ffb3cc7 100644 --- a/src/pyrmv/const/__init__.py +++ b/src/pyrmv/const/__init__.py @@ -0,0 +1 @@ +from .product import PRODUCTS diff --git a/src/pyrmv/const/product.py b/src/pyrmv/const/product.py index fe6087e..84794ba 100644 --- a/src/pyrmv/const/product.py +++ b/src/pyrmv/const/product.py @@ -17,4 +17,4 @@ PRODUCTS: Dict[str, int] = { "ferry": 256, "taxi": 512, "bahn": 1024, -} \ No newline at end of file +} diff --git a/src/pyrmv/enums/__init__.py b/src/pyrmv/enums/__init__.py index 425b262..92cffb6 100644 --- a/src/pyrmv/enums/__init__.py +++ b/src/pyrmv/enums/__init__.py @@ -1,10 +1,10 @@ -from .product import Product -from .rt_mode import RealTimeMode +from .aff_journey_mode import AffectedJourneyMode +from .aff_journey_stop_mode import AffectedJourneyStopMode +from .board_type import BoardArrivalType, BoardDepartureType +from .filter_mode import FilterMode from .lang import Language from .location_type import LocationType -from .selection_mode import SelectionMode +from .product import Product +from .rt_mode import RealTimeMode from .search_mode import SearchMode -from .filter_mode import FilterMode -from .board_type import BoardArrivalType, BoardDepartureType -from .aff_journey_mode import AffectedJourneyMode -from .aff_journey_stop_mode import AffectedJourneyStopMode \ No newline at end of file +from .selection_mode import SelectionMode diff --git a/src/pyrmv/enums/aff_journey_mode.py b/src/pyrmv/enums/aff_journey_mode.py index cf67c93..15d7e96 100644 --- a/src/pyrmv/enums/aff_journey_mode.py +++ b/src/pyrmv/enums/aff_journey_mode.py @@ -1,6 +1,8 @@ from enum import auto + from .auto_name import AutoName + class AffectedJourneyMode(AutoName): """Enumeration used to declare types of HIM search modes.""" @@ -8,4 +10,4 @@ class AffectedJourneyMode(AutoName): "Return affected journeys." OFF = auto() - "Do not return affected journeys." \ No newline at end of file + "Do not return affected journeys." diff --git a/src/pyrmv/enums/aff_journey_stop_mode.py b/src/pyrmv/enums/aff_journey_stop_mode.py index 85066ae..d21034f 100644 --- a/src/pyrmv/enums/aff_journey_stop_mode.py +++ b/src/pyrmv/enums/aff_journey_stop_mode.py @@ -1,6 +1,8 @@ from enum import auto + from .auto_name import AutoName + class AffectedJourneyStopMode(AutoName): """Enumeration used to declare types of affected journey stops return modes.""" @@ -11,4 +13,4 @@ class AffectedJourneyStopMode(AutoName): "Return important stops of affected journeys." OFF = auto() - "Do not return stops of affected journeys." \ No newline at end of file + "Do not return stops of affected journeys." diff --git a/src/pyrmv/enums/auto_name.py b/src/pyrmv/enums/auto_name.py index fa8a5fe..d0c07cf 100644 --- a/src/pyrmv/enums/auto_name.py +++ b/src/pyrmv/enums/auto_name.py @@ -2,7 +2,9 @@ # https://github.com/pyrogram/pyrogram/blob/master/pyrogram/enums/auto_name.py from enum import Enum -from pyrmv.const.product import PRODUCTS + +from pyrmv.const import PRODUCTS + class AutoName(Enum): def __init__(self, code) -> None: @@ -14,6 +16,7 @@ class AutoName(Enum): def __repr__(self): return f"pyrmv.enums.{self}" + class AutoNameProduct(AutoName): def __init__(self, code) -> None: - self.code = PRODUCTS[code] \ No newline at end of file + self.code = PRODUCTS[code] diff --git a/src/pyrmv/enums/board_type.py b/src/pyrmv/enums/board_type.py index 426da65..0d4ccfa 100644 --- a/src/pyrmv/enums/board_type.py +++ b/src/pyrmv/enums/board_type.py @@ -1,9 +1,11 @@ from enum import auto + from .auto_name import AutoName + class BoardArrivalType(AutoName): - """Enumeration used to declare types of arrival board. - + """Enumeration used to declare types of arrival board. + * ARR - Arrival board as configured in HAFAS * ARR_EQUIVS - Arrival board with all journeys at any masts and equivalent stops * ARR_MAST - Arrival board at mast @@ -22,9 +24,10 @@ class BoardArrivalType(AutoName): ARR_STATION = auto() "Arrival board with all journeys at any masts of the requested station" + class BoardDepartureType(AutoName): - """Enumeration used to declare types of departure board. - + """Enumeration used to declare types of departure board. + * DEP - Departure board as configured in HAFAS * DEP_EQUIVS - Departure board with all journeys at any masts and equivalent stops * DEP_MAST - Departure board at mast @@ -41,4 +44,4 @@ class BoardDepartureType(AutoName): "Departure board at mast" DEP_STATION = auto() - "Departure board with all journeys at any masts of the requested station" \ No newline at end of file + "Departure board with all journeys at any masts of the requested station" diff --git a/src/pyrmv/enums/filter_mode.py b/src/pyrmv/enums/filter_mode.py index 192c3c0..b7ce25d 100644 --- a/src/pyrmv/enums/filter_mode.py +++ b/src/pyrmv/enums/filter_mode.py @@ -1,9 +1,11 @@ from enum import auto + from .auto_name import AutoName + class FilterMode(AutoName): - """Enumeration used to declare filters for nearby searches. - + """Enumeration used to declare filters for nearby searches. + * DIST_PERI - Accentuate matches. Matches in the radius are first * EXCL_PERI - Returns matches inside the radius only * SLCT_PERI - Matches in the radius are excluded. Returns matches outside the radius only @@ -16,4 +18,4 @@ class FilterMode(AutoName): "Returns matches inside the radius only." SLCT_PERI = auto() - "Matches in the radius are excluded. Returns matches outside the radius only." \ No newline at end of file + "Matches in the radius are excluded. Returns matches outside the radius only." diff --git a/src/pyrmv/enums/lang.py b/src/pyrmv/enums/lang.py index f87c13f..57cf286 100644 --- a/src/pyrmv/enums/lang.py +++ b/src/pyrmv/enums/lang.py @@ -1,24 +1,44 @@ from enum import auto + from .auto_name import AutoName + class Language(AutoName): """Enumeration used to declare locales as ISO-3166 codes (but only available in HAFAS ones).""" - DE = auto() - "German" + AR = auto() + "Arabic" + + CA = auto() + "Catalan, Valencian" DA = auto() "Danish" + DE = auto() + "German" + + EL = auto() + "Greek" + EN = auto() "English" ES = auto() "Spanish" + FI = auto() + "Finnish" + FR = auto() "French" + HI = auto() + "Hindi" + + HR = auto() + "Croatian" + HU = auto() "Hungarian" @@ -34,8 +54,26 @@ class Language(AutoName): PL = auto() "Polish" + RU = auto() + "Russian" + + SK = auto() + "Slovak" + + SL = auto() + "Slovenian" + SV = auto() "Swedish" + TL = auto() + "Tagalog" + TR = auto() - "Turkish" \ No newline at end of file + "Turkish" + + UR = auto() + "Urdu" + + ZH = auto() + "Chinese" diff --git a/src/pyrmv/enums/location_type.py b/src/pyrmv/enums/location_type.py index 9631444..45e4a94 100644 --- a/src/pyrmv/enums/location_type.py +++ b/src/pyrmv/enums/location_type.py @@ -1,9 +1,11 @@ from enum import auto + from .auto_name import AutoName + class LocationType(AutoName): - """Enumeration used to declare types of location filter. - + """Enumeration used to declare types of location filter. + * S - Search for station/stops only * A - Search for addresses only * P - Search for POIs only @@ -15,7 +17,7 @@ class LocationType(AutoName): * SPE - Search for stations/stops, POIs and entrypoints Note that not all location types may be available for a certain methods. - Make sure that selected type is supported by method by looking up + Make sure that selected type is supported by method by looking up its acceptable types in argument description. """ @@ -44,4 +46,4 @@ class LocationType(AutoName): "Search in all existing location pools" SPE = auto() - "Search for stations/stops, POIs and entrypoints" \ No newline at end of file + "Search for stations/stops, POIs and entrypoints" diff --git a/src/pyrmv/enums/product.py b/src/pyrmv/enums/product.py index 45bf631..c0c6cb6 100644 --- a/src/pyrmv/enums/product.py +++ b/src/pyrmv/enums/product.py @@ -1,6 +1,8 @@ from enum import auto + from .auto_name import AutoNameProduct + class Product(AutoNameProduct): """Enumeration used to declare types of transport.""" @@ -11,7 +13,7 @@ class Product(AutoNameProduct): "InterCity (commonly abbreviated IC on timetables and tickets) is the classification applied to certain long-distance passenger train services in Europe. Such trains (in contrast to regional, local, or commuter trains) generally call at major stations only." EC = auto() - "EuroCity, abbreviated as EC, is a cross-border train category within the European inter-city rail network. In contrast to trains allocated to the lower-level \"IC\" (InterCity) category, EC trains are international services that meet 20 criteria covering comfort, speed, food service, and cleanliness." + 'EuroCity, abbreviated as EC, is a cross-border train category within the European inter-city rail network. In contrast to trains allocated to the lower-level "IC" (InterCity) category, EC trains are international services that meet 20 criteria covering comfort, speed, food service, and cleanliness.' R = auto() "Regional rail, also known as local trains and stopping trains, are passenger rail services that operate between towns and cities. These trains operate with more stops over shorter distances than inter-city rail, but fewer stops and faster service than commuter rail." @@ -44,4 +46,4 @@ class Product(AutoNameProduct): "A taxi, also known as a taxicab or simply a cab, is a type of vehicle for hire with a driver, used by a single passenger or small group of passengers, often for a non-shared ride." BAHN = auto() - "Rail transport (also known as train transport) is a means of transport that transfers passengers and goods on wheeled vehicles running on rails, which are located on tracks. In contrast to road transport, where the vehicles run on a prepared flat surface, rail vehicles (rolling stock) are directionally guided by the tracks on which they run." \ No newline at end of file + "Rail transport (also known as train transport) is a means of transport that transfers passengers and goods on wheeled vehicles running on rails, which are located on tracks. In contrast to road transport, where the vehicles run on a prepared flat surface, rail vehicles (rolling stock) are directionally guided by the tracks on which they run." diff --git a/src/pyrmv/enums/rt_mode.py b/src/pyrmv/enums/rt_mode.py index 97c1b4b..c5e5f32 100644 --- a/src/pyrmv/enums/rt_mode.py +++ b/src/pyrmv/enums/rt_mode.py @@ -1,6 +1,8 @@ from enum import auto + from .auto_name import AutoName + class RealTimeMode(AutoName): """Enumeration used to declare types of real-time traffic.""" @@ -17,4 +19,4 @@ class RealTimeMode(AutoName): "Search on real-time data: Connections are computed on the basis of real-time data, using planned schedule only whenever no real-time data is available. All connections computed are feasible with respect to the currently known real-time situation. Additional trains (supplied via real-time feed) will be found if these are part of a fast, comfortable, or direct connection (or economic connection, if economic search is activated)." SERVER_DEFAULT = auto() - "One of the other real-times modes used by default for RMV." \ No newline at end of file + "One of the other real-times modes used by default for RMV." diff --git a/src/pyrmv/enums/search_mode.py b/src/pyrmv/enums/search_mode.py index e6956b9..150aafc 100644 --- a/src/pyrmv/enums/search_mode.py +++ b/src/pyrmv/enums/search_mode.py @@ -1,6 +1,8 @@ from enum import auto + from .auto_name import AutoName + class SearchMode(AutoName): """Enumeration used to declare types of HIM search modes.""" @@ -11,4 +13,4 @@ class SearchMode(AutoName): "Iterate over all HIM messages available." TFMATCH = auto() - "Uses filters defined `metas` parameter." \ No newline at end of file + "Uses filters defined `metas` parameter." diff --git a/src/pyrmv/enums/selection_mode.py b/src/pyrmv/enums/selection_mode.py index 4bbd9fb..7724be6 100644 --- a/src/pyrmv/enums/selection_mode.py +++ b/src/pyrmv/enums/selection_mode.py @@ -1,9 +1,11 @@ from enum import auto + from .auto_name import AutoName + class SelectionMode(AutoName): """Enumeration used to declare location selection modes. - + * SLCT_A - Selectable * SLCT_N - Not selectable """ @@ -12,4 +14,4 @@ class SelectionMode(AutoName): "Selectable" SLCT_N = auto() - "Not selectable" \ No newline at end of file + "Not selectable" diff --git a/src/pyrmv/errors/__init__.py b/src/pyrmv/errors/__init__.py index e69de29..1671d6b 100644 --- a/src/pyrmv/errors/__init__.py +++ b/src/pyrmv/errors/__init__.py @@ -0,0 +1,7 @@ +from .api_errors import * +from .int_errors import * +from .not_ready import * +from .ps_errors import * +from .sot_errors import * +from .svc_errors import * +from .unknown_error import * diff --git a/src/pyrmv/errors/api_errors.py b/src/pyrmv/errors/api_errors.py index 8119d16..1f057ba 100644 --- a/src/pyrmv/errors/api_errors.py +++ b/src/pyrmv/errors/api_errors.py @@ -2,32 +2,38 @@ class ApiAuthError(Exception): """ Access denied for accessId provided. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class ApiQuotaError(Exception): """ Quota exceeded for accessId provided. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class ApiTooManyRequests(Exception): """ Too many requests. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class ApiParamError(Exception): """Exception raised for errors in the input arguments. @@ -42,14 +48,16 @@ class ApiParamError(Exception): super().__init__(self.errorText) def __str__(self): - return f'{self.errorCode} -> {self.errorText}' + return f"{self.errorCode} -> {self.errorText}" + class ApiFormatError(Exception): """ Response format not supported. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): - return self.__doc__ \ No newline at end of file + return self.__doc__ diff --git a/src/pyrmv/errors/int_errors.py b/src/pyrmv/errors/int_errors.py index b92dde8..cc5fc44 100644 --- a/src/pyrmv/errors/int_errors.py +++ b/src/pyrmv/errors/int_errors.py @@ -2,28 +2,33 @@ class IntError(Exception): """ Internal RMV server error. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class IntGatewayError(Exception): """ Communication error with RMV backend systems. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class IntTimeoutError(Exception): """ Timeout during service processing. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): - return self.__doc__ \ No newline at end of file + return self.__doc__ diff --git a/src/pyrmv/errors/not_ready.py b/src/pyrmv/errors/not_ready.py index 0ed3c03..b1c428e 100644 --- a/src/pyrmv/errors/not_ready.py +++ b/src/pyrmv/errors/not_ready.py @@ -2,8 +2,9 @@ class NotReadyYetError(Exception): """ This method is not finished yet. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): - return self.__doc__ \ No newline at end of file + return self.__doc__ diff --git a/src/pyrmv/errors/ps_errors.py b/src/pyrmv/errors/ps_errors.py index 83ac32c..adc8392 100644 --- a/src/pyrmv/errors/ps_errors.py +++ b/src/pyrmv/errors/ps_errors.py @@ -6,8 +6,9 @@ class PsIncorrectParamError(Exception): forward/backward from the end/beginning of the connection. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): - return self.__doc__ \ No newline at end of file + return self.__doc__ diff --git a/src/pyrmv/errors/sot_errors.py b/src/pyrmv/errors/sot_errors.py index 6b2459f..cc99f9b 100644 --- a/src/pyrmv/errors/sot_errors.py +++ b/src/pyrmv/errors/sot_errors.py @@ -2,48 +2,57 @@ class SotAlreadyArrivedError(Exception): """ Trip already arrived. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SotNotStartedError(Exception): """ Trip not started. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SotCancelledError(Exception): """ Trip cancelled. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SotAllTrainsFilteredError(Exception): """ All trips filtered. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SotStayOnTripError(Exception): """ No change. Stay on trip. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): - return self.__doc__ \ No newline at end of file + return self.__doc__ diff --git a/src/pyrmv/errors/svc_errors.py b/src/pyrmv/errors/svc_errors.py index c2073ad..b28b7e6 100644 --- a/src/pyrmv/errors/svc_errors.py +++ b/src/pyrmv/errors/svc_errors.py @@ -12,134 +12,160 @@ class SvcParamError(Exception): super().__init__(self.errorText) def __str__(self): - return f'{self.errorCode} -> {self.errorText}' + return f"{self.errorCode} -> {self.errorText}" + class SvcLocationError(Exception): """ Location missing or invalid. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcLocationArrivalError(Exception): """ Arrival location missing or invalid. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcLocationDepartureError(Exception): """ Departure location missing or invalid. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcLocationViaError(Exception): """ Unknown change stop. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcLocationEqualError(Exception): """ Origin/destination or vias are equal. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcLocationNearError(Exception): """ Origin and destination are too close. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcDatetimeError(Exception): """ Date/time are missing or invalid. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcDatetimePeriodError(Exception): """ Date/time are not in timetable or allowed period. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcProductError(Exception): """ Product field missing or invalid. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcContextError(Exception): """ Context is invalid. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcNoResultError(Exception): """ No result found. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcSearchError(Exception): """ Unsuccessful search. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): return self.__doc__ + class SvcNoMatchError(Exception): """ No match found. """ + def __init__(self): super().__init__(self.__doc__) def __str__(self): - return self.__doc__ \ No newline at end of file + return self.__doc__ diff --git a/src/pyrmv/errors/unknown_error.py b/src/pyrmv/errors/unknown_error.py index 0f56ca6..786ffae 100644 --- a/src/pyrmv/errors/unknown_error.py +++ b/src/pyrmv/errors/unknown_error.py @@ -12,4 +12,4 @@ class UnknownError(Exception): super().__init__(self.errorText) def __str__(self): - return f'{self.errorCode} -> {self.errorText}' \ No newline at end of file + return f"{self.errorCode} -> {self.errorText}" diff --git a/src/pyrmv/raw/__init__.py b/src/pyrmv/raw/__init__.py index 62fb3fd..3c8c095 100644 --- a/src/pyrmv/raw/__init__.py +++ b/src/pyrmv/raw/__init__.py @@ -5,4 +5,4 @@ from .journey_detail import journey_detail from .stop_by_coords import stop_by_coords from .stop_by_name import stop_by_name from .trip_find import trip_find -from .trip_recon import trip_recon \ No newline at end of file +from .trip_recon import trip_recon diff --git a/src/pyrmv/raw/board_arrival.py b/src/pyrmv/raw/board_arrival.py index 9b8f347..fee0b99 100644 --- a/src/pyrmv/raw/board_arrival.py +++ b/src/pyrmv/raw/board_arrival.py @@ -1,6 +1,7 @@ -from requests import get from datetime import datetime, timedelta from typing import Union + +from requests import get from xmltodict import parse as xmlparse try: @@ -8,32 +9,34 @@ try: except ImportError: from typing_extensions import Literal + # 2.25. Arrival Board (arrivalBoard) -def board_arrival(accessId: str, - json: bool = True, - id: Union[str, None] = None, - extId: Union[str, None] = None, - direction: Union[str, None] = None, - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, - duration: Union[int, timedelta] = 60, - maxJourneys: int = -1, - products: Union[int, None] = None, - operators: Union[str, list, None] = None, - lines: Union[str, list, None] = None, - filterEquiv: bool = True, - attributes: Union[str, list, None] = None, - platforms: Union[str, list, None] = None, - passlist: bool = False, - boardType: Literal["ARR", "ARR_EQUIVS", "ARR_MAST", "ARR_STATION"] = "ARR" - ) -> dict: +def board_arrival( + accessId: str, + json: bool = True, + id: Union[str, None] = None, + extId: Union[str, None] = None, + direction: Union[str, None] = None, + date: Union[str, datetime, None] = None, + time: Union[str, datetime, None] = None, + duration: Union[int, timedelta] = 60, + maxJourneys: int = -1, + products: Union[int, None] = None, + operators: Union[str, list, None] = None, + lines: Union[str, list, None] = None, + filterEquiv: bool = True, + attributes: Union[str, list, None] = None, + platforms: Union[str, list, None] = None, + passlist: bool = False, + boardType: Literal["ARR", "ARR_EQUIVS", "ARR_MAST", "ARR_STATION"] = "ARR", +) -> dict: """The arrival board can be retrieved by a call to the arrivalBoard service. This method will return the next - arrivals from a given point in time within a duration covered time span. The default duration size is 60 minutes. + arrivals from a given point in time within a duration covered time span. The default duration size is 60 minutes. Note: The result list always contains all arrivals running the the last minute found even if the requested - maximum was overrun. + maximum was overrun. - Read more about this in section 2.25. "Arrival Board (arrivalBoard)" of HAFAS ReST Documentation. + Read more about this in section 2.25. "Arrival Board (arrivalBoard)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -56,14 +59,10 @@ def board_arrival(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): if str(var) == "date": @@ -74,16 +73,12 @@ def board_arrival(accessId: str, payload[str(var)] = val elif str(var) == "time": if val != None: - if isinstance(val, datetime): - payload[str(var)] = val.strftime("%H:%M") - else: - payload[str(var)] = val + payload[str(var)] = ( + val.strftime("%H:%M") if isinstance(val, datetime) else val + ) elif str(var) == "duration": if val != None: - if isinstance(val, timedelta): - payload[str(var)] = val.minutes # type: ignore - else: - payload[str(var)] = val + payload[str(var)] = val.minutes if isinstance(val, timedelta) else val elif str(var) == "boardType": if val != None: payload["type"] = val.upper() @@ -93,7 +88,4 @@ def board_arrival(accessId: str, output = get("https://www.rmv.de/hapi/arrivalBoard", params=payload, headers=headers) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/raw/board_departure.py b/src/pyrmv/raw/board_departure.py index ed30539..57e76b2 100644 --- a/src/pyrmv/raw/board_departure.py +++ b/src/pyrmv/raw/board_departure.py @@ -1,6 +1,7 @@ -from requests import get from datetime import datetime, timedelta from typing import Union + +from requests import get from xmltodict import parse as xmlparse try: @@ -8,33 +9,35 @@ try: except ImportError: from typing_extensions import Literal + # 2.24. Departure Board (departureBoard) -def board_departure(accessId: str, - json: bool = True, - id: Union[str, None] = None, - extId: Union[str, None] = None, - direction: Union[str, None] = None, - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, - duration: Union[int, timedelta] = 60, - maxJourneys: int = -1, - products: Union[int, None] = None, - operators: Union[str, list, None] = None, - lines: Union[str, list, None] = None, - filterEquiv: bool = True, - attributes: Union[str, list, None] = None, - platforms: Union[str, list, None] = None, - passlist: bool = False, - boardType: Literal["DEP", "DEP_EQUIVS", "DEP_MAST", "DEP_STATION"] = "DEP" - ) -> dict: +def board_departure( + accessId: str, + json: bool = True, + id: Union[str, None] = None, + extId: Union[str, None] = None, + direction: Union[str, None] = None, + date: Union[str, datetime, None] = None, + time: Union[str, datetime, None] = None, + duration: Union[int, timedelta] = 60, + maxJourneys: int = -1, + products: Union[int, None] = None, + operators: Union[str, list, None] = None, + lines: Union[str, list, None] = None, + filterEquiv: bool = True, + attributes: Union[str, list, None] = None, + platforms: Union[str, list, None] = None, + passlist: bool = False, + boardType: Literal["DEP", "DEP_EQUIVS", "DEP_MAST", "DEP_STATION"] = "DEP", +) -> dict: """The separture board can be retrieved by a call to the departureBoard service. This method will return the next departures (or less if not existing) from a given point in time within a duration covered time span. The - default duration size is 60 minutes. + default duration size is 60 minutes. Note: The result list always contains all departures running the the last minute found even if the requested - maximum was overrun. + maximum was overrun. - Read more about this in section 2.24. "Departure Board (departureBoard)" of HAFAS ReST Documentation. + Read more about this in section 2.24. "Departure Board (departureBoard)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -57,14 +60,10 @@ def board_departure(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): if str(var) == "date": @@ -75,16 +74,12 @@ def board_departure(accessId: str, payload[str(var)] = val elif str(var) == "time": if val != None: - if isinstance(val, datetime): - payload[str(var)] = val.strftime("%H:%M") - else: - payload[str(var)] = val + payload[str(var)] = ( + val.strftime("%H:%M") if isinstance(val, datetime) else val + ) elif str(var) == "duration": if val != None: - if isinstance(val, timedelta): - payload[str(var)] = val.minutes # type: ignore - else: - payload[str(var)] = val + payload[str(var)] = val.minutes if isinstance(val, timedelta) else val elif str(var) == "boardType": if val != None: payload["type"] = val.upper() @@ -94,7 +89,4 @@ def board_departure(accessId: str, output = get("https://www.rmv.de/hapi/departureBoard", params=payload, headers=headers) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/raw/him_search.py b/src/pyrmv/raw/him_search.py index 0ebf5fe..ae38717 100644 --- a/src/pyrmv/raw/him_search.py +++ b/src/pyrmv/raw/him_search.py @@ -1,55 +1,58 @@ -from requests import get -from typing import OrderedDict, Union -from xmltodict import parse as xmlparse from datetime import datetime +from typing import OrderedDict, Union -from pyrmv.utility.weekdays_bitmask import weekdays_bitmask +from requests import get +from xmltodict import parse as xmlparse + +from pyrmv.utility import weekdays_bitmask try: from typing import Literal except ImportError: from typing_extensions import Literal + # 2.37. HIM Search (himsearch) -def him_search(accessId: str, - json: bool = True, - dateB: Union[str, datetime, None] = None, - dateE: Union[str, datetime, None] = None, - timeB: Union[str, datetime, None] = None, - timeE: Union[str, datetime, None] = None, - weekdays: Union[str, OrderedDict[str, bool], None] = None, - himIds: Union[str, list, None] = None, - hierarchicalView: bool = False, - operators: Union[str, list, None] = None, - categories: Union[str, list, None] = None, - channels: Union[str, list, None] = None, - companies: Union[str, list, None] = None, - lines: Union[str, list, None] = None, - lineids: Union[str, list, None] = None, - stations: Union[str, list, None] = None, - fromstation: Union[str, None] = None, - tostation: Union[str, None] = None, - bothways: Union[bool, None] = None, - trainnames: Union[str, list, None] = None, - metas: Union[str, list, None] = None, - himcategory: Union[str, None] = None, - himtags: Union[str, list, None] = None, - regions: Union[str, list, None] = None, - himtext: Union[str, list, None] = None, - himtexttags: Union[str, list, None] = None, - additionalfields: Union[str, list, dict, None] = None, - poly: bool = False, - searchmode: Union[Literal["MATCH", "NOMATCH", "TFMATCH"], None] = None, - affectedJourneyMode: Union[Literal["ALL", "OFF"], None] = None, - affectedJourneyStopMode: Union[Literal["ALL", "IMP", "OFF"], None] = None, - orderBy: Union[str, list, None] = None, - minprio: Union[str, int, None] = None, - maxprio: Union[str, int, None] = None - ) -> dict: +def him_search( + accessId: str, + json: bool = True, + dateB: Union[str, datetime, None] = None, + dateE: Union[str, datetime, None] = None, + timeB: Union[str, datetime, None] = None, + timeE: Union[str, datetime, None] = None, + weekdays: Union[str, OrderedDict[str, bool], None] = None, + himIds: Union[str, list, None] = None, + hierarchicalView: bool = False, + operators: Union[str, list, None] = None, + categories: Union[str, list, None] = None, + channels: Union[str, list, None] = None, + companies: Union[str, list, None] = None, + lines: Union[str, list, None] = None, + lineids: Union[str, list, None] = None, + stations: Union[str, list, None] = None, + fromstation: Union[str, None] = None, + tostation: Union[str, None] = None, + bothways: Union[bool, None] = None, + trainnames: Union[str, list, None] = None, + metas: Union[str, list, None] = None, + himcategory: Union[str, None] = None, + himtags: Union[str, list, None] = None, + regions: Union[str, list, None] = None, + himtext: Union[str, list, None] = None, + himtexttags: Union[str, list, None] = None, + additionalfields: Union[str, list, dict, None] = None, + poly: bool = False, + searchmode: Union[Literal["MATCH", "NOMATCH", "TFMATCH"], None] = None, + affectedJourneyMode: Union[Literal["ALL", "OFF"], None] = None, + affectedJourneyStopMode: Union[Literal["ALL", "IMP", "OFF"], None] = None, + orderBy: Union[str, list, None] = None, + minprio: Union[str, int, None] = None, + maxprio: Union[str, int, None] = None, +) -> dict: """The himSearch will return a list of HIM messages if matched by the given criteria as well as affected products if any. - Read more about this in section 2.37. "HIM Search (himsearch)" of HAFAS ReST Documentation. + Read more about this in section 2.37. "HIM Search (himsearch)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -89,28 +92,23 @@ def him_search(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): - if str(var) in ["dateB", "dateE"]: + if str(var) in {"dateB", "dateE"}: if val != None: if isinstance(val, datetime): payload[str(var)] = val.strftime("%Y-%m-%d") else: payload[str(var)] = val - elif str(var) in ["timeB", "timeE"]: + elif str(var) in {"timeB", "timeE"}: if val != None: - if isinstance(val, datetime): - payload[str(var)] = val.strftime("%H:%M") - else: - payload[str(var)] = val + payload[str(var)] = ( + val.strftime("%H:%M") if isinstance(val, datetime) else val + ) elif str(var) == "weekdays": if val != None: if isinstance(val, OrderedDict): @@ -132,7 +130,4 @@ def him_search(accessId: str, output = get("https://www.rmv.de/hapi/himsearch", params=payload, headers=headers) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/raw/journey_detail.py b/src/pyrmv/raw/journey_detail.py index 56347a0..6aa9be8 100644 --- a/src/pyrmv/raw/journey_detail.py +++ b/src/pyrmv/raw/journey_detail.py @@ -1,6 +1,7 @@ from datetime import datetime -from requests import get from typing import Union + +from requests import get from xmltodict import parse as xmlparse try: @@ -8,27 +9,29 @@ try: except ImportError: from typing_extensions import Literal + # 2.26. Journey Detail (journeyDetail) -def journey_detail(accessId: str, - id: str, - json: bool = True, - date: Union[str, datetime, None] = None, - poly: bool = False, - polyEnc: Literal["DLT", "GPA", "N"] = "N", - showPassingPoints: bool = False, - rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None, - fromId: Union[str, None] = None, - fromIdx: Union[int, None] = None, - toId: Union[str, None] = None, - toIdx: Union[int, None] = None, - baim: bool = False - ) -> dict: +def journey_detail( + accessId: str, + id: str, + json: bool = True, + date: Union[str, datetime, None] = None, + poly: bool = False, + polyEnc: Literal["DLT", "GPA", "N"] = "N", + showPassingPoints: bool = False, + rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None, + fromId: Union[str, None] = None, + fromIdx: Union[int, None] = None, + toId: Union[str, None] = None, + toIdx: Union[int, None] = None, + baim: bool = False, +) -> dict: """The journey_detail method will deliver information about the complete route of a vehicle. The journey identifier is part of a trip or departureBoard response. It contains a list of all stops/stations of this journey including all departure and arrival times (with real-time data if available) and additional information like - specific attributes about facilities and other texts. + specific attributes about facilities and other texts. - Read more about this in section 2.26. "Journey Detail (journeyDetail)" of HAFAS ReST Documentation. + Read more about this in section 2.26. "Journey Detail (journeyDetail)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -47,14 +50,10 @@ def journey_detail(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): if str(var) == "rtMode": @@ -66,7 +65,4 @@ def journey_detail(accessId: str, output = get("https://www.rmv.de/hapi/journeyDetail", params=payload, headers=headers) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/raw/stop_by_coords.py b/src/pyrmv/raw/stop_by_coords.py index 160b2e4..1122d08 100644 --- a/src/pyrmv/raw/stop_by_coords.py +++ b/src/pyrmv/raw/stop_by_coords.py @@ -1,5 +1,6 @@ -from requests import get from typing import Union + +from requests import get from xmltodict import parse as xmlparse try: @@ -7,25 +8,29 @@ try: except ImportError: from typing_extensions import Literal -# 2.4. Location Search by Coordinate (location.nearbystops) -def stop_by_coords(accessId: str, - originCoordLat: Union[str, float], - originCoordLong: Union[str, float], - lang: Literal["de", "da", "en", "es", "fr", "hu", "it", "nl", "no", "pl", "sv", "tr"] = "en", - json: bool = True, - radius: Union[int, float] = 1000, - maxNo: int = 10, - stopType: Literal["S", "P", "SP", "SE", "SPE"] = "S", - locationSelectionMode: Union[Literal["SLCT_N", "SLCT_A"], None] = None, - products: Union[int, None] = None, - meta: Union[str, None] = None, - sattributes: Union[str, list, None] = None, - sinfotexts: Union[str, list, None] = None - ) -> dict: - """The location.nearbystops service returns a list of stops around a given center coordinate (within a - radius of 1000m). The returned results are ordered by their distance to the center coordinate. - Read more about this in section 2.4. "Location Search by Coordinate (location.nearbystops)" of HAFAS ReST Documentation. +# 2.4. Location Search by Coordinate (location.nearbystops) +def stop_by_coords( + accessId: str, + originCoordLat: Union[str, float], + originCoordLong: Union[str, float], + lang: Literal[ + "de", "da", "en", "es", "fr", "hu", "it", "nl", "no", "pl", "sv", "tr" + ] = "en", + json: bool = True, + radius: Union[int, float] = 1000, + maxNo: int = 10, + stopType: Literal["S", "P", "SP", "SE", "SPE"] = "S", + locationSelectionMode: Union[Literal["SLCT_N", "SLCT_A"], None] = None, + products: Union[int, None] = None, + meta: Union[str, None] = None, + sattributes: Union[str, list, None] = None, + sinfotexts: Union[str, list, None] = None, +) -> dict: + """The location.nearbystops service returns a list of stops around a given center coordinate (within a + radius of 1000m). The returned results are ordered by their distance to the center coordinate. + + Read more about this in section 2.4. "Location Search by Coordinate (location.nearbystops)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -44,14 +49,10 @@ def stop_by_coords(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): if str(var) == "stopType": @@ -64,9 +65,8 @@ def stop_by_coords(accessId: str, if val != None: payload[str(var)] = val - output = get("https://www.rmv.de/hapi/location.nearbystops", params=payload, headers=headers) + output = get( + "https://www.rmv.de/hapi/location.nearbystops", params=payload, headers=headers + ) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/raw/stop_by_name.py b/src/pyrmv/raw/stop_by_name.py index ac0adb8..f46f4c8 100644 --- a/src/pyrmv/raw/stop_by_name.py +++ b/src/pyrmv/raw/stop_by_name.py @@ -1,5 +1,6 @@ -from requests import get from typing import Union + +from requests import get from xmltodict import parse as xmlparse try: @@ -7,33 +8,37 @@ try: except ImportError: from typing_extensions import Literal + # 2.3. Location Search by Name (location.name) -def stop_by_name(accessId: str, - inputString: str, - lang: Literal["de", "da", "en", "es", "fr", "hu", "it", "nl", "no", "pl", "sv", "tr"] = "en", - json: bool = True, - maxNo: int = 10, - stopType: Literal["A", "ALL", "AP", "P", "S", "SA", "SP"] = "ALL", - locationSelectionMode: Union[Literal["SLCT_N", "SLCT_A"], None] = None, - products: Union[int, None] = None, - coordLat: Union[str, float, None] = None, - coordLong: Union[str, float, None] = None, - radius: Union[int, float] = 1000, - refineId: Union[str, None] = None, - meta: Union[str, None] = None, - stations: Union[str, list, None] = None, - sattributes: Union[str, list, None] = None, - filterMode: Literal["DIST_PERI", "EXCL_PERI", "SLCT_PERI"] = "DIST_PERI" - ) -> dict: +def stop_by_name( + accessId: str, + inputString: str, + lang: Literal[ + "de", "da", "en", "es", "fr", "hu", "it", "nl", "no", "pl", "sv", "tr" + ] = "en", + json: bool = True, + maxNo: int = 10, + stopType: Literal["A", "ALL", "AP", "P", "S", "SA", "SP"] = "ALL", + locationSelectionMode: Union[Literal["SLCT_N", "SLCT_A"], None] = None, + products: Union[int, None] = None, + coordLat: Union[str, float, None] = None, + coordLong: Union[str, float, None] = None, + radius: Union[int, float] = 1000, + refineId: Union[str, None] = None, + meta: Union[str, None] = None, + stations: Union[str, list, None] = None, + sattributes: Union[str, list, None] = None, + filterMode: Literal["DIST_PERI", "EXCL_PERI", "SLCT_PERI"] = "DIST_PERI", +) -> dict: """The location.name service can be used to perform a pattern matching of a user input and to retrieve a list of possible matches in the journey planner database. Possible matches might be stops/stations, points of - interest and addresses. + interest and addresses. The result is a list of possible matches (locations) where the user might pick one entry to perform a trip request with this location as origin or destination or to ask for a departure board or arrival board of this - location (stops/stations only). + location (stops/stations only). - Read more about this in section 2.3. "Location Search by Name (location.name)" of HAFAS ReST Documentation. + Read more about this in section 2.3. "Location Search by Name (location.name)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -55,14 +60,10 @@ def stop_by_name(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): if str(var) == "inputString": @@ -80,7 +81,4 @@ def stop_by_name(accessId: str, output = get("https://www.rmv.de/hapi/location.name", params=payload, headers=headers) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/raw/trip_find.py b/src/pyrmv/raw/trip_find.py index 19336a6..659632f 100644 --- a/src/pyrmv/raw/trip_find.py +++ b/src/pyrmv/raw/trip_find.py @@ -1,6 +1,7 @@ from datetime import datetime -from requests import get from typing import List, Union + +from requests import get from xmltodict import parse as xmlparse try: @@ -8,125 +9,103 @@ try: except ImportError: from typing_extensions import Literal -# 2.12. Trip Search (trip) -def trip_find(accessId: str, - lang: Literal["de", "da", "en", "es", "fr", "hu", "it", "nl", "no", "pl", "sv", "tr"] = "en", - json: bool = True, - originId: Union[str, None] = None, - originExtId: Union[str, None] = None, - originCoordLat: Union[str, float, None] = None, - originCoordLong: Union[str, float, None] = None, - originCoordName: Union[str, None] = None, - - destId: Union[str, None] = None, - destExtId: Union[str, None] = None, - destCoordLat: Union[str, float, None] = None, - destCoordLong: Union[str, float, None] = None, - destCoordName: Union[str, None] = None, - - via: Union[str, None] = None, - viaId: Union[str, None] = None, - viaWaitTime: int = 0, - - avoid: Union[str, None] = None, - avoidId: Union[str, None] = None, - - viaGis: Union[str, None] = None, - - changeTimePercent: int = 100, - minChangeTime: Union[int, None] = None, - maxChangeTime: Union[int, None] = None, - addChangeTime: Union[int, None] = None, - maxChange: Union[int, None] = None, - - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, - - searchForArrival: bool = False, - - numF: Union[int, None] = None, - numB: Union[int, None] = None, - - context: Union[str, None] = None, - - poly: bool = False, - polyEnc: Literal["DLT", "GPA", "N"] = "N", - - passlist: bool = False, - products: Union[int, None] = None, - operators: Union[str, list, None] = None, - - attributes: Union[str, list, None] = None, - sattributes: Union[str, list, None] = None, - fattributes: Union[str, list, None] = None, - lines: Union[str, list, None] = None, - lineids: Union[str, list, None] = None, - - avoidPaths: Union[List[Literal["SW", "EA", "ES", "RA", "CB"]], None] = None, - - originWalk: Union[str, list, None] = None, - originBike: Union[str, list, None] = None, - originCar: Union[str, list, None] = None, - originTaxi: Union[str, list, None] = None, - originPark: Union[str, list, None] = None, - originMeta: Union[str, list, None] = None, - - destWalk: Union[str, list, None] = None, - destBike: Union[str, list, None] = None, - destCar: Union[str, list, None] = None, - destTaxi: Union[str, list, None] = None, - destPark: Union[str, list, None] = None, - destMeta: Union[str, list, None] = None, - - totalWalk: Union[str, list, None] = None, - totalBike: Union[str, list, None] = None, - totalCar: Union[str, list, None] = None, - totalTaxi: Union[str, list, None] = None, - totalMeta: Union[str, list, None] = None, - - gisProducts: Union[str, None] = None, - - includeIv: bool = False, - ivOnly: bool = False, - - mobilityProfile: Union[str, None] = None, - - bikeCarriage: bool = False, - bikeCarriageType: Union[Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"], None] = None, - - sleepingCar: bool = False, - couchetteCoach: bool = False, - showPassingPoints: bool = False, - baim: bool = False, - - eco: bool = False, - ecoCmp: bool = False, - ecoParams: Union[str, None] = None, - - rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None, - - unsharp: bool = False, - trainFilter: Union[str, None] = None, - economic: bool = False, - groupFilter: Union[str, None] = None, - - blockingList: Union[str, None] = None, - blockedEdges: Union[str, None] = None, - - trainComposition: bool = False, - includeEarlier: bool = False, - withICTAlternatives: bool = False, - tariff: Union[bool, None] = None, - trafficMessages: bool = False, - travellerProfileData: Union[str, None] = None, - withFreq: bool = True - ) -> dict: +def trip_find( + accessId: str, + lang: Literal[ + "de", "da", "en", "es", "fr", "hu", "it", "nl", "no", "pl", "sv", "tr" + ] = "en", + json: bool = True, + originId: Union[str, None] = None, + originExtId: Union[str, None] = None, + originCoordLat: Union[str, float, None] = None, + originCoordLong: Union[str, float, None] = None, + originCoordName: Union[str, None] = None, + destId: Union[str, None] = None, + destExtId: Union[str, None] = None, + destCoordLat: Union[str, float, None] = None, + destCoordLong: Union[str, float, None] = None, + destCoordName: Union[str, None] = None, + via: Union[str, None] = None, + viaId: Union[str, None] = None, + viaWaitTime: int = 0, + avoid: Union[str, None] = None, + avoidId: Union[str, None] = None, + viaGis: Union[str, None] = None, + changeTimePercent: int = 100, + minChangeTime: Union[int, None] = None, + maxChangeTime: Union[int, None] = None, + addChangeTime: Union[int, None] = None, + maxChange: Union[int, None] = None, + date: Union[str, datetime, None] = None, + time: Union[str, datetime, None] = None, + searchForArrival: bool = False, + numF: Union[int, None] = None, + numB: Union[int, None] = None, + context: Union[str, None] = None, + poly: bool = False, + polyEnc: Literal["DLT", "GPA", "N"] = "N", + passlist: bool = False, + products: Union[int, None] = None, + operators: Union[str, list, None] = None, + attributes: Union[str, list, None] = None, + sattributes: Union[str, list, None] = None, + fattributes: Union[str, list, None] = None, + lines: Union[str, list, None] = None, + lineids: Union[str, list, None] = None, + avoidPaths: Union[List[Literal["SW", "EA", "ES", "RA", "CB"]], None] = None, + originWalk: Union[str, list, None] = None, + originBike: Union[str, list, None] = None, + originCar: Union[str, list, None] = None, + originTaxi: Union[str, list, None] = None, + originPark: Union[str, list, None] = None, + originMeta: Union[str, list, None] = None, + destWalk: Union[str, list, None] = None, + destBike: Union[str, list, None] = None, + destCar: Union[str, list, None] = None, + destTaxi: Union[str, list, None] = None, + destPark: Union[str, list, None] = None, + destMeta: Union[str, list, None] = None, + totalWalk: Union[str, list, None] = None, + totalBike: Union[str, list, None] = None, + totalCar: Union[str, list, None] = None, + totalTaxi: Union[str, list, None] = None, + totalMeta: Union[str, list, None] = None, + gisProducts: Union[str, None] = None, + includeIv: bool = False, + ivOnly: bool = False, + mobilityProfile: Union[str, None] = None, + bikeCarriage: bool = False, + bikeCarriageType: Union[ + Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"], None + ] = None, + sleepingCar: bool = False, + couchetteCoach: bool = False, + showPassingPoints: bool = False, + baim: bool = False, + eco: bool = False, + ecoCmp: bool = False, + ecoParams: Union[str, None] = None, + rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None, + unsharp: bool = False, + trainFilter: Union[str, None] = None, + economic: bool = False, + groupFilter: Union[str, None] = None, + blockingList: Union[str, None] = None, + blockedEdges: Union[str, None] = None, + trainComposition: bool = False, + includeEarlier: bool = False, + withICTAlternatives: bool = False, + tariff: Union[bool, None] = None, + trafficMessages: bool = False, + travellerProfileData: Union[str, None] = None, + withFreq: bool = True, +) -> dict: """The trip service calculates a trip from a specified origin to a specified destination. These might be stop/station IDs or coordinates based on addresses and points of interest validated by the location service or - coordinates freely defined by the client. + coordinates freely defined by the client. - Read more about this in section 2.12. "Trip Search (trip)" of HAFAS ReST Documentation. + Read more about this in section 2.12. "Trip Search (trip)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -217,14 +196,10 @@ def trip_find(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): if str(var) == "date": @@ -235,10 +210,9 @@ def trip_find(accessId: str, payload[str(var)] = val elif str(var) == "time": if val != None: - if isinstance(val, datetime): - payload[str(var)] = val.strftime("%H:%M") - else: - payload[str(var)] = val + payload[str(var)] = ( + val.strftime("%H:%M") if isinstance(val, datetime) else val + ) elif str(var) == "rtMode": if val != None: payload["rtMode"] = val.upper() @@ -248,7 +222,4 @@ def trip_find(accessId: str, output = get("https://www.rmv.de/hapi/trip", params=payload, headers=headers) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/raw/trip_recon.py b/src/pyrmv/raw/trip_recon.py index 9b4ac45..d0ac727 100644 --- a/src/pyrmv/raw/trip_recon.py +++ b/src/pyrmv/raw/trip_recon.py @@ -1,6 +1,7 @@ from datetime import datetime -from requests import get from typing import Union + +from requests import get from xmltodict import parse as xmlparse try: @@ -8,43 +9,44 @@ try: except ImportError: from typing_extensions import Literal -# 2.17. Reconstruction (recon) -def trip_recon(accessId: str, - ctx: str, - json: bool = True, - poly: bool = False, - polyEnc: Literal["DLT", "GPA", "N"] = "N", - date: Union[str, datetime, None] = None, - useCombinedComparison: Union[bool, None] = None, - acceptGaps: Union[bool, None] = None, - allowDummySections: Union[bool, None] = None, - flagAllNonReachable: Union[bool, None] = None, - matchCatStrict: Union[bool, None] = None, - matchIdNonBlank: Union[bool, None] = None, - matchIdStrict: Union[bool, None] = None, - matchNumStrict: Union[bool, None] = None, - matchRtType: Union[bool, None] = None, - enableRtFullSearch: Union[bool, None] = None, - enableReplacements: Union[bool, None] = None, - arrL: Union[int, None] = None, - arrU: Union[int, None] = None, - depL: Union[int, None] = None, - depU: Union[int, None] = None, - passlist: bool = False, - showPassingPoints: bool = False, - rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None, - eco: bool = False, - ecoCmp: bool = False, - ecoParams: Union[str, None] = None, - tariff: Union[bool, None] = None, - trafficMessages: Union[bool, None] = None, - travellerProfileData: Union[str, None] = None - ) -> dict: + +def trip_recon( + accessId: str, + ctx: str, + json: bool = True, + poly: bool = False, + polyEnc: Literal["DLT", "GPA", "N"] = "N", + date: Union[str, datetime, None] = None, + useCombinedComparison: Union[bool, None] = None, + acceptGaps: Union[bool, None] = None, + allowDummySections: Union[bool, None] = None, + flagAllNonReachable: Union[bool, None] = None, + matchCatStrict: Union[bool, None] = None, + matchIdNonBlank: Union[bool, None] = None, + matchIdStrict: Union[bool, None] = None, + matchNumStrict: Union[bool, None] = None, + matchRtType: Union[bool, None] = None, + enableRtFullSearch: Union[bool, None] = None, + enableReplacements: Union[bool, None] = None, + arrL: Union[int, None] = None, + arrU: Union[int, None] = None, + depL: Union[int, None] = None, + depU: Union[int, None] = None, + passlist: bool = False, + showPassingPoints: bool = False, + rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None, + eco: bool = False, + ecoCmp: bool = False, + ecoParams: Union[str, None] = None, + tariff: Union[bool, None] = None, + trafficMessages: Union[bool, None] = None, + travellerProfileData: Union[str, None] = None, +) -> dict: """Reconstructing a trip can be achieved using the reconstruction context provided by any trip result in the ctxRecon attribute of Trip element. The result will be a true copy of the original trip search result given - that the underlying data did not change. + that the underlying data did not change. - Read more about this in section 2.17. "Reconstruction (recon)" of HAFAS ReST Documentation. + Read more about this in section 2.17. "Reconstruction (recon)" of HAFAS ReST Documentation. ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). @@ -80,14 +82,10 @@ def trip_recon(accessId: str, ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. - """ - - if json: - headers = {"Accept": "application/json"} - else: - headers = {"Accept": "application/xml"} + """ payload = {} + headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} for var, val in locals().items(): if str(var) == "date": @@ -102,7 +100,4 @@ def trip_recon(accessId: str, output = get("https://www.rmv.de/hapi/recon", params=payload, headers=headers) - if json: - return output.json() - else: - return xmlparse(output.content) \ No newline at end of file + return output.json() if json else xmlparse(output.content) diff --git a/src/pyrmv/utility/__init__.py b/src/pyrmv/utility/__init__.py index e69de29..1a20d53 100644 --- a/src/pyrmv/utility/__init__.py +++ b/src/pyrmv/utility/__init__.py @@ -0,0 +1,2 @@ +from .find_exception import find_exception +from .weekdays_bitmask import weekdays_bitmask diff --git a/src/pyrmv/utility/find_exception.py b/src/pyrmv/utility/find_exception.py index 066ed8d..eb18ae9 100644 --- a/src/pyrmv/utility/find_exception.py +++ b/src/pyrmv/utility/find_exception.py @@ -1,22 +1,46 @@ -from pyrmv.errors.api_errors import ApiAuthError, ApiFormatError, ApiParamError, ApiQuotaError, ApiTooManyRequests -from pyrmv.errors.int_errors import IntError, IntGatewayError, IntTimeoutError -from pyrmv.errors.ps_errors import PsIncorrectParamError -from pyrmv.errors.sot_errors import SotAllTrainsFilteredError, SotAlreadyArrivedError, SotCancelledError, SotNotStartedError, SotStayOnTripError -from pyrmv.errors.svc_errors import SvcContextError, SvcDatetimeError, SvcDatetimePeriodError, SvcLocationArrivalError, SvcLocationDepartureError, SvcLocationEqualError, SvcLocationError, SvcLocationNearError, SvcLocationViaError, SvcNoMatchError, SvcNoResultError, SvcProductError, SvcSearchError -from pyrmv.errors.unknown_error import UnknownError +from pyrmv.errors import ( + ApiAuthError, + ApiFormatError, + ApiParamError, + ApiQuotaError, + ApiTooManyRequests, + IntError, + IntGatewayError, + IntTimeoutError, + PsIncorrectParamError, + SotAllTrainsFilteredError, + SotAlreadyArrivedError, + SotCancelledError, + SotNotStartedError, + SotStayOnTripError, + SvcContextError, + SvcDatetimeError, + SvcDatetimePeriodError, + SvcLocationArrivalError, + SvcLocationDepartureError, + SvcLocationEqualError, + SvcLocationError, + SvcLocationNearError, + SvcLocationViaError, + SvcNoMatchError, + SvcNoResultError, + SvcProductError, + SvcSearchError, + UnknownError, +) + def find_exception(data: dict): """Scan returned dict for errorCode from RMV. - Raises different exceptions if errorCode is not None. + Raises different exceptions if errorCode is not None. ### Args: * data (dict): Response from RMV as a dict. ### Raises: * Any: Formatted as "errorCode -> errorText" if ApiParamError and UnknownError or as a single massage for others. - """ + """ if "errorCode" in data: - if data["errorCode"] == "API_AUTH": raise ApiAuthError() @@ -25,7 +49,7 @@ def find_exception(data: dict): elif data["errorCode"] == "API_TOO_MANY_REQUESTS": raise ApiTooManyRequests() - + elif data["errorCode"] == "API_PARAM": raise ApiParamError(errorCode=data["errorCode"], errorText=data["errorText"]) @@ -99,4 +123,4 @@ def find_exception(data: dict): raise PsIncorrectParamError() else: - raise UnknownError(errorCode=data["errorCode"], errorText=data["errorText"]) \ No newline at end of file + raise UnknownError(errorCode=data["errorCode"], errorText=data["errorText"]) diff --git a/src/pyrmv/utility/weekdays_bitmask.py b/src/pyrmv/utility/weekdays_bitmask.py index c5456d3..d426cbe 100644 --- a/src/pyrmv/utility/weekdays_bitmask.py +++ b/src/pyrmv/utility/weekdays_bitmask.py @@ -9,13 +9,10 @@ def weekdays_bitmask(data: OrderedDict[str, bool]) -> str: ### Returns: * str: _description_ - """ - output = "" + """ if len(data) != 7: - raise ValueError("OrderedDict must be formatted as follows: OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)") - for day in data: - if data[day]: - output += "1" - else: - output += "0" - return output \ No newline at end of file + raise ValueError( + "OrderedDict must be formatted as follows: OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)" + ) + + return "".join("1" if data[day] else "0" for day in data) -- 2.39.2 From 7b9367c0a71b1ac40aff54415a53c034b8e954fb Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 24 Nov 2023 12:35:51 +0100 Subject: [PATCH 06/66] Changed imports --- src/pyrmv/__init__.py | 5 ++--- src/pyrmv/classes/Client.py | 24 ++++++++++++++++-------- src/pyrmv/classes/Ticket.py | 6 +++--- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/pyrmv/__init__.py b/src/pyrmv/__init__.py index 8ecd27d..fe1ddca 100644 --- a/src/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -25,6 +25,5 @@ __version__ = "0.3.6" __license__ = "MIT License" __author__ = "Profitroll" -from . import const, enums, errors, raw, utility -from .classes import * -from .classes.Client import Client +from . import classes, const, enums, errors, raw, utility +from .classes.client import Client diff --git a/src/pyrmv/classes/Client.py b/src/pyrmv/classes/Client.py index 8676f76..ef103b0 100644 --- a/src/pyrmv/classes/Client.py +++ b/src/pyrmv/classes/Client.py @@ -1,16 +1,24 @@ from datetime import datetime, timedelta from typing import List, OrderedDict, Union -from pyrmv.classes import * +from pyrmv.classes import ( + BoardArrival, + BoardDeparture, + Journey, + Message, + Stop, + StopTrip, + Trip, +) from pyrmv.enums import * from pyrmv.raw import board_arrival as raw_board_arrival -from pyrmv.raw.board_departure import board_departure as raw_board_departure -from pyrmv.raw.him_search import him_search as raw_him_search -from pyrmv.raw.journey_detail import journey_detail as raw_journey_detail -from pyrmv.raw.stop_by_coords import stop_by_coords as raw_stop_by_coords -from pyrmv.raw.stop_by_name import stop_by_name as raw_stop_by_name -from pyrmv.raw.trip_find import trip_find as raw_trip_find -from pyrmv.raw.trip_recon import trip_recon as raw_trip_recon +from pyrmv.raw import board_departure as raw_board_departure +from pyrmv.raw import him_search as raw_him_search +from pyrmv.raw import journey_detail as raw_journey_detail +from pyrmv.raw import stop_by_coords as raw_stop_by_coords +from pyrmv.raw import stop_by_name as raw_stop_by_name +from pyrmv.raw import trip_find as raw_trip_find +from pyrmv.raw import trip_recon as raw_trip_recon from pyrmv.utility import find_exception try: diff --git a/src/pyrmv/classes/Ticket.py b/src/pyrmv/classes/Ticket.py index 310f065..8fb79ab 100644 --- a/src/pyrmv/classes/Ticket.py +++ b/src/pyrmv/classes/Ticket.py @@ -1,4 +1,4 @@ -class Ticket(): +class Ticket: """ { "externalContent": { @@ -44,9 +44,9 @@ class Ticket(): "FreigabeId": "20730", "Freigabe":"2645, 3670, 5001, 5002, 5003, 5004, 5005, 5006, 5011, 5013, 5015, 5021, 5022, 5023, 5031, 5041, 5042, 5046, 5059, 5100, 5233, 6239, 6626, 6636, 6637, 6639, 6648, 6649, 6650, 6655, 6660, 6664, 6691", "FreigabeOverview": "Bad Homburg v.d.Höhe;Bad Soden a.Ts.;Eschborn;Friedrichsdorf;Glashütten" - } + } } """ def __init__(self) -> None: - pass \ No newline at end of file + pass -- 2.39.2 From 3a6599125750e21ca45a1accaef57fb6e3361967 Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 24 Nov 2023 12:37:24 +0100 Subject: [PATCH 07/66] This commit breaks everything --- src/pyrmv/__init__.py | 2 +- src/pyrmv/{classes => classes_new}/Board.py | 0 src/pyrmv/{classes => classes_new}/Client.py | 0 src/pyrmv/{classes => classes_new}/Gis.py | 0 src/pyrmv/{classes => classes_new}/Journey.py | 0 src/pyrmv/{classes => classes_new}/Leg.py | 0 src/pyrmv/{classes => classes_new}/Message.py | 0 src/pyrmv/{classes => classes_new}/Stop.py | 0 src/pyrmv/{classes => classes_new}/Ticket.py | 0 src/pyrmv/{classes => classes_new}/Trip.py | 0 src/pyrmv/{classes => classes_new}/__init__.py | 0 11 files changed, 1 insertion(+), 1 deletion(-) rename src/pyrmv/{classes => classes_new}/Board.py (100%) rename src/pyrmv/{classes => classes_new}/Client.py (100%) rename src/pyrmv/{classes => classes_new}/Gis.py (100%) rename src/pyrmv/{classes => classes_new}/Journey.py (100%) rename src/pyrmv/{classes => classes_new}/Leg.py (100%) rename src/pyrmv/{classes => classes_new}/Message.py (100%) rename src/pyrmv/{classes => classes_new}/Stop.py (100%) rename src/pyrmv/{classes => classes_new}/Ticket.py (100%) rename src/pyrmv/{classes => classes_new}/Trip.py (100%) rename src/pyrmv/{classes => classes_new}/__init__.py (100%) diff --git a/src/pyrmv/__init__.py b/src/pyrmv/__init__.py index fe1ddca..087d2cb 100644 --- a/src/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -26,4 +26,4 @@ __license__ = "MIT License" __author__ = "Profitroll" from . import classes, const, enums, errors, raw, utility -from .classes.client import Client +from .classes.Client import Client diff --git a/src/pyrmv/classes/Board.py b/src/pyrmv/classes_new/Board.py similarity index 100% rename from src/pyrmv/classes/Board.py rename to src/pyrmv/classes_new/Board.py diff --git a/src/pyrmv/classes/Client.py b/src/pyrmv/classes_new/Client.py similarity index 100% rename from src/pyrmv/classes/Client.py rename to src/pyrmv/classes_new/Client.py diff --git a/src/pyrmv/classes/Gis.py b/src/pyrmv/classes_new/Gis.py similarity index 100% rename from src/pyrmv/classes/Gis.py rename to src/pyrmv/classes_new/Gis.py diff --git a/src/pyrmv/classes/Journey.py b/src/pyrmv/classes_new/Journey.py similarity index 100% rename from src/pyrmv/classes/Journey.py rename to src/pyrmv/classes_new/Journey.py diff --git a/src/pyrmv/classes/Leg.py b/src/pyrmv/classes_new/Leg.py similarity index 100% rename from src/pyrmv/classes/Leg.py rename to src/pyrmv/classes_new/Leg.py diff --git a/src/pyrmv/classes/Message.py b/src/pyrmv/classes_new/Message.py similarity index 100% rename from src/pyrmv/classes/Message.py rename to src/pyrmv/classes_new/Message.py diff --git a/src/pyrmv/classes/Stop.py b/src/pyrmv/classes_new/Stop.py similarity index 100% rename from src/pyrmv/classes/Stop.py rename to src/pyrmv/classes_new/Stop.py diff --git a/src/pyrmv/classes/Ticket.py b/src/pyrmv/classes_new/Ticket.py similarity index 100% rename from src/pyrmv/classes/Ticket.py rename to src/pyrmv/classes_new/Ticket.py diff --git a/src/pyrmv/classes/Trip.py b/src/pyrmv/classes_new/Trip.py similarity index 100% rename from src/pyrmv/classes/Trip.py rename to src/pyrmv/classes_new/Trip.py diff --git a/src/pyrmv/classes/__init__.py b/src/pyrmv/classes_new/__init__.py similarity index 100% rename from src/pyrmv/classes/__init__.py rename to src/pyrmv/classes_new/__init__.py -- 2.39.2 From c4b7197267d9e75f2112f4c8a8aa082da601920f Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 24 Nov 2023 12:39:25 +0100 Subject: [PATCH 08/66] Classes restructure --- src/pyrmv/__init__.py | 4 ++-- src/pyrmv/classes/__init__.py | 9 +++++++++ src/pyrmv/{classes_new/Board.py => classes/board.py} | 2 +- src/pyrmv/{classes_new/Client.py => classes/client.py} | 0 src/pyrmv/{classes_new/Gis.py => classes/gis.py} | 0 src/pyrmv/{classes_new/Journey.py => classes/journey.py} | 4 ++-- src/pyrmv/{classes_new/Leg.py => classes/leg.py} | 6 +++--- src/pyrmv/{classes_new/Message.py => classes/message.py} | 2 +- src/pyrmv/{classes_new/Stop.py => classes/stop.py} | 0 src/pyrmv/{classes_new/Ticket.py => classes/ticket.py} | 0 src/pyrmv/{classes_new/Trip.py => classes/trip.py} | 4 ++-- src/pyrmv/classes_new/__init__.py | 9 --------- 12 files changed, 20 insertions(+), 20 deletions(-) create mode 100644 src/pyrmv/classes/__init__.py rename src/pyrmv/{classes_new/Board.py => classes/board.py} (98%) rename src/pyrmv/{classes_new/Client.py => classes/client.py} (100%) rename src/pyrmv/{classes_new/Gis.py => classes/gis.py} (100%) rename src/pyrmv/{classes_new/Journey.py => classes/journey.py} (90%) rename src/pyrmv/{classes_new/Leg.py => classes/leg.py} (87%) rename src/pyrmv/{classes_new/Message.py => classes/message.py} (98%) rename src/pyrmv/{classes_new/Stop.py => classes/stop.py} (100%) rename src/pyrmv/{classes_new/Ticket.py => classes/ticket.py} (100%) rename src/pyrmv/{classes_new/Trip.py => classes/trip.py} (93%) delete mode 100644 src/pyrmv/classes_new/__init__.py diff --git a/src/pyrmv/__init__.py b/src/pyrmv/__init__.py index 087d2cb..58ad764 100644 --- a/src/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -21,9 +21,9 @@ trip = client.trip_find(origin_id=origin.id, dest_id=destination.id) """ __name__ = "pyrmv" -__version__ = "0.3.6" +__version__ = "1.0.0" __license__ = "MIT License" __author__ = "Profitroll" from . import classes, const, enums, errors, raw, utility -from .classes.Client import Client +from .classes.client import Client diff --git a/src/pyrmv/classes/__init__.py b/src/pyrmv/classes/__init__.py new file mode 100644 index 0000000..c3babc0 --- /dev/null +++ b/src/pyrmv/classes/__init__.py @@ -0,0 +1,9 @@ +from .board import BoardArrival, BoardDeparture, LineArrival, LineDeparture +from .client import Client +from .gis import Gis +from .journey import Journey +from .leg import Leg +from .message import Channel, Message, Url +from .stop import Stop, StopTrip +from .ticket import Ticket +from .trip import Trip diff --git a/src/pyrmv/classes_new/Board.py b/src/pyrmv/classes/board.py similarity index 98% rename from src/pyrmv/classes_new/Board.py rename to src/pyrmv/classes/board.py index a52a1d5..b5362f0 100644 --- a/src/pyrmv/classes_new/Board.py +++ b/src/pyrmv/classes/board.py @@ -1,7 +1,7 @@ from datetime import datetime from typing import Any, Mapping -from pyrmv.classes.Message import Message +from pyrmv.classes.message import Message class LineArrival: diff --git a/src/pyrmv/classes_new/Client.py b/src/pyrmv/classes/client.py similarity index 100% rename from src/pyrmv/classes_new/Client.py rename to src/pyrmv/classes/client.py diff --git a/src/pyrmv/classes_new/Gis.py b/src/pyrmv/classes/gis.py similarity index 100% rename from src/pyrmv/classes_new/Gis.py rename to src/pyrmv/classes/gis.py diff --git a/src/pyrmv/classes_new/Journey.py b/src/pyrmv/classes/journey.py similarity index 90% rename from src/pyrmv/classes_new/Journey.py rename to src/pyrmv/classes/journey.py index a2deca4..1cd2f37 100644 --- a/src/pyrmv/classes_new/Journey.py +++ b/src/pyrmv/classes/journey.py @@ -1,7 +1,7 @@ from typing import Any, Mapping -from pyrmv.classes.Message import Message -from pyrmv.classes.Stop import Stop +from pyrmv.classes.message import Message +from pyrmv.classes.stop import Stop class Journey: diff --git a/src/pyrmv/classes_new/Leg.py b/src/pyrmv/classes/leg.py similarity index 87% rename from src/pyrmv/classes_new/Leg.py rename to src/pyrmv/classes/leg.py index be3594d..eb27d5f 100644 --- a/src/pyrmv/classes_new/Leg.py +++ b/src/pyrmv/classes/leg.py @@ -2,9 +2,9 @@ from typing import Any, Mapping from isodate import parse_duration -from pyrmv.classes.Gis import Gis -from pyrmv.classes.Message import Message -from pyrmv.classes.Stop import StopTrip +from pyrmv.classes.gis import Gis +from pyrmv.classes.message import Message +from pyrmv.classes.stop import StopTrip class Leg: diff --git a/src/pyrmv/classes_new/Message.py b/src/pyrmv/classes/message.py similarity index 98% rename from src/pyrmv/classes_new/Message.py rename to src/pyrmv/classes/message.py index 4b151bc..f5ae8e2 100644 --- a/src/pyrmv/classes_new/Message.py +++ b/src/pyrmv/classes/message.py @@ -3,7 +3,7 @@ from typing import Any, Mapping from isodate import parse_duration -from pyrmv.classes.Stop import Stop +from pyrmv.classes.stop import Stop class Url: diff --git a/src/pyrmv/classes_new/Stop.py b/src/pyrmv/classes/stop.py similarity index 100% rename from src/pyrmv/classes_new/Stop.py rename to src/pyrmv/classes/stop.py diff --git a/src/pyrmv/classes_new/Ticket.py b/src/pyrmv/classes/ticket.py similarity index 100% rename from src/pyrmv/classes_new/Ticket.py rename to src/pyrmv/classes/ticket.py diff --git a/src/pyrmv/classes_new/Trip.py b/src/pyrmv/classes/trip.py similarity index 93% rename from src/pyrmv/classes_new/Trip.py rename to src/pyrmv/classes/trip.py index 809d85e..3693f16 100644 --- a/src/pyrmv/classes_new/Trip.py +++ b/src/pyrmv/classes/trip.py @@ -1,7 +1,7 @@ from isodate import parse_duration -from pyrmv.classes.Leg import Leg -from pyrmv.classes.Stop import StopTrip +from pyrmv.classes.leg import Leg +from pyrmv.classes.stop import StopTrip class Trip: diff --git a/src/pyrmv/classes_new/__init__.py b/src/pyrmv/classes_new/__init__.py deleted file mode 100644 index ab6bb04..0000000 --- a/src/pyrmv/classes_new/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from .Board import BoardArrival, BoardDeparture, LineArrival, LineDeparture -from .Client import Client -from .Gis import Gis -from .Journey import Journey -from .Leg import Leg -from .Message import Channel, Message, Url -from .Stop import Stop, StopTrip -from .Ticket import Ticket -from .Trip import Trip -- 2.39.2 From 059c511e05cfa6605083b2ee382cfa86eebbd9de Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 24 Nov 2023 12:44:57 +0100 Subject: [PATCH 09/66] Removed Client from classes --- src/pyrmv/classes/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pyrmv/classes/__init__.py b/src/pyrmv/classes/__init__.py index c3babc0..c87171b 100644 --- a/src/pyrmv/classes/__init__.py +++ b/src/pyrmv/classes/__init__.py @@ -1,5 +1,4 @@ from .board import BoardArrival, BoardDeparture, LineArrival, LineDeparture -from .client import Client from .gis import Gis from .journey import Journey from .leg import Leg -- 2.39.2 From efedb2533bdc5b0a5883c9616a47f0276806d56f Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 24 Nov 2023 13:35:47 +0100 Subject: [PATCH 10/66] WIP: Automatic tests --- tests/conftest.py | 21 ++++++++++++++ tests/test_client.py | 67 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 8fff836..53a6c4c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,4 +1,5 @@ from os import environ +from typing import List import pytest @@ -13,3 +14,23 @@ def api_token() -> str: @pytest.fixture() def api_client(api_token: str) -> Client: return Client(api_token) + + +@pytest.fixture() +def sample_stop_id() -> str: + return "A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@" + + +@pytest.fixture() +def sample_journey_id() -> str: + return "2|#VN#1#ST#1664906549#PI#0#ZI#12709#TA#0#DA#61022#1S#3008007#1T#1248#LS#3008043#LT#1323#PU#80#RT#1#CA#1aE#ZE#101#ZB#Bus 101 #PC#6#FR#3008007#FT#1248#TO#3008043#TT#1323#" + + +@pytest.fixture() +def sample_origin() -> List[str]: + return ["50.084659", "8.785948"] + + +@pytest.fixture() +def sample_destination() -> List[float]: + return [50.1233048, 8.6129742] diff --git a/tests/test_client.py b/tests/test_client.py index 071a465..4f5a7b1 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,7 +1,70 @@ +from datetime import datetime, timedelta +from typing import List + import pytest -from pyrmv import Client -from pyrmv.classes import Stop +from pyrmv import Client, enums +from pyrmv.classes import Journey, Message, Stop, Trip +from pyrmv.classes.board import BoardArrival, BoardDeparture + + +def test_board_arrival(api_client: Client, sample_stop_id: str): + assert isinstance( + api_client.board_arrival(id=sample_stop_id, journeys_max=3), BoardArrival + ) + + +def test_board_departure(api_client: Client, sample_stop_id: str): + assert isinstance( + api_client.board_departure(id=sample_stop_id, journeys_max=3), BoardDeparture + ) + + +def test_him_search(api_client: Client): + assert isinstance( + api_client.him_search(date_end=datetime.now() + timedelta(days=10))[0], Message + ) + + +# Does not work as it should yet +# def test_journey_detail(api_client: Client, sample_journey_id: str): +# assert ( +# api_client.journey_detail( +# sample_journey_id, +# real_time_mode=enums.RealTimeMode.FULL, +# ), +# Journey, +# ) + + +def test_stop_by_coords(api_client: Client, sample_origin: List[str]): + assert isinstance( + api_client.stop_by_coords(sample_origin[0], sample_origin[1], max_number=3)[0], Stop + ) + + +def test_stop_by_id(api_client: Client, sample_stop_id: str): + assert isinstance(api_client.stop_by_id(sample_stop_id), Stop) + + +def test_trip_find( + api_client: Client, sample_origin: List[str], sample_destination: List[float] +): + assert isinstance( + api_client.trip_find( + origin_coord_lat=sample_origin[0], + origin_coord_lon=sample_origin[1], + destination_coord_lat=sample_destination[0], + destination_coord_lon=sample_destination[1], + messages=True, + )[0], + Trip, + ) + + +# Does not work as it should yet +# def test_trip_recon(api_client: Client): +# assert api_client.trip_recon() def test_stop_by_name(api_client: Client): -- 2.39.2 From 414f3966da75c17e655b88e591b31be386eaae7e Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 24 Nov 2023 23:52:50 +0100 Subject: [PATCH 11/66] Attempt to temporarily fix #2 --- src/pyrmv/classes/board.py | 11 +++++-- src/pyrmv/classes/client.py | 7 ++--- src/pyrmv/classes/journey.py | 7 ++++- src/pyrmv/utility/__init__.py | 1 + src/pyrmv/utility/journey_ref_converter.py | 26 ++++++++++++++++ tests/conftest.py | 2 +- tests/test_client.py | 35 ++++++++++++++-------- 7 files changed, 68 insertions(+), 21 deletions(-) create mode 100644 src/pyrmv/utility/journey_ref_converter.py diff --git a/src/pyrmv/classes/board.py b/src/pyrmv/classes/board.py index b5362f0..a69c9ac 100644 --- a/src/pyrmv/classes/board.py +++ b/src/pyrmv/classes/board.py @@ -2,11 +2,15 @@ from datetime import datetime from typing import Any, Mapping from pyrmv.classes.message import Message +from pyrmv.utility import ref_upgrade class LineArrival: def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): - self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) + # Upgrade is temporarily used due to RMV API mismatch + # self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) + self.journey = client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"])) + self.status = data["JourneyStatus"] self.messages = [] self.name = data["name"] @@ -40,7 +44,10 @@ class LineArrival: class LineDeparture: def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): - self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) + # Upgrade is temporarily used due to RMV API mismatch + # self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) + self.journey = client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"])) + self.status = data["JourneyStatus"] self.messages = [] self.name = data["name"] diff --git a/src/pyrmv/classes/client.py b/src/pyrmv/classes/client.py index ef103b0..1c04c1f 100644 --- a/src/pyrmv/classes/client.py +++ b/src/pyrmv/classes/client.py @@ -121,7 +121,7 @@ class Client: * BoardArrival: Instance of `BoardArrival` object. """ - if isinstance(direction, Stop) or isinstance(direction, StopTrip): + if isinstance(direction, (Stop, StopTrip)): direction = direction.id board_raw = raw_board_arrival( @@ -827,10 +827,7 @@ class Client: * List[Trip]: List of `Trip` objects. Empty list if none found. """ - if real_time_mode == None: - real_time_mode = None - else: - real_time_mode = real_time_mode.code + real_time_mode = None if real_time_mode is None else real_time_mode.code if isinstance(context, Trip): context = context.ctx_recon diff --git a/src/pyrmv/classes/journey.py b/src/pyrmv/classes/journey.py index 1cd2f37..32aa574 100644 --- a/src/pyrmv/classes/journey.py +++ b/src/pyrmv/classes/journey.py @@ -2,6 +2,7 @@ from typing import Any, Mapping from pyrmv.classes.message import Message from pyrmv.classes.stop import Stop +from pyrmv.utility import ref_upgrade class Journey: @@ -9,7 +10,11 @@ class Journey: def __init__(self, data: Mapping[str, Any]): self.stops = [] - self.ref = data["ref"] + + # Upgrade is temporarily used due to RMV API mismatch + # self.ref = data["ref"] + self.ref = ref_upgrade(data["ref"]) + self.direction = data["Directions"]["Direction"][0]["value"] self.direction_flag = data["Directions"]["Direction"][0]["flag"] self.stops.extend(Stop(stop) for stop in data["Stops"]["Stop"]) diff --git a/src/pyrmv/utility/__init__.py b/src/pyrmv/utility/__init__.py index 1a20d53..c88aa0e 100644 --- a/src/pyrmv/utility/__init__.py +++ b/src/pyrmv/utility/__init__.py @@ -1,2 +1,3 @@ from .find_exception import find_exception +from .journey_ref_converter import ref_upgrade from .weekdays_bitmask import weekdays_bitmask diff --git a/src/pyrmv/utility/journey_ref_converter.py b/src/pyrmv/utility/journey_ref_converter.py new file mode 100644 index 0000000..2449a2a --- /dev/null +++ b/src/pyrmv/utility/journey_ref_converter.py @@ -0,0 +1,26 @@ +def ref_upgrade(ref: str) -> str: + """This function converts older journey refs to the newer ones. + + ### WARNING + This function will be deprecated as soon as RMV updates their API + + ### Args: + * ref (`str`): Old ref like this one: `2|#VN#1#ST#1700765441#PI#0#ZI#160749#TA#0#DA#241123#1S#3004646#1T#2228#LS#3006907#LT#2354#PU#80#RT#1#CA#S30#ZE#S1#ZB# S1#PC#3#FR#3004646#FT#2228#TO#3006907#TT#2354#` + + ### Raises: + * `KeyError`: Some required keys are not found in the ref provided + + ### Returns: + * `str`: Ref of the new type + """ + + items = "|".join(ref.split("|")[1:]).strip("#").split("#") + result = {items[i]: items[i + 1] for i in range(0, len(items), 2)} + + for required in ["VN", "ZI", "TA", "PU"]: + if required not in result: + raise KeyError( + f"Required key {required} in the old journey ref is not found during conversion to the newer journey ref" + ) + + return "|".join([result["VN"], result["ZI"], result["TA"], result["PU"]]) diff --git a/tests/conftest.py b/tests/conftest.py index 53a6c4c..fbe4293 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,7 +23,7 @@ def sample_stop_id() -> str: @pytest.fixture() def sample_journey_id() -> str: - return "2|#VN#1#ST#1664906549#PI#0#ZI#12709#TA#0#DA#61022#1S#3008007#1T#1248#LS#3008043#LT#1323#PU#80#RT#1#CA#1aE#ZE#101#ZB#Bus 101 #PC#6#FR#3008007#FT#1248#TO#3008043#TT#1323#" + return "1|12709|0|80" @pytest.fixture() diff --git a/tests/test_client.py b/tests/test_client.py index 4f5a7b1..8577e4e 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -26,15 +26,14 @@ def test_him_search(api_client: Client): ) -# Does not work as it should yet -# def test_journey_detail(api_client: Client, sample_journey_id: str): -# assert ( -# api_client.journey_detail( -# sample_journey_id, -# real_time_mode=enums.RealTimeMode.FULL, -# ), -# Journey, -# ) +def test_journey_detail(api_client: Client, sample_journey_id: str): + assert ( + api_client.journey_detail( + sample_journey_id, + real_time_mode=enums.RealTimeMode.FULL, + ), + Journey, + ) def test_stop_by_coords(api_client: Client, sample_origin: List[str]): @@ -62,9 +61,21 @@ def test_trip_find( ) -# Does not work as it should yet -# def test_trip_recon(api_client: Client): -# assert api_client.trip_recon() +def test_trip_recon( + api_client: Client, sample_origin: List[str], sample_destination: List[float] +): + assert isinstance( + api_client.trip_recon( + api_client.trip_find( + origin_coord_lat=sample_origin[0], + origin_coord_lon=sample_origin[1], + destination_coord_lat=sample_destination[0], + destination_coord_lon=sample_destination[1], + messages=True, + )[0], + )[0], + Trip, + ) def test_stop_by_name(api_client: Client): -- 2.39.2 From 3656a040f415f5d96a2baaa56b1b2a6cd4e1b0b5 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sat, 25 Nov 2023 12:23:33 +0100 Subject: [PATCH 12/66] Okay, 1.0.0 was an overkill, module is in alpha --- src/pyrmv/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pyrmv/__init__.py b/src/pyrmv/__init__.py index 58ad764..e331cda 100644 --- a/src/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -21,7 +21,7 @@ trip = client.trip_find(origin_id=origin.id, dest_id=destination.id) """ __name__ = "pyrmv" -__version__ = "1.0.0" +__version__ = "0.4.0" __license__ = "MIT License" __author__ = "Profitroll" -- 2.39.2 From 83ae0999ea4727dbe4ce40be5a7d3b5a955c97a8 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sat, 25 Nov 2023 13:16:48 +0100 Subject: [PATCH 13/66] Documentation prepared and improved --- wiki/Home.md | 36 ++++++++++++++++++- wiki/Raw-Functions.md | 1 + wiki/_Sidebar.md | 32 ++++++++++------- wiki/classes/BoardArrival.md | 1 + wiki/classes/BoardDeparture.md | 1 + wiki/classes/Channel.md | 1 + wiki/{ => classes/Client}/Client.md | 15 ++++---- .../Client/methods/Client.board_arrival.md | 1 + .../Client/methods/Client.board_departure.md | 1 + .../Client/methods/Client.him_search.md | 1 + .../Client/methods/Client.journey_detail.md | 1 + .../Client/methods/Client.stop_by_coords.md | 1 + .../Client/methods/Client.stop_by_id.md | 1 + .../Client/methods/Client.stop_by_name.md | 1 + .../Client/methods/Client.trip_find.md | 1 + .../Client/methods/Client.trip_recon.md | 1 + wiki/classes/Gis.md | 1 + wiki/classes/Journey.md | 1 + wiki/classes/Leg.md | 1 + wiki/classes/LineArrival.md | 1 + wiki/classes/LineDeparture.md | 1 + wiki/classes/Message.md | 1 + wiki/classes/Stop.md | 1 + wiki/classes/StopTrip.md | 1 + wiki/classes/Ticket.md | 1 + wiki/classes/Trip.md | 1 + wiki/classes/Url.md | 1 + 27 files changed, 86 insertions(+), 21 deletions(-) create mode 100644 wiki/Raw-Functions.md create mode 100644 wiki/classes/BoardArrival.md create mode 100644 wiki/classes/BoardDeparture.md create mode 100644 wiki/classes/Channel.md rename wiki/{ => classes/Client}/Client.md (85%) create mode 100644 wiki/classes/Client/methods/Client.board_arrival.md create mode 100644 wiki/classes/Client/methods/Client.board_departure.md create mode 100644 wiki/classes/Client/methods/Client.him_search.md create mode 100644 wiki/classes/Client/methods/Client.journey_detail.md create mode 100644 wiki/classes/Client/methods/Client.stop_by_coords.md create mode 100644 wiki/classes/Client/methods/Client.stop_by_id.md create mode 100644 wiki/classes/Client/methods/Client.stop_by_name.md create mode 100644 wiki/classes/Client/methods/Client.trip_find.md create mode 100644 wiki/classes/Client/methods/Client.trip_recon.md create mode 100644 wiki/classes/Gis.md create mode 100644 wiki/classes/Journey.md create mode 100644 wiki/classes/Leg.md create mode 100644 wiki/classes/LineArrival.md create mode 100644 wiki/classes/LineDeparture.md create mode 100644 wiki/classes/Message.md create mode 100644 wiki/classes/Stop.md create mode 100644 wiki/classes/StopTrip.md create mode 100644 wiki/classes/Ticket.md create mode 100644 wiki/classes/Trip.md create mode 100644 wiki/classes/Url.md diff --git a/wiki/Home.md b/wiki/Home.md index 498c410..ac9b491 100644 --- a/wiki/Home.md +++ b/wiki/Home.md @@ -2,4 +2,38 @@ Welcome to the project's Wiki. -Conceptional there are two different types of methods. Normal and raw ones. Raw methods are only beautiful variant of HTTP requests, nothing except for that actually. Normal ones are meant to be used as objects. You can still provide strings here and there, but basic concept is focused on objects usage. \ No newline at end of file +This module aims to provide eased access to RMV's OpenData API endpoints and enable some home-projects to show the data about public transit state at the moment. As for now, async is not supported and is not necessarily planned in the future, so bigger projects should consider this before using this module in the first place. + +## Basic concepts behind + +So the module `pyrmv` has two options to choose from when it comes to the usage: + +1. Using higher-level methods of the class [pyrmv.Client](https://git.end-play.xyz/profitroll/PythonRMV/wiki/Client). These methods provide pythonic objects, can throw exceptions and are overall pretty neat. +2. Using raw functions from [pyrmv.raw](https://git.end-play.xyz/profitroll/PythonRMV/wiki/Raw-Functions). These functions are basically a small interface for HTTP requests that happen in the background and have little to no processing behind the scenes. + +Your preferred variant depends on the use case, but usually higher-level methods of the Client should be the match. + +## Objects + +This module does **not** use the [FPTF](https://github.com/public-transport/friendly-public-transport-format) because it aims to give full access to the API RMV provides, thus objects Client gives you will contain a bit more information. + +These objects are implemented in pyrmv: + +* [BoardArrival](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.BoardArrival) +* [BoardDeparture](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.BoardDeparture) +* [LineArrival](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.LineArrival) +* [LineDeparture](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.LineDeparture) +* [Gis](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Gis) +* [Journey](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Journey) +* [Leg](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Leg) +* [Channel](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Channel) +* [Message](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Message) +* [Url](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Url) +* [Stop](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Stop) +* [StopTrip](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.StopTrip) +* [Trip](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Trip) +* ~~[Ticket](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Ticket)~~ (WIP) + +## Note for bigger projects + +As you may already know, bigger projects like [Öffi](https://gitlab.com/oeffi/oeffi) and [DB Navigator](https://play.google.com/store/apps/details?id=de.hafas.android.db) use NVV's API instead of RMV's for navigation and public transit querying. Reasons behind this are clear as day and from perspective of pyrmv it's highly recommended you also choose that way, because RMV loves to change or break their API in unexpected places and does not cooperate with developers well enough when they do so. diff --git a/wiki/Raw-Functions.md b/wiki/Raw-Functions.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/Raw-Functions.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/_Sidebar.md b/wiki/_Sidebar.md index a7b5992..7fd228d 100644 --- a/wiki/_Sidebar.md +++ b/wiki/_Sidebar.md @@ -1,15 +1,21 @@ -## [Home](https://git.end-play.xyz/profitroll/PythonRMV/wiki) +# [Home](https://git.end-play.xyz/profitroll/PythonRMV/wiki) -### Classes -* [Client](https://git.end-play.xyz/profitroll/PythonRMV/wiki/Client) +## Classes -### Methods -* [board_arrival](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_arrival) -* [board_departure](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_departure) -* [him_search](https://git.end-play.xyz/profitroll/PythonRMV/wiki/him_search) -* [journey_detail](https://git.end-play.xyz/profitroll/PythonRMV/wiki/journey_detail) -* [stop_by_coords](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_coords) -* [stop_by_id](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_id) -* [stop_by_name](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_name) -* [trip_find](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_find) -* [trip_recon](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_recon) \ No newline at end of file +* [Client](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client) + +## Methods + +* [board_arrival](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.board_arrival) +* [board_departure](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.board_departure) +* [him_search](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.him_search) +* [journey_detail](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.journey_detail) +* [stop_by_coords](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.stop_by_coords) +* [stop_by_id](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.stop_by_id) +* [stop_by_name](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.stop_by_name) +* [trip_find](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.trip_find) +* [trip_recon](https://git.end-play.xyz/profitroll/PythonRMV/wiki/classes.Client.trip_recon) + +## Raw functions + +* [List of raw functions](https://git.end-play.xyz/profitroll/PythonRMV/wiki/Raw-Functions) diff --git a/wiki/classes/BoardArrival.md b/wiki/classes/BoardArrival.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/BoardArrival.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/BoardDeparture.md b/wiki/classes/BoardDeparture.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/BoardDeparture.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Channel.md b/wiki/classes/Channel.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Channel.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/Client.md b/wiki/classes/Client/Client.md similarity index 85% rename from wiki/Client.md rename to wiki/classes/Client/Client.md index 5f875c0..8549979 100644 --- a/wiki/Client.md +++ b/wiki/classes/Client/Client.md @@ -1,5 +1,6 @@ -# PythonRMV Client -You are now viewing the main class of the module, its heart. The main Client class, all available normal methods can be found here. +# Client + +You are now viewing the main class of the module, all available higher-level methods can be found here. This page is about the Client class, which exposes high-level methods for an easy access to the API. @@ -11,14 +12,14 @@ client = Client("SampleAPIKey") print(client.stop_by_id("A=1@O=Offenbach (Main)-Zentrum Marktplatz\/Frankf. Straße@X=8764456@Y=50105181@U=80@L=3002510@")) ``` -# Details - -## `class pyrmv.Client` +## Details ### Parameters + * access_key (`str`) – Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). -### Methods: +### Methods + * [board_arrival](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_arrival) -> `BoardArrival` * [board_departure](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_departure) -> `BoardDeparture` * [him_search](https://git.end-play.xyz/profitroll/PythonRMV/wiki/him_search) -> `List[Message]` @@ -27,4 +28,4 @@ print(client.stop_by_id("A=1@O=Offenbach (Main)-Zentrum Marktplatz\/Frankf. Stra * [stop_by_id](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_id) -> `Union[Stop, None]` * [stop_by_name](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_name) -> `List[Stop]` * [trip_find](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_find) -> `List[Trip]` -* [trip_recon](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_recon) -> `List[Trip]` \ No newline at end of file +* [trip_recon](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_recon) -> `List[Trip]` diff --git a/wiki/classes/Client/methods/Client.board_arrival.md b/wiki/classes/Client/methods/Client.board_arrival.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.board_arrival.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.board_departure.md b/wiki/classes/Client/methods/Client.board_departure.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.board_departure.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.him_search.md b/wiki/classes/Client/methods/Client.him_search.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.him_search.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.journey_detail.md b/wiki/classes/Client/methods/Client.journey_detail.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.journey_detail.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.stop_by_coords.md b/wiki/classes/Client/methods/Client.stop_by_coords.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.stop_by_coords.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.stop_by_id.md b/wiki/classes/Client/methods/Client.stop_by_id.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.stop_by_id.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.stop_by_name.md b/wiki/classes/Client/methods/Client.stop_by_name.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.stop_by_name.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.trip_find.md b/wiki/classes/Client/methods/Client.trip_find.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.trip_find.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Client/methods/Client.trip_recon.md b/wiki/classes/Client/methods/Client.trip_recon.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Client/methods/Client.trip_recon.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Gis.md b/wiki/classes/Gis.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Gis.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Journey.md b/wiki/classes/Journey.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Journey.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Leg.md b/wiki/classes/Leg.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Leg.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/LineArrival.md b/wiki/classes/LineArrival.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/LineArrival.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/LineDeparture.md b/wiki/classes/LineDeparture.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/LineDeparture.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Message.md b/wiki/classes/Message.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Message.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Stop.md b/wiki/classes/Stop.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Stop.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/StopTrip.md b/wiki/classes/StopTrip.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/StopTrip.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Ticket.md b/wiki/classes/Ticket.md new file mode 100644 index 0000000..ff713c3 --- /dev/null +++ b/wiki/classes/Ticket.md @@ -0,0 +1 @@ +Class is not available yet. Documentation will appear here after the class is finished. diff --git a/wiki/classes/Trip.md b/wiki/classes/Trip.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Trip.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. diff --git a/wiki/classes/Url.md b/wiki/classes/Url.md new file mode 100644 index 0000000..7d18af3 --- /dev/null +++ b/wiki/classes/Url.md @@ -0,0 +1 @@ +Docs are not available yet. Please, use the linting in your IDE until the documentation is there. -- 2.39.2 From f7873ac66b534d0b8ef23e24e5d4a8ae253f8256 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sat, 25 Nov 2023 13:20:00 +0100 Subject: [PATCH 14/66] Fixed installation methods --- README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 6345086..a8910dd 100644 --- a/README.md +++ b/README.md @@ -19,13 +19,11 @@ If you have everything listed in [requirements](#requirements), then let's begin ### Variant 1 -1. `python -m pip install pyrmv` +`python -m pip install pyrmv` ### Variant 2 -1. `git clone https://git.end-play.xyz/profitroll/PythonRMV.git` -2. `cd PythonRMV` -3. `python setup.py install` +`python -m pip install git+https://git.end-play.xyz/profitroll/PythonRMV.git` ## Usage @@ -39,7 +37,7 @@ client = pyrmv.Client("AcessId") origin = client.stop_by_name("Frankfurt Hauptbahnhof", max_number=3)[0] destination = client.stop_by_coords(50.099613, 8.685449, max_number=3)[0] -# Find a trip by locations got +# Find a trip by locations you got above trip = client.trip_find(origin_id=origin.id, dest_id=destination.id) ``` -- 2.39.2 From 5690080a6a7b9fce2821df0a5ff39d6f579a0672 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sat, 25 Nov 2023 14:21:48 +0100 Subject: [PATCH 15/66] Version is set to 0.4.0-rc.1 --- src/pyrmv/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pyrmv/__init__.py b/src/pyrmv/__init__.py index e331cda..87e7955 100644 --- a/src/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -21,7 +21,7 @@ trip = client.trip_find(origin_id=origin.id, dest_id=destination.id) """ __name__ = "pyrmv" -__version__ = "0.4.0" +__version__ = "0.4.0-rc.1" __license__ = "MIT License" __author__ = "Profitroll" -- 2.39.2 From 3ee90c7a41ab06b241c56d76a06ab6dcd4dd3d7d Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 27 Nov 2023 21:44:17 +0100 Subject: [PATCH 16/66] New date and time behavior, improved typing --- src/pyrmv/classes/board.py | 174 ++++++++++++++++++++--------- src/pyrmv/classes/client.py | 185 +++++++++++++++++++++---------- src/pyrmv/classes/gis.py | 13 ++- src/pyrmv/classes/journey.py | 20 +++- src/pyrmv/classes/leg.py | 25 +++-- src/pyrmv/classes/message.py | 109 +++++++++++------- src/pyrmv/classes/stop.py | 28 ++--- src/pyrmv/classes/trip.py | 28 ++--- src/pyrmv/raw/board_arrival.py | 32 +++--- src/pyrmv/raw/board_departure.py | 32 +++--- src/pyrmv/raw/him_search.py | 66 +++++------ src/pyrmv/raw/journey_detail.py | 22 ++-- src/pyrmv/raw/stop_by_coords.py | 20 ++-- src/pyrmv/raw/stop_by_name.py | 28 ++--- src/pyrmv/raw/trip_find.py | 168 ++++++++++++++-------------- src/pyrmv/raw/trip_recon.py | 56 +++++----- tests/test_client.py | 7 +- 17 files changed, 598 insertions(+), 415 deletions(-) diff --git a/src/pyrmv/classes/board.py b/src/pyrmv/classes/board.py index a69c9ac..c3b69cc 100644 --- a/src/pyrmv/classes/board.py +++ b/src/pyrmv/classes/board.py @@ -1,41 +1,57 @@ from datetime import datetime -from typing import Any, Mapping +from typing import Any, List, Mapping, Union +from pyrmv.classes.journey import Journey from pyrmv.classes.message import Message +from pyrmv.classes.stop import Stop from pyrmv.utility import ref_upgrade class LineArrival: - def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): + def __init__( + self, + data: Mapping[str, Any], + retrieve_stops: bool = False, + retrieve_journey: bool = False, + client: Union["pyrmv.Client", None] = None, + ): + if (retrieve_stops or retrieve_journey) and client is None: + raise KeyError( + "Stops/journey retrieval requested but client argument was not provided." + ) + # Upgrade is temporarily used due to RMV API mismatch # self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) - self.journey = client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"])) + self.journey: Union[Journey, None] = ( + client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"])) + if retrieve_journey + else None + ) - self.status = data["JourneyStatus"] - self.messages = [] - self.name = data["name"] - self.type = data["type"] - self.stop_name = data["stop"] - self.stop_id = data["stopid"] - self.stop_id_ext = data["stopExtId"] - self.stop = client.stop_by_id(self.stop_id) if retrieve_stops else None - self.stop = client.stop_by_id(self.stop_id) - self.time = datetime.strptime(data["time"], "%H:%M:%S") - self.date = datetime.strptime(data["date"], "%Y-%m-%d") - self.reachable = data["reachable"] - self.origin = data["origin"] - self.origin = data["origin"] + self.status: str = data["JourneyStatus"] + self.messages: List[Message] = [] + self.name: str = data["name"] + self.type: str = data["type"] + self.stop_name: str = data["stop"] + self.stop_id: str = data["stopid"] + self.stop_id_ext: Union[str, None] = data.get("stopExtId") + self.stop: Union[Stop, None] = ( + client.stop_by_id(self.stop_id) if retrieve_stops else None + ) + self.time: datetime = datetime.strptime( + f"{data['date']} {data['time']}", "%Y-%m-%d %H:%M:%S" + ) + self.time_real: datetime = ( + datetime.strptime(f"{data['rtDate']} {data['rtTime']}", "%Y-%m-%d %H:%M:%S") + if data.get("rtTime") and data.get("rtDate") + else None + ) + self.reachable: bool = data["reachable"] + self.origin: Union[str, None] = data.get("origin") if "Messages" in data: self.messages.extend(Message(message) for message in data["Messages"]["Message"]) - if ("rtTime" in data) and ("rtDate" in data): - self.time_real_time = datetime.strptime(data["rtTime"], "%H:%M:%S") - self.date_real_time = datetime.strptime(data["rtDate"], "%Y-%m-%d") - else: - self.time_real_time = None - self.date_real_time = None - def __str__(self) -> str: return ( f"{self.name} coming from {self.origin} at {self.time.time()} {self.date.date()}" @@ -43,35 +59,51 @@ class LineArrival: class LineDeparture: - def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): + def __init__( + self, + data: Mapping[str, Any], + retrieve_stops: bool = False, + retrieve_journey: bool = False, + client: Union["pyrmv.Client", None] = None, + ): + if (retrieve_stops or retrieve_journey) and client is None: + raise KeyError( + "Stops/journey retrieval requested but client argument was not provided." + ) + # Upgrade is temporarily used due to RMV API mismatch # self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) - self.journey = client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"])) + self.journey: Union[Journey, None] = ( + client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"])) + if retrieve_journey + else None + ) - self.status = data["JourneyStatus"] - self.messages = [] - self.name = data["name"] - self.type = data["type"] - self.stop_name = data["stop"] - self.stop_id = data["stopid"] - self.stop_id_ext = data["stopExtId"] - self.stop = client.stop_by_id(self.stop_id) if retrieve_stops else None - self.time = datetime.strptime(data["time"], "%H:%M:%S") - self.date = datetime.strptime(data["date"], "%Y-%m-%d") - self.reachable = data["reachable"] - self.direction = data["direction"] - self.direction_flag = data["directionFlag"] + self.status: str = data["JourneyStatus"] + self.messages: List[Message] = [] + self.name: str = data["name"] + self.type: str = data["type"] + self.stop_name: str = data["stop"] + self.stop_id: str = data["stopid"] + self.stop_id_ext: Union[str, None] = data.get("stopExtId") + self.stop: Union[Stop, None] = ( + client.stop_by_id(self.stop_id) if retrieve_stops else None + ) + self.time: datetime = datetime.strptime( + f"{data['date']} {data['time']}", "%Y-%m-%d %H:%M:%S" + ) + self.time_real: datetime = ( + datetime.strptime(f"{data['rtDate']} {data['rtTime']}", "%Y-%m-%d %H:%M:%S") + if data.get("rtTime") and data.get("rtDate") + else None + ) + self.reachable: bool = data["reachable"] + self.direction: Union[str, None] = data.get("direction") + self.direction_flag: Union[str, None] = data.get("directionFlag") if "Messages" in data: self.messages.extend(Message(message) for message in data["Messages"]["Message"]) - if ("rtTime" in data) and ("rtDate" in data): - self.time_real_time = datetime.strptime(data["rtTime"], "%H:%M:%S") - self.date_real_time = datetime.strptime(data["rtDate"], "%Y-%m-%d") - else: - self.time_real_time = None - self.date_real_time = None - def __str__(self) -> str: return ( f"{self.name} heading {self.direction} at {self.time.time()} {self.date.date()}" @@ -79,28 +111,70 @@ class LineDeparture: class BoardArrival(list): - def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): + def __init__( + self, + data: Mapping[str, Any], + retrieve_stops: bool = False, + retrieve_journey: bool = False, + client: Union["pyrmv.Client", None] = None, + ): + """Arrival board representation + + ### Args: + * data (`Mapping[str, Any]`): Dictionary from RMV to be parsed. + * retrieve_stops (`bool`, *optional*): Retrieve `Stop` objects for each line of the board. Defaults to `False`. + * retrieve_journey (`bool`, *optional*): Retrieve `Journey` object for each line of the board. Defaults to `False`. + * client (`Union[Client, None]`, *optional*): Client to be used if `retrieve_stops` or `retrieve_journey` are set to `True`. Defaults to `None`. + """ super().__init__([]) if "Arrival" not in data: return for line in data["Arrival"]: - self.append(LineArrival(line, client, retrieve_stops=retrieve_stops)) + self.append( + LineArrival( + line, + retrieve_stops=retrieve_stops, + retrieve_journey=retrieve_journey, + client=client, + ) + ) def __str__(self) -> str: return "Arrival board\n" + "\n".join([str(line) for line in self]) class BoardDeparture(list): - def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True): + def __init__( + self, + data: Mapping[str, Any], + retrieve_stops: bool = False, + retrieve_journey: bool = False, + client: Union["pyrmv.Client", None] = None, + ): + """Departure board representation + + ### Args: + * data (`Mapping[str, Any]`): Dictionary from RMV to be parsed. + * retrieve_stops (`bool`, *optional*): Retrieve `Stop` objects for each line of the board. Defaults to `False`. + * retrieve_journey (`bool`, *optional*): Retrieve `Journey` object for each line of the board. Defaults to `False`. + * client (`Union[Client, None]`, *optional*): Client to be used if `retrieve_stops` or `retrieve_journey` are set to `True`. Defaults to `None`. + """ super().__init__([]) if "Departure" not in data: return for line in data["Departure"]: - self.append(LineDeparture(line, client, retrieve_stops=retrieve_stops)) + self.append( + LineDeparture( + line, + retrieve_stops=retrieve_stops, + retrieve_journey=retrieve_journey, + client=client, + ) + ) def __str__(self) -> str: return "Departure board\n" + "\n".join([str(line) for line in self]) diff --git a/src/pyrmv/classes/client.py b/src/pyrmv/classes/client.py index 1c04c1f..e9c9e72 100644 --- a/src/pyrmv/classes/client.py +++ b/src/pyrmv/classes/client.py @@ -10,7 +10,18 @@ from pyrmv.classes import ( StopTrip, Trip, ) -from pyrmv.enums import * +from pyrmv.enums import ( + AffectedJourneyMode, + AffectedJourneyStopMode, + BoardArrivalType, + BoardDepartureType, + FilterMode, + Language, + LocationType, + RealTimeMode, + SearchMode, + SelectionMode, +) from pyrmv.raw import board_arrival as raw_board_arrival from pyrmv.raw import board_departure as raw_board_departure from pyrmv.raw import him_search as raw_him_search @@ -60,7 +71,7 @@ class Client: board_departure = client.board_departure("A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@", journeys_max=5) # Search for HIM messages for S9 - messages = client.him_search(date_end=datetime.now()+timedelta(days=10), priority_min=2, train_names=["S9"]) + messages = client.him_search(time_end=datetime.now()+timedelta(days=10), priority_min=2, train_names=["S9"]) # Get detailed journey of Bus 101 journey = client.journey_detail("2|#VN#1#ST#1664906549#PI#0#ZI#12709#TA#0#DA#61022#1S#3008007#1T#1248#LS#3008043#LT#1323#PU#80#RT#1#CA#1aE#ZE#101#ZB#Bus 101 #PC#6#FR#3008007#FT#1248#TO#3008043#TT#1323#", real_time_mode=pyrmv.enums.RealTimeMode.FULL) @@ -77,15 +88,14 @@ class Client: """ def __init__(self, access_id: str) -> None: - self.access_id = access_id + self.access_id: str = access_id def board_arrival( self, id: Union[str, None] = None, id_ext: Union[str, None] = None, direction: Union[str, Stop, StopTrip, None] = None, - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, + time: Union[datetime, None] = None, duration: Union[int, timedelta] = 60, journeys_max: int = -1, operators: Union[str, list, None] = None, @@ -98,6 +108,7 @@ class Client: BoardArrivalType.ARR_STATION, ] = BoardArrivalType.ARR, retrieve_stops: bool = True, + retrieve_journey: bool = True, ) -> BoardArrival: """Method returns a board with arriving transport. @@ -107,15 +118,15 @@ class Client: * id (`str`, **optional**): Specifies the station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * id_ext (`str`, **optional**): Deprecated. Please use `id` as it supports external IDs. Specifies the external station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * direction (`Union[str, Stop, StopTrip]`, **optional**): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey or the Stop object itself. Defaults to `None`. - * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD or as a datetime object. By default the current server date is used. Defaults to `None`. - * time (`Union[str, datetime]`, **optional**): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature or as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. + * time (`datetime`, **optional**): Sets the start time for which the departures shall be retrieved. Represented as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. * duration (`Union[int, timedelta]`, **optional**): Set the interval size in minutes. Can also be provided as a timedelta. Defaults to `60`. * journeys_max (`int`, **optional**): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to `-1`. * operators (`Union[str, list]`, **optional**): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma or provide a list. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to `None`. * lines (`Union[str, list]`, **optional**): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma or provide a list. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to `None`. * passlist (`bool`, **optional**): Include a list of all passed waystops. Defaults to `False`. - * board_type (`Union[BoardArrivalType.ARR, BoardArrivalType.ARR_EQUIVS, BoardArrivalType.ARR_MAST, BoardArrivalType.ARR_STATION]`, optional): Set the station arrival board type to be used. Defaults to `BoardArrivalType.ARR`. + * board_type (`Union[BoardArrivalType.ARR, BoardArrivalType.ARR_EQUIVS, BoardArrivalType.ARR_MAST, BoardArrivalType.ARR_STATION]`, *optional*): Set the station arrival board type to be used. Defaults to `BoardArrivalType.ARR`. * retrieve_stops (`bool`, **optional**): Whether the stops should be retrieved as a `Stop` objects. Using `False` will drastically increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`. + * retrieve_journey (`bool`, **optional**): Whether the journey should be retrieved as a `Journey` object. Using `False` will increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`. ### Returns: * BoardArrival: Instance of `BoardArrival` object. @@ -129,7 +140,7 @@ class Client: id=id, extId=id_ext, direction=direction, # type: ignore - date=date, + date=time, time=time, duration=duration, maxJourneys=journeys_max, @@ -141,15 +152,19 @@ class Client: find_exception(board_raw) - return BoardArrival(board_raw, self, retrieve_stops=retrieve_stops) + return BoardArrival( + board_raw, + retrieve_stops=retrieve_stops, + retrieve_journey=retrieve_journey, + client=self, + ) def board_departure( self, id: Union[str, None] = None, id_ext: Union[str, None] = None, direction: Union[str, Stop, StopTrip, None] = None, - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, + time: Union[datetime, None] = None, duration: Union[int, timedelta] = 60, journeys_max: int = -1, operators: Union[str, list, None] = None, @@ -162,6 +177,7 @@ class Client: BoardDepartureType.DEP_STATION, ] = BoardDepartureType.DEP, retrieve_stops: bool = True, + retrieve_journey: bool = True, ) -> BoardDeparture: """Method returns a board with departing transport. @@ -171,15 +187,15 @@ class Client: * id (`str`, **optional**): Specifies the station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * id_ext (`str`, **optional**): Deprecated. Please use `id` as it supports external IDs. Specifies the external station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * direction (`Union[str, Stop, StopTrip]`, **optional**): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey or the Stop object itself. Defaults to `None`. - * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD or as a datetime object. By default the current server date is used. Defaults to `None`. - * time (`Union[str, datetime]`, **optional**): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature or as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. + * time (`datetime`, **optional**): Sets the start time for which the departures shall be retrieved. Represented as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. * duration (`Union[int, timedelta]`, **optional**): Set the interval size in minutes. Can also be provided as a timedelta. Defaults to `60`. * journeys_max (`int`, **optional**): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to `-1`. * operators (`Union[str, list]`, **optional**): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma or provide a list. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to `None`. * lines (`Union[str, list]`, **optional**): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma or provide a list. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to `None`. * passlist (`bool`, **optional**): Include a list of all passed waystops. Defaults to `False`. - * board_type (`Union[BoardDepartureType.DEP, BoardDepartureType.DEP_EQUIVS, BoardDepartureType.DEP_MAST, BoardDepartureType.DEP_STATION]`, optional): Set the station departure board type to be used. Defaults to `BoardDepartureType.DEP`. + * board_type (`Union[BoardDepartureType.DEP, BoardDepartureType.DEP_EQUIVS, BoardDepartureType.DEP_MAST, BoardDepartureType.DEP_STATION]`, *optional*): Set the station departure board type to be used. Defaults to `BoardDepartureType.DEP`. * retrieve_stops (`bool`, **optional**): Whether the stops should be retrieved as a `Stop` objects. Using `False` will drastically increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`. + * retrieve_journey (`bool`, **optional**): Whether the journey should be retrieved as a `Journey` object. Using `False` will increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`. ### Returns: * BoardDeparture: Instance of `BoardDeparture` object. @@ -193,7 +209,7 @@ class Client: id=id, extId=id_ext, direction=direction, # type: ignore - date=date, + date=time, time=time, duration=duration, maxJourneys=journeys_max, @@ -205,14 +221,17 @@ class Client: find_exception(board_raw) - return BoardDeparture(board_raw, self, retrieve_stops=retrieve_stops) + return BoardDeparture( + board_raw, + retrieve_stops=retrieve_stops, + retrieve_journey=retrieve_journey, + client=self, + ) def him_search( self, - date_begin: Union[str, datetime, None] = None, - date_end: Union[str, datetime, None] = None, - time_begin: Union[str, datetime, None] = None, - time_end: Union[str, datetime, None] = None, + time_begin: Union[datetime, None] = None, + time_end: Union[datetime, None] = None, weekdays: Union[str, OrderedDict[str, bool], None] = None, ids: Union[list, None] = None, operators: Union[list, None] = None, @@ -249,28 +268,26 @@ class Client: More detailed request is available as `raw.him_search()`, however returns `dict` instead of `List[Message]`. ### Args: - * date_begin (`Union[str, datetime]`, optional): Sets the event period start date. Defaults to `None`. - * date_end (`Union[str, datetime]`, optional): Sets the event period end date. Defaults to `None`. - * time_begin (`Union[str, datetime]`, optional): Sets the event period start time. Defaults to `None`. - * time_end (`Union[str, datetime]`, optional): Sets the event period end time. Defaults to `None`. - * weekdays (`Union[str, OrderedDict[str, bool]]`, optional): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to `None`. - * ids (`list`, optional): List of HIM message IDs as a list or separated by comma. Defaults to `None`. - * operators (`list`, optional): List of operators as a list or separated by comma. Defaults to `None`. - * categories (`list`, optional): List of train categories as a list or separated by comma. Defaults to `None`. - * channels (`list`, optional): List of channels as a list or separated by comma. Defaults to `None`. - * companies (`list`, optional): List of companies as a list or separated by comma. Defaults to `None`. - * lines (`list`, optional): Only HIM messages for the given line are part of the result. To filter multiple lines, provide them as a list or separate the codes by comma. Defaults to `None`. - * line_ids (`list`, optional): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, provide them as a list or separate the line IDs by comma. Defaults to `None`. - * stations (`Union[list, List[Stop]]`, optional): List of (external) station ids or a list of `Stop` objects to be filtered for as a list or separated by comma. Defaults to `None`. - * station_from (`Union[str, Stop]`, optional): Filter messages by line segment starting at this station given as (external) station id or as a `Stop` object. Defaults to `None`. - * station_to (`Union[str, Stop]`, optional): Filter messages by line segment travelling in direction of this station given as (external) station id or as a `Stop` object. Defaults to `None`. - * both_ways (`bool`, optional): If enabled, messages in both directions - from 'station_from' to 'station_to' as well as from 'station_to' to 'station_from' are returned. Defaults to `None`. - * train_names (`list`, optional): List of train name to be filtered for seperated by comma. Defaults to `None`. - * search_mode (`Literal[SearchMode.MATCH, SearchMode.NOMATCH, SearchMode.TFMATCH]`, optional): HIM search mode. `SearchMode.NOMATCH` iterate over all HIM messages available. `SearchMode.MATCH` iterate over all trips to find HIM messages. `SearchMode.TFMATCH` uses filters defined `metas` parameter. Defaults to `None`. - * affected_journey_mode (`Literal[AffectedJourneyMode.ALL, AffectedJourneyMode.OFF]`, optional): Define how to return affected journeys `AffectedJourneyMode.OFF`: do not return affected journeys. `AffectedJourneyMode.ALL`: return affected journeys. Defaults to `None`. - * affected_journey_stop_mode (`Literal[AffectedJourneyStopMode.ALL, AffectedJourneyStopMode.IMP, AffectedJourneyStopMode.OFF]`, optional): Define how to return stops of affected journeys. `AffectedJourneyStopMode.IMP`: return important stops of affected journeys. `AffectedJourneyStopMode.OFF`: do not return stops of affected journeys. `AffectedJourneyStopMode.ALL`: return all affected stops of affected journeys. Defaults to `None`. - * priority_min (`int`, optional): Filter for HIM messages having at least this priority. Defaults to `None`. - * priority_max (`int`, optional): Filter for HIM messages having this priority as maximum. Defaults to `None`. + * time_begin (`datetime`, *optional*): Sets the event period start time. Represented as a datetime object. Defaults to `None`. + * time_end (`datetime`, *optional*): Sets the event period end time. Represented as a datetime object. Defaults to `None`. + * weekdays (`Union[str, OrderedDict[str, bool]]`, *optional*): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to `None`. + * ids (`list`, *optional*): List of HIM message IDs as a list or separated by comma. Defaults to `None`. + * operators (`list`, *optional*): List of operators as a list or separated by comma. Defaults to `None`. + * categories (`list`, *optional*): List of train categories as a list or separated by comma. Defaults to `None`. + * channels (`list`, *optional*): List of channels as a list or separated by comma. Defaults to `None`. + * companies (`list`, *optional*): List of companies as a list or separated by comma. Defaults to `None`. + * lines (`list`, *optional*): Only HIM messages for the given line are part of the result. To filter multiple lines, provide them as a list or separate the codes by comma. Defaults to `None`. + * line_ids (`list`, *optional*): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, provide them as a list or separate the line IDs by comma. Defaults to `None`. + * stations (`Union[list, List[Stop]]`, *optional*): List of (external) station ids or a list of `Stop` objects to be filtered for as a list or separated by comma. Defaults to `None`. + * station_from (`Union[str, Stop]`, *optional*): Filter messages by line segment starting at this station given as (external) station id or as a `Stop` object. Defaults to `None`. + * station_to (`Union[str, Stop]`, *optional*): Filter messages by line segment travelling in direction of this station given as (external) station id or as a `Stop` object. Defaults to `None`. + * both_ways (`bool`, *optional*): If enabled, messages in both directions - from 'station_from' to 'station_to' as well as from 'station_to' to 'station_from' are returned. Defaults to `None`. + * train_names (`list`, *optional*): List of train name to be filtered for seperated by comma. Defaults to `None`. + * search_mode (`Literal[SearchMode.MATCH, SearchMode.NOMATCH, SearchMode.TFMATCH]`, *optional*): HIM search mode. `SearchMode.NOMATCH` iterate over all HIM messages available. `SearchMode.MATCH` iterate over all trips to find HIM messages. `SearchMode.TFMATCH` uses filters defined `metas` parameter. Defaults to `None`. + * affected_journey_mode (`Literal[AffectedJourneyMode.ALL, AffectedJourneyMode.OFF]`, *optional*): Define how to return affected journeys `AffectedJourneyMode.OFF`: do not return affected journeys. `AffectedJourneyMode.ALL`: return affected journeys. Defaults to `None`. + * affected_journey_stop_mode (`Literal[AffectedJourneyStopMode.ALL, AffectedJourneyStopMode.IMP, AffectedJourneyStopMode.OFF]`, *optional*): Define how to return stops of affected journeys. `AffectedJourneyStopMode.IMP`: return important stops of affected journeys. `AffectedJourneyStopMode.OFF`: do not return stops of affected journeys. `AffectedJourneyStopMode.ALL`: return all affected stops of affected journeys. Defaults to `None`. + * priority_min (`int`, *optional*): Filter for HIM messages having at least this priority. Defaults to `None`. + * priority_max (`int`, *optional*): Filter for HIM messages having this priority as maximum. Defaults to `None`. ### Returns: * List[Message]: List of `Message` objects. Empty list if none found. @@ -302,8 +319,8 @@ class Client: messages = [] messages_raw = raw_him_search( accessId=self.access_id, - dateB=date_begin, - dateE=date_end, + dateB=time_begin, + dateE=time_end, timeB=time_begin, timeE=time_end, weekdays=weekdays, @@ -394,18 +411,30 @@ class Client: coords_lat: Union[str, float], coords_lon: Union[str, float], lang: Literal[ - Language.DE, + Language.AR, + Language.CA, Language.DA, + Language.DE, + Language.EL, Language.EN, Language.ES, + Language.FI, Language.FR, + Language.HI, + Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, + Language.RU, + Language.SK, + Language.SL, Language.SV, + Language.TL, Language.TR, + Language.UR, + Language.ZH, ] = Language.EN, radius: Union[int, float] = 1000, max_number: int = 10, @@ -428,7 +457,7 @@ class Client: ### Args: * coords_lat (`Union[str, float]`): Latitude of centre coordinate. * coords_lon (`Union[str, float]`): Longitude of centre coordinate. - * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`. + * lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. * radius (`Union[int, float]`, **optional**): Search radius in meter around the given coordinate if any. Defaults to `1000`. * max_number (`int`, **optional**): Maximum number of returned stops. Defaults to `10`. * stop_type (`Literal[LocationType.S, LocationType.P, LocationType.SP, LocationType.SE, LocationType.SPE]`, **optional**): Type filter for location types. Defaults to `LocationType.S`. @@ -467,25 +496,37 @@ class Client: self, query: str, lang: Literal[ - Language.DE, + Language.AR, + Language.CA, Language.DA, + Language.DE, + Language.EL, Language.EN, Language.ES, + Language.FI, Language.FR, + Language.HI, + Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, + Language.RU, + Language.SK, + Language.SL, Language.SV, + Language.TL, Language.TR, + Language.UR, + Language.ZH, ] = Language.EN, ) -> Union[Stop, None]: """Method can be used to get Stop object whilst only having id available. ### Args: * query (`str`): Search for that token. - * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`. + * lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. ### Returns: * Union[Stop, None]: Instance of `Stop` object or `None` if not found. @@ -513,18 +554,30 @@ class Client: self, query: str, lang: Literal[ - Language.DE, + Language.AR, + Language.CA, Language.DA, + Language.DE, + Language.EL, Language.EN, Language.ES, + Language.FI, Language.FR, + Language.HI, + Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, + Language.RU, + Language.SK, + Language.SL, Language.SV, + Language.TL, Language.TR, + Language.UR, + Language.ZH, ] = Language.EN, max_number: int = 10, stop_type: Literal[ @@ -556,7 +609,7 @@ class Client: ### Args: * query (`str`): Search for that token. - * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`. + * lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. * max_number (`int`, **optional**): Maximum number of returned stops. In range 1-1000. Defaults to `10`. * stop_type (`Literal[LocationType.A, LocationType.ALL, LocationType.AP, LocationType.P, LocationType.S, LocationType.SA, LocationType.SP]`, **optional**): Type filter for location types. Defaults to `LocationType.ALL`. * selection_mode (`Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N]`, **optional**): Selection mode for locations. `SelectionMode.SLCT_N`: Not selectable, `SelectionMode.SLCT_A`: Selectable. Defaults to `None`. @@ -603,18 +656,30 @@ class Client: def trip_find( self, lang: Literal[ - Language.DE, + Language.AR, + Language.CA, Language.DA, + Language.DE, + Language.EL, Language.EN, Language.ES, + Language.FI, Language.FR, + Language.HI, + Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, + Language.RU, + Language.SK, + Language.SL, Language.SV, + Language.TL, Language.TR, + Language.UR, + Language.ZH, ] = Language.EN, origin_id: Union[str, None] = None, origin_id_ext: Union[str, None] = None, @@ -637,8 +702,7 @@ class Client: change_time_max: Union[int, None] = None, change_time_add: Union[int, None] = None, change_max: Union[int, None] = None, - date: Union[str, datetime, None] = None, - time: Union[str, datetime, None] = None, + time: Union[datetime, None] = None, search_arrival: bool = False, trips_after_time: Union[int, None] = None, trips_before_time: Union[int, None] = None, @@ -674,7 +738,7 @@ class Client: More detailed request is available as `raw.trip_find()`, however returns `dict` instead of `List[Trip]`. ### Args: - * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`. + * lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. * origin_id (`str`, **optional**): Specifies the station/stop ID of the origin for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * origin_id_ext (`str`, **optional**): Deprecated. Please use originId as it supports external IDs. Specifies the external station/stop ID of the origin for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * origin_coord_lat (`Union[str, float]`, **optional**): Latitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. @@ -689,15 +753,14 @@ class Client: * via_id (`str`, **optional**): ID of a station/stop used as a via for the trip. Specifying a via station forces the trip search to look for trips which must pass through this station. Such ID can be retrieved from stop_by_name() or stop_by_coords(). If `via` is used, `via_id` and `via_wait_time ` are having no effect. Defaults to `None`. * via_gis (`str`, **optional**): Complex structure to provide multiple GIS via locations separated by semicolon. This structure is build like this: `locationId|locationMode|transportMode|placeType|usageType|mode|durationOfStay`. Read more about this in HAFAS ReST Documentation. Defaults to `None`. * via_wait_time (`int`, **optional**): Defines the waiting time spent at via station in minutes. If `via` is used, `via_id` and `via_wait_time` are having no effect. Defaults to 0. - * avoid (`str`, **optional**): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), optional but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to `None`. + * avoid (`str`, **optional**): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), *optional* but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to `None`. * avoid_id (`str`, **optional**): ID of a station/stop to be avoided as transfer stop for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). If `avoid` is used, `avoid_id` has no effect. Defaults to `None`. * change_time_percent (`int`, **optional**): Configures the walking speed when changing from one leg of the journey to the next one. It extends the time required for changes by a specified percentage. A value of 200 doubles the change time as initially calculated by the system. In the response, change time is presented in full minutes. If the calculation based on changeTime-Percent does not result in a full minute, it is rounded using "round half up" method. Defaults to `100`. * change_time_min (`int`, **optional**): Minimum change time at stop in minutes. Defaults to `None`. * change_time_max (`int`, **optional**): Maximum change time at stop in minutes. Defaults to `None`. * change_time_add (`int`, **optional**): This amount of minutes is added to the change time at each stop. Defaults to `None`. * change_max (`int`, **optional**): Maximum number of changes. In range 0-11. Defaults to `None`. - * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD` or as a datetime object. By default the current server date is used. Defaults to `None`. - * time (`Union[str, datetime]`, **optional**): Sets the start time for which the departures shall be retrieved. Represented in the format `hh:mm[:ss]` in 24h nomenclature or as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. + * time (`datetime`, **optional**): Sets the start time for which the departures shall be retrieved. Represented as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. * search_arrival (`bool`, **optional**): If set, the date and time parameters specify the arrival time for the trip search instead of the departure time. Defaults to `False`. * trips_after_time (`int`, **optional**): Minimum number of trips after the search time. Sum of `trips_after_time` and `trips_before_time` has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 1-6. Defaults to `None`. * trips_before_time (`int`, **optional**): Minimum number of trips before the search time. Sum of `trips_after_time` and `trips_before_time` has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 0-6. Defaults to `None`. @@ -748,7 +811,7 @@ class Client: maxChangeTime=change_time_max, addChangeTime=change_time_add, maxChange=change_max, - date=date, + date=time, time=time, searchForArrival=search_arrival, numF=trips_after_time, @@ -780,7 +843,7 @@ class Client: def trip_recon( self, context: Union[str, Trip], - date: Union[str, datetime, None] = None, + date: Union[datetime, None] = None, match_real_time: Union[bool, None] = None, enable_replacements: Union[bool, None] = None, arrival_dev_lower: Union[int, None] = None, @@ -810,7 +873,7 @@ class Client: ### Args: * context (`Union[str, Journey]`): Specifies the reconstruction context. - * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD` or as a datetime object. This parameter will force the service to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, exception SvcNoResultError will be raised. Defaults to `None`. + * date (`datetime`, **optional**): Sets the start date for which the departures shall be retrieved. Represented as a datetime object. This parameter will force the service to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, exception SvcNoResultError will be raised. Defaults to `None`. * match_real_time (`bool`, **optional**): Whether the realtime type that journeys are based on be considered. Defaults to `None`. * enable_replacements (`bool`, **optional**): If set to `True` replaces cancelled journeys with their replacement journeys if possible. Defaults to `None`. * arrival_dev_lower (`int`, **optional**): Lower deviation in minutes within interval `[0, 720]` indicating "how much earlier than original arrival". Defaults to `None`. diff --git a/src/pyrmv/classes/gis.py b/src/pyrmv/classes/gis.py index ff972b6..a53b159 100644 --- a/src/pyrmv/classes/gis.py +++ b/src/pyrmv/classes/gis.py @@ -1,13 +1,14 @@ -from typing import Any, Mapping +from datetime import timedelta +from typing import Any, Mapping, Union -from isodate import parse_duration +from isodate import Duration, parse_duration class Gis: """Gis object.""" def __init__(self, ref: str, route: Mapping[str, Any]): - self.ref = ref - self.dist = route["dist"] - self.duration = parse_duration(route["durS"]) - self.geo = route["dirGeo"] + self.ref: str = ref + self.dist: Union[int, None] = route.get("dist") + self.duration: Union[Duration, timedelta] = parse_duration(route["durS"]) + self.geo: Union[int, None] = route.get("dirGeo") diff --git a/src/pyrmv/classes/journey.py b/src/pyrmv/classes/journey.py index 32aa574..45ea7e7 100644 --- a/src/pyrmv/classes/journey.py +++ b/src/pyrmv/classes/journey.py @@ -1,4 +1,4 @@ -from typing import Any, Mapping +from typing import Any, List, Mapping, Union from pyrmv.classes.message import Message from pyrmv.classes.stop import Stop @@ -9,16 +9,24 @@ class Journey: """Journey object.""" def __init__(self, data: Mapping[str, Any]): - self.stops = [] + self.stops: List[Stop] = [] # Upgrade is temporarily used due to RMV API mismatch # self.ref = data["ref"] - self.ref = ref_upgrade(data["ref"]) + self.ref: str = ref_upgrade(data["ref"]) - self.direction = data["Directions"]["Direction"][0]["value"] - self.direction_flag = data["Directions"]["Direction"][0]["flag"] + self.direction: Union[str, None] = ( + data["Directions"]["Direction"][0].get("value") + if data["Directions"]["Direction"] + else None + ) + self.direction_flag: Union[str, None] = ( + data["Directions"]["Direction"][0].get("flag") + if data["Directions"]["Direction"] + else None + ) self.stops.extend(Stop(stop) for stop in data["Stops"]["Stop"]) - self.messages = [] + self.messages: List[Message] = [] if "Messages" in data: self.messages.extend(Message(message) for message in data["Messages"]["Message"]) diff --git a/src/pyrmv/classes/leg.py b/src/pyrmv/classes/leg.py index eb27d5f..968694a 100644 --- a/src/pyrmv/classes/leg.py +++ b/src/pyrmv/classes/leg.py @@ -1,6 +1,7 @@ -from typing import Any, Mapping +from datetime import timedelta +from typing import Any, List, Mapping, Union -from isodate import parse_duration +from isodate import Duration, parse_duration from pyrmv.classes.gis import Gis from pyrmv.classes.message import Message @@ -11,19 +12,19 @@ class Leg: """Trip leg object.""" def __init__(self, data: Mapping[str, Any]): - self.origin = StopTrip(data["Origin"]) - self.destination = StopTrip(data["Destination"]) + self.origin: StopTrip = StopTrip(data["Origin"]) + self.destination: StopTrip = StopTrip(data["Destination"]) self.gis = ( None if "GisRef" not in data else Gis(data["GisRef"]["ref"], data["GisRoute"]) ) - self.messages = [] - self.index = data["idx"] - self.name = data["name"] - self.type = data["type"] - self.direction = data.get("direction") - self.number = data.get("number") - self.duration = parse_duration(data["duration"]) - self.distance = data.get("dist") + self.messages: List[Message] = [] + self.index: Union[int, None] = data.get("idx") + self.name: str = data["name"] + self.type: Union[str, None] = data.get("type") + self.direction: Union[str, None] = data.get("direction") + self.number: Union[str, None] = data.get("number") + self.duration: Union[Duration, timedelta] = parse_duration(data["duration"]) + self.distance: Union[int, None] = data.get("dist") if "Messages" in data: self.messages.extend(Message(message) for message in data["Messages"]["Message"]) diff --git a/src/pyrmv/classes/message.py b/src/pyrmv/classes/message.py index f5ae8e2..b08dfe5 100644 --- a/src/pyrmv/classes/message.py +++ b/src/pyrmv/classes/message.py @@ -1,7 +1,7 @@ -from datetime import datetime -from typing import Any, Mapping +from datetime import datetime, timedelta +from typing import Any, List, Mapping, Union -from isodate import parse_duration +from isodate import Duration, parse_duration from pyrmv.classes.stop import Stop @@ -10,8 +10,8 @@ class Url: """Traffic message channel url object.""" def __init__(self, data: Mapping[str, Any]) -> None: - self.name = data["name"] - self.url = data["url"] + self.name: str = data["name"] + self.url: str = data["url"] def __str__(self) -> str: return f"{self.name}: {self.url}" @@ -21,51 +21,84 @@ class Channel: """Traffic message channel object.""" def __init__(self, data: Mapping[str, Any]) -> None: - self.name = data["name"] + self.name: str = data["name"] url = [] url.extend(Url(link) for link in url) - self.url = url - self.time_start = datetime.strptime(data["validFromTime"], "%H:%M:%S") - self.date_start = datetime.strptime(data["validFromDate"], "%Y-%m-%d") - self.time_end = datetime.strptime(data["validToTime"], "%H:%M:%S") - self.date_end = datetime.strptime(data["validToDate"], "%Y-%m-%d") + self.url: List[Url] = url + self.time_start: Union[datetime, None] = ( + None + if "validFromDate" not in data + else datetime.strptime( + f"{data['validFromDate']} {data['validFromTime']}", "%Y-%m-%d %H:%M:%S" + ) + ) + self.time_end: Union[datetime, None] = ( + None + if "validToDate" not in data + else datetime.strptime( + f"{data['validToDate']} {data['validToTime']}", "%Y-%m-%d %H:%M:%S" + ) + ) def __str__(self) -> str: - return f"{self.name}: from {self.time_start} {self.date_start} until {self.time_end} {self.date_end}" + return f"{self.name}: from {self.time_start} until {self.time_end}" class Message: """Traffic message object.""" def __init__(self, data: Mapping[str, Any]) -> None: - self.affected_stops = [] - self.valid_from_stop = ( + self.affected_stops: List[Stop] = [] + self.valid_from_stop: Union[Stop, None] = ( None if "validFromStop" not in data else Stop(data["validFromStop"]) ) - self.valid_to_stop = None if "validToStop" not in data else Stop(data["validToStop"]) - self.channels = [] + self.valid_to_stop: Union[Stop, None] = ( + None if "validToStop" not in data else Stop(data["validToStop"]) + ) + self.channels: Union[Channel, None] = [] self.channels.extend(Channel(channel) for channel in data["channel"]) - self.id = data["id"] - self.active = data["act"] - self.head = data["head"] - self.lead = data["lead"] - self.text = data["text"] - self.company = data["company"] - self.category = data["category"] - self.priority = None if "priority" not in data else data["priority"] - self.products = data["products"] - self.icon = data["icon"] - self.time_start = datetime.strptime(data["sTime"], "%H:%M:%S") - self.date_start = datetime.strptime(data["sDate"], "%Y-%m-%d") - self.time_end = datetime.strptime(data["eTime"], "%H:%M:%S") - self.date_end = datetime.strptime(data["eDate"], "%Y-%m-%d") - self.date_start_alt = data["altStart"] - self.date_end_alt = data["altEnd"] - self.time_modified = datetime.strptime(data["modTime"], "%H:%M:%S") - self.date_modified = datetime.strptime(data["modDate"], "%Y-%m-%d") - self.daily_start = datetime.strptime(data["dailyStartingAt"], "%H:%M:%S") - self.daily_duration = parse_duration(data["dailyDuration"]) - self.base_type = data["baseType"] if "baseType" in data else None + self.id: str = data["id"] + self.active: bool = data["act"] + self.head: str = data["head"] + self.lead: str = data["lead"] + self.text: str = data["text"] + self.company: Union[str, None] = data.get("company") + self.category: Union[str, None] = data.get("category") + self.priority: Union[int, None] = data.get("priority") + self.products: int = data["products"] + self.icon: Mapping[str, Any] = data["icon"] + self.time_start: Union[datetime, None] = ( + None + if "validFromDate" not in data or "validFromTime" not in data + else datetime.strptime( + f"{data['validFromDate']} {data['validFromTime']}", "%Y-%m-%d %H:%M:%S" + ) + ) + self.time_end: Union[datetime, None] = ( + None + if "validToDate" not in data or "validToTime" not in data + else datetime.strptime( + f"{data['validToDate']} {data['validToTime']}", "%Y-%m-%d %H:%M:%S" + ) + ) + self.date_start_alt: str = data["altStart"] + self.date_end_alt: str = data["altEnd"] + self.time_modified: Union[datetime, None] = ( + None + if "modDate" not in data or "modTime" not in data + else datetime.strptime( + f"{data['modDate']} {data['modTime']}", "%Y-%m-%d %H:%M:%S" + ) + ) + self.daily_start: Union[datetime, None] = ( + None + if "dailyStartingAt" not in data + else datetime.strptime(data["dailyStartingAt"], "%H:%M:%S") + ) + self.daily_duration: Union[Duration, timedelta] = parse_duration( + data["dailyDuration"] + ) + self.base_type: Union[str, None] = data.get("baseType") if "affectedStops" in data: self.affected_stops.extend( @@ -73,4 +106,4 @@ class Message: ) def __str__(self) -> str: - return f"{self.base_type} message with priority {self.products} valid from {self.time_start.time()} {self.date_start.date()} until {self.time_end.time()} {self.date_end.date()}: {self.head} - {self.lead}" + return f"{self.base_type} message with priority {self.products} valid from {self.time_start} until {self.time_end}: {self.head} - {self.lead}" diff --git a/src/pyrmv/classes/stop.py b/src/pyrmv/classes/stop.py index e197e1c..74022d2 100644 --- a/src/pyrmv/classes/stop.py +++ b/src/pyrmv/classes/stop.py @@ -1,19 +1,20 @@ from datetime import datetime +from typing import Union class Stop: """Stop object.""" def __init__(self, data: dict): - self.name = data["name"] - self.id = data["id"] - self.ext_id = data.get("extId") - self.description = data.get("description") - self.lon = data["lon"] - self.lat = data["lat"] - self.route_index = data.get("routeIdx") - self.track_arrival = data.get("arrTrack") - self.track_departure = data.get("depTrack") + self.name: str = data["name"] + self.id: str = data["id"] + self.ext_id: Union[str, None] = data.get("extId") + self.description: Union[str, None] = data.get("description") + self.lon: float = data["lon"] + self.lat: float = data["lat"] + self.route_index: Union[int, None] = data.get("routeIdx") + self.track_arrival: Union[str, None] = data.get("arrTrack") + self.track_departure: Union[str, None] = data.get("depTrack") def __str__(self) -> str: return f"Stop {self.name} at {self.lon}, {self.lat}" @@ -23,10 +24,11 @@ class StopTrip(Stop): """Trip stop object. It's like a Stop object, but with a date and time.""" def __init__(self, data: dict): - self.type = data["type"] - self.date = datetime.strptime(data["date"], "%Y-%m-%d") - self.time = datetime.strptime(data["time"], "%H:%M:%S") + self.type: str = data["type"] + self.time: datetime = datetime.strptime( + f"{data['date']} {data['time']}", "%Y-%m-%d %H:%M:%S" + ) super().__init__(data) def __str__(self) -> str: - return f"Stop {self.name} at {self.lon}, {self.lat} at {self.time.time()} {self.date.date()}" + return f"Stop {self.name} at {self.lon}, {self.lat} at {self.time.time()}" diff --git a/src/pyrmv/classes/trip.py b/src/pyrmv/classes/trip.py index 3693f16..9bab704 100644 --- a/src/pyrmv/classes/trip.py +++ b/src/pyrmv/classes/trip.py @@ -1,4 +1,7 @@ -from isodate import parse_duration +from datetime import timedelta +from typing import List, Union + +from isodate import Duration, parse_duration from pyrmv.classes.leg import Leg from pyrmv.classes.stop import StopTrip @@ -8,21 +11,20 @@ class Trip: """Trip object.""" def __init__(self, data: dict): - self.raw_data = data - self.origin = StopTrip(data["Origin"]) - self.destination = StopTrip(data["Destination"]) - self.legs = [] + self.origin: StopTrip = StopTrip(data["Origin"]) + self.destination: StopTrip = StopTrip(data["Destination"]) + self.legs: List[Leg] = [] self.legs.extend(Leg(leg) for leg in data["LegList"]["Leg"]) - self.calculation = data["calculation"] - self.index = data["idx"] - self.id = data["tripId"] - self.ctx_recon = data["ctxRecon"] - self.duration = parse_duration(data["duration"]) - self.real_time_duration = ( + self.calculation: str = data["calculation"] + self.index: int = data["idx"] + self.id: str = data["tripId"] + self.ctx_recon: str = data["ctxRecon"] + self.duration: Union[Duration, timedelta] = parse_duration(data["duration"]) + self.real_time_duration: Union[Duration, timedelta] = ( None if "rtDuration" not in data else parse_duration(data["rtDuration"]) ) - self.checksum = data["checksum"] - self.transfer_count = data.get("transferCount", 0) + self.checksum: str = data["checksum"] + self.transfer_count: int = data.get("transferCount", 0) def __str__(self) -> str: return f"Trip from {self.origin.name} to {self.destination.name} lasting {self.duration} ({self.real_time_duration}) with {len(self.legs)} legs and {self.transfer_count} transfers" diff --git a/src/pyrmv/raw/board_arrival.py b/src/pyrmv/raw/board_arrival.py index fee0b99..1e34527 100644 --- a/src/pyrmv/raw/board_arrival.py +++ b/src/pyrmv/raw/board_arrival.py @@ -40,22 +40,22 @@ def board_arrival( ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. - * id (str, optional): Access ID for identifying the requesting client. Defaults to None. - * extId (str, optional): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None. - * direction (str, optional): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None. - * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None. - * time (Union[str, datetime], optional): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. - * duration (int, optional): Set the interval size in minutes. Defaults to 60. - * maxJourneys (int, optional): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1. - * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. - * operators (Union[str, list], optional): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None. - * lines (Union[str, list], optional): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. - * filterEquiv (bool, optional): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True. - * attributes (Union[str, list], optional): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None. - * platforms (Union[str, list], optional): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None. - * passlist (bool, optional): Include a list of all passed waystops. Defaults to False. - * boardType (Literal["ARR", "ARR_EQUIVS", "ARR_MAST", "ARR_STATION"], optional): Set the station arrival board type to be used. ARR: Arrival board as configured in HAFAS; ARR_EQUIVS: Arrival board with all journeys at any masts and equivalent stops; ARR_MAST: Arrival board at mast; ARR_STATION: Arrival board with all journeys at any masts of the requested station. Defaults to "ARR". + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. + * id (str, *optional*): Access ID for identifying the requesting client. Defaults to None. + * extId (str, *optional*): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None. + * direction (str, *optional*): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None. + * date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None. + * time (Union[str, datetime], *optional*): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. + * duration (int, *optional*): Set the interval size in minutes. Defaults to 60. + * maxJourneys (int, *optional*): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1. + * products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. + * operators (Union[str, list], *optional*): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None. + * lines (Union[str, list], *optional*): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. + * filterEquiv (bool, *optional*): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True. + * attributes (Union[str, list], *optional*): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None. + * platforms (Union[str, list], *optional*): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None. + * passlist (bool, *optional*): Include a list of all passed waystops. Defaults to False. + * boardType (Literal["ARR", "ARR_EQUIVS", "ARR_MAST", "ARR_STATION"], *optional*): Set the station arrival board type to be used. ARR: Arrival board as configured in HAFAS; ARR_EQUIVS: Arrival board with all journeys at any masts and equivalent stops; ARR_MAST: Arrival board at mast; ARR_STATION: Arrival board with all journeys at any masts of the requested station. Defaults to "ARR". ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/src/pyrmv/raw/board_departure.py b/src/pyrmv/raw/board_departure.py index 57e76b2..e3cef29 100644 --- a/src/pyrmv/raw/board_departure.py +++ b/src/pyrmv/raw/board_departure.py @@ -41,22 +41,22 @@ def board_departure( ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. - * id (str, optional): Access ID for identifying the requesting client. Defaults to None. - * extId (str, optional): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None. - * direction (str, optional): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None. - * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None. - * time (Union[str, datetime], optional): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. - * duration (int, optional): Set the interval size in minutes. Defaults to 60. - * maxJourneys (int, optional): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1. - * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. - * operators (Union[str, list], optional): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None. - * lines (Union[str, list], optional): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. - * filterEquiv (bool, optional): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True. - * attributes (Union[str, list], optional): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None. - * platforms (Union[str, list], optional): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None. - * passlist (bool, optional): Include a list of all passed waystops. Defaults to False. - * boardType (Literal["DEP", "DEP_EQUIVS", "DEP_MAST", "DEP_STATION"], optional): Set the station departure board type to be used. DEP: Departure board as configured in HAFAS; DEP_EQUIVS: Departure board with all journeys at any masts and equivalent stops; DEP_MAST: Departure board at mast; DEP_STATION: Departure board with all journeys at any masts of the requested station. Defaults to "DEP". + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. + * id (str, *optional*): Access ID for identifying the requesting client. Defaults to None. + * extId (str, *optional*): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None. + * direction (str, *optional*): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None. + * date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None. + * time (Union[str, datetime], *optional*): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. + * duration (int, *optional*): Set the interval size in minutes. Defaults to 60. + * maxJourneys (int, *optional*): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1. + * products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. + * operators (Union[str, list], *optional*): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None. + * lines (Union[str, list], *optional*): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. + * filterEquiv (bool, *optional*): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True. + * attributes (Union[str, list], *optional*): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None. + * platforms (Union[str, list], *optional*): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None. + * passlist (bool, *optional*): Include a list of all passed waystops. Defaults to False. + * boardType (Literal["DEP", "DEP_EQUIVS", "DEP_MAST", "DEP_STATION"], *optional*): Set the station departure board type to be used. DEP: Departure board as configured in HAFAS; DEP_EQUIVS: Departure board with all journeys at any masts and equivalent stops; DEP_MAST: Departure board at mast; DEP_STATION: Departure board with all journeys at any masts of the requested station. Defaults to "DEP". ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/src/pyrmv/raw/him_search.py b/src/pyrmv/raw/him_search.py index ae38717..c8911cf 100644 --- a/src/pyrmv/raw/him_search.py +++ b/src/pyrmv/raw/him_search.py @@ -56,39 +56,39 @@ def him_search( ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. - * dateB (Union[str, datetime], optional): Sets the event period start date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. - * dateE (Union[str, datetime], optional): Sets the event period end date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. - * timeB (Union[str, datetime], optional): Sets the event period start time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. - * timeE (Union[str, datetime], optional): Sets the event period end time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. - * weekdays (Union[str, OrderedDict[str, bool]], optional): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to None. - * himIds (Union[str, list], optional): List of HIM message IDs as a list or as a string separated by comma. Defaults to None. - * hierarchicalView (bool, optional): Return parent messages with childs. Defaults to False. - * operators (Union[str, list], optional): List of operators as a list or as a string separated by comma. Defaults to None. - * categories (Union[str, list], optional): List of train categories as a list or as a string separated by comma. Defaults to None. - * channels (Union[str, list], optional): List of channels as a list or as a string separated by comma. Defaults to None. - * companies (Union[str, list], optional): List of companies as a list or as a string separated by comma. Defaults to None. - * lines (Union[str, list], optional): Only HIM messages for the given line are part of the result. To filter multiple lines, separate the codes by comma. Defaults to None. - * lineids (Union[str, list], optional): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, separate the line IDs by comma. Defaults to None. - * stations (Union[str, list], optional): List of (external) station ids to be filtered for as a list or as a string separated by comma. Defaults to None. - * fromstation (str, optional): Filter messages by line segment starting at this station given as (external) station id. Defaults to None. - * tostation (str, optional): Filter messages by line segment travelling in direction of this station given as (external) station id. Defaults to None. - * bothways (bool, optional): If enabled, messages in both directions - from 'fromstation' to 'tostation' as well as from 'tostation' to 'fromstation' are returned. Defaults to None. - * trainnames (Union[str, list], optional): List of train name to be filtered for as a list or as a string separated by comma. Defaults to None. - * metas (Union[str, list], optional): List of predefined filters as a list or as a string separated by comma. Defaults to None. - * himcategory (str, optional): HIM category, e.g. Works and/or Disturbance. Value depends on your HAFAS server data. Defaults to None. - * himtags (Union[str, list], optional): HIM Tags. Value depends on your HAFAS server data. Return HIM messages having these tag(s) only. Multiple values are separated by comma. Note: HIM tags differ from HIM text tags. Defaults to None. - * regions (Union[str, list], optional): Filter for HIM messages based on regions defined in HAFAS raw data. As a list or as a string separated by comma. Available regions can be retrieved by /datainfo service. Defaults to None. - * himtext (Union[str, list], optional): Filter for HIM messages containing the given free text message as a list or as a string separated by comma. Defaults to None. - * himtexttags (Union[str, list], optional): Return HIM texts having this text tag(s) only. Multiple values are separated by comma. Note: HIM text tags differ from HIM tags. Defaults to None. - * additionalfields (Union[str, list, dict], optional): List of additional fields and values to be filtered for. Two filter options are available: Filter by key only: `additionalfields=key` or filter by key and value: `additionalfields={key:value}`. Multiple filters are separated by comma like `additionalfields=[keyA,keyB]` or `additionalfields={key:value}`. Defaults to None. - * poly (bool, optional): Enables/disables returning of geo information for affected edges and regions if available and enabled in the backend. Defaults to False. - * searchmode (Literal["MATCH", "NOMATCH", "TFMATCH"], optional): HIM search mode. `"NOMATCH"` iterate over all HIM messages available. `"MATCH"` iterate over all trips to find HIM messages. `"TFMATCH"` uses filters defined `metas` parameter. Defaults to None. - * affectedJourneyMode (Literal["ALL", "OFF"], optional): Define how to return affected journeys `"OFF"`: do not return affected journeys. `"ALL"`: return affected journeys. Defaults to None. - * affectedJourneyStopMode (Literal["ALL", "IMP", "OFF"], optional): Define how to return stops of affected journeys. `"IMP"`: return important stops of affected journeys. `"OFF"`: do not return stops of affected journeys. `"ALL"`: return all affected stops of affected journeys. Defaults to None. - * orderBy (Union[str, list], optional): Define the Order the returned messages by fields and directions. Multiple, string comma separated or list entries are supported. Read more about this in HAFAS ReST Documentation. Defaults to None. - * minprio (Union[str, int], optional): Filter for HIM messages having at least this priority. Defaults to None. - * maxprio (Union[str, int], optional): Filter for HIM messages having this priority as maximum. Defaults to None. + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. + * dateB (Union[str, datetime], *optional*): Sets the event period start date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. + * dateE (Union[str, datetime], *optional*): Sets the event period end date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. + * timeB (Union[str, datetime], *optional*): Sets the event period start time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. + * timeE (Union[str, datetime], *optional*): Sets the event period end time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. + * weekdays (Union[str, OrderedDict[str, bool]], *optional*): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to None. + * himIds (Union[str, list], *optional*): List of HIM message IDs as a list or as a string separated by comma. Defaults to None. + * hierarchicalView (bool, *optional*): Return parent messages with childs. Defaults to False. + * operators (Union[str, list], *optional*): List of operators as a list or as a string separated by comma. Defaults to None. + * categories (Union[str, list], *optional*): List of train categories as a list or as a string separated by comma. Defaults to None. + * channels (Union[str, list], *optional*): List of channels as a list or as a string separated by comma. Defaults to None. + * companies (Union[str, list], *optional*): List of companies as a list or as a string separated by comma. Defaults to None. + * lines (Union[str, list], *optional*): Only HIM messages for the given line are part of the result. To filter multiple lines, separate the codes by comma. Defaults to None. + * lineids (Union[str, list], *optional*): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, separate the line IDs by comma. Defaults to None. + * stations (Union[str, list], *optional*): List of (external) station ids to be filtered for as a list or as a string separated by comma. Defaults to None. + * fromstation (str, *optional*): Filter messages by line segment starting at this station given as (external) station id. Defaults to None. + * tostation (str, *optional*): Filter messages by line segment travelling in direction of this station given as (external) station id. Defaults to None. + * bothways (bool, *optional*): If enabled, messages in both directions - from 'fromstation' to 'tostation' as well as from 'tostation' to 'fromstation' are returned. Defaults to None. + * trainnames (Union[str, list], *optional*): List of train name to be filtered for as a list or as a string separated by comma. Defaults to None. + * metas (Union[str, list], *optional*): List of predefined filters as a list or as a string separated by comma. Defaults to None. + * himcategory (str, *optional*): HIM category, e.g. Works and/or Disturbance. Value depends on your HAFAS server data. Defaults to None. + * himtags (Union[str, list], *optional*): HIM Tags. Value depends on your HAFAS server data. Return HIM messages having these tag(s) only. Multiple values are separated by comma. Note: HIM tags differ from HIM text tags. Defaults to None. + * regions (Union[str, list], *optional*): Filter for HIM messages based on regions defined in HAFAS raw data. As a list or as a string separated by comma. Available regions can be retrieved by /datainfo service. Defaults to None. + * himtext (Union[str, list], *optional*): Filter for HIM messages containing the given free text message as a list or as a string separated by comma. Defaults to None. + * himtexttags (Union[str, list], *optional*): Return HIM texts having this text tag(s) only. Multiple values are separated by comma. Note: HIM text tags differ from HIM tags. Defaults to None. + * additionalfields (Union[str, list, dict], *optional*): List of additional fields and values to be filtered for. Two filter options are available: Filter by key only: `additionalfields=key` or filter by key and value: `additionalfields={key:value}`. Multiple filters are separated by comma like `additionalfields=[keyA,keyB]` or `additionalfields={key:value}`. Defaults to None. + * poly (bool, *optional*): Enables/disables returning of geo information for affected edges and regions if available and enabled in the backend. Defaults to False. + * searchmode (Literal["MATCH", "NOMATCH", "TFMATCH"], *optional*): HIM search mode. `"NOMATCH"` iterate over all HIM messages available. `"MATCH"` iterate over all trips to find HIM messages. `"TFMATCH"` uses filters defined `metas` parameter. Defaults to None. + * affectedJourneyMode (Literal["ALL", "OFF"], *optional*): Define how to return affected journeys `"OFF"`: do not return affected journeys. `"ALL"`: return affected journeys. Defaults to None. + * affectedJourneyStopMode (Literal["ALL", "IMP", "OFF"], *optional*): Define how to return stops of affected journeys. `"IMP"`: return important stops of affected journeys. `"OFF"`: do not return stops of affected journeys. `"ALL"`: return all affected stops of affected journeys. Defaults to None. + * orderBy (Union[str, list], *optional*): Define the Order the returned messages by fields and directions. Multiple, string comma separated or list entries are supported. Read more about this in HAFAS ReST Documentation. Defaults to None. + * minprio (Union[str, int], *optional*): Filter for HIM messages having at least this priority. Defaults to None. + * maxprio (Union[str, int], *optional*): Filter for HIM messages having this priority as maximum. Defaults to None. ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/src/pyrmv/raw/journey_detail.py b/src/pyrmv/raw/journey_detail.py index 6aa9be8..81235c2 100644 --- a/src/pyrmv/raw/journey_detail.py +++ b/src/pyrmv/raw/journey_detail.py @@ -36,17 +36,17 @@ def journey_detail( ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * id (str): Specifies the internal journey id of the journey shall be retrieved. Maximum length 512. - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. - * date (Union[str, datetime], optional): Day of operation. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. - * poly (bool, optional): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. - * polyEnc (Literal["DLT", "GPA", "N"], optional): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". - * showPassingPoints (bool, optional): Enables/disables the return of stops having no alighting and no boarding in its passlist for each leg of the trip. Defaults to False. - * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], optional): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. - * fromId (str, optional): Specifies the station/stop ID the partial itinerary shall start from. Defaults to None. - * fromIdx (str, optional): Specifies the station/stop index the partial itinerary shall start from. Defaults to None. - * toId (str, optional): Specifies the station/stop ID the partial itinerary shall end at. Defaults to None. - * toIdx (str, optional): Specifies the station/stop index the partial itinerary shall end at. Defaults to None. - * baim (bool, optional): Enables/disables BAIM search and response. Defaults to False. + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. + * date (Union[str, datetime], *optional*): Day of operation. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. + * poly (bool, *optional*): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. + * polyEnc (Literal["DLT", "GPA", "N"], *optional*): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". + * showPassingPoints (bool, *optional*): Enables/disables the return of stops having no alighting and no boarding in its passlist for each leg of the trip. Defaults to False. + * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], *optional*): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. + * fromId (str, *optional*): Specifies the station/stop ID the partial itinerary shall start from. Defaults to None. + * fromIdx (str, *optional*): Specifies the station/stop index the partial itinerary shall start from. Defaults to None. + * toId (str, *optional*): Specifies the station/stop ID the partial itinerary shall end at. Defaults to None. + * toIdx (str, *optional*): Specifies the station/stop index the partial itinerary shall end at. Defaults to None. + * baim (bool, *optional*): Enables/disables BAIM search and response. Defaults to False. ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/src/pyrmv/raw/stop_by_coords.py b/src/pyrmv/raw/stop_by_coords.py index 1122d08..b8c7f05 100644 --- a/src/pyrmv/raw/stop_by_coords.py +++ b/src/pyrmv/raw/stop_by_coords.py @@ -36,16 +36,16 @@ def stop_by_coords( * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * originCoordLat (Union[str, float]): Latitude of centre coordinate. * originCoordLong (Union[str, float]): Longitude of centre coordinate. - * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], optional): The language of response. Defaults to "en". - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. - * radius (Union[int, float], optional): Search radius in meter around the given coordinate if any. Defaults to 1000. - * maxNo (int, optional): Maximum number of returned stops. Defaults to 10. - * stopType (Literal["S", "P", "SP", "SE", "SPE"], optional): Type filter for location types. Defaults to "S". - * locationSelectionMode (Literal["SLCT_N", "SLCT_A"], optional): Selection mode for locations. Defaults to None. - * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. - * meta (str, optional): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None. - * sattributes (Union[str, list], optional): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None. - * sinfotexts (Union[str, list], optional): Filter locations by one or more station infotext codes and values. Multiple attribute codes are separated by comma the value by pipe |. Defaults to None. + * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], *optional*): The language of response. Defaults to "en". + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. + * radius (Union[int, float], *optional*): Search radius in meter around the given coordinate if any. Defaults to 1000. + * maxNo (int, *optional*): Maximum number of returned stops. Defaults to 10. + * stopType (Literal["S", "P", "SP", "SE", "SPE"], *optional*): Type filter for location types. Defaults to "S". + * locationSelectionMode (Literal["SLCT_N", "SLCT_A"], *optional*): Selection mode for locations. Defaults to None. + * products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. + * meta (str, *optional*): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None. + * sattributes (Union[str, list], *optional*): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None. + * sinfotexts (Union[str, list], *optional*): Filter locations by one or more station infotext codes and values. Multiple attribute codes are separated by comma the value by pipe |. Defaults to None. ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/src/pyrmv/raw/stop_by_name.py b/src/pyrmv/raw/stop_by_name.py index f46f4c8..5355a0b 100644 --- a/src/pyrmv/raw/stop_by_name.py +++ b/src/pyrmv/raw/stop_by_name.py @@ -43,20 +43,20 @@ def stop_by_name( ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * inputString (str): Search for that token. - * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], optional): The language of response. Defaults to "en". - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. - * maxNo (int, optional): Maximum number of returned stops. In range 1-1000. Defaults to 10. - * stopType (Literal["A", "ALL", "AP", "P", "S", "SA", "SP"], optional): Type filter for location types. Defaults to "ALL". - * locationSelectionMode (str, optional): Selection mode for locations. "SLCT_N": Not selectable, "SLCT_A": Selectable. Defaults to None. - * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. - * coordLat (Union[str, float], optional): Latitude of centre coordinate. Defaults to None. - * coordLong (Union[str, float], optional): Longitude of centre coordinate. Defaults to None. - * radius (Union[int, float], optional): Search radius in meter around the given coordinate if any. Defaults to 1000. - * refineId (str, optional): In case of an refinable location, this value takes the ID of the refinable one of a previous result. Defaults to None. - * meta (str, optional): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None. - * stations (Union[str, list], optional): Filter for stations. Matches if the given value is prefix of any station in the itinerary. Multiple values are separated by comma. Defaults to None. - * sattributes (Union[str, list], optional): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None. - * filterMode (Literal["DIST_PERI", "EXCL_PERI", "SLCT_PERI"], optional): Filter modes for nearby searches. Defaults to "DIST_PERI". + * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], *optional*): The language of response. Defaults to "en". + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. + * maxNo (int, *optional*): Maximum number of returned stops. In range 1-1000. Defaults to 10. + * stopType (Literal["A", "ALL", "AP", "P", "S", "SA", "SP"], *optional*): Type filter for location types. Defaults to "ALL". + * locationSelectionMode (str, *optional*): Selection mode for locations. "SLCT_N": Not selectable, "SLCT_A": Selectable. Defaults to None. + * products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. + * coordLat (Union[str, float], *optional*): Latitude of centre coordinate. Defaults to None. + * coordLong (Union[str, float], *optional*): Longitude of centre coordinate. Defaults to None. + * radius (Union[int, float], *optional*): Search radius in meter around the given coordinate if any. Defaults to 1000. + * refineId (str, *optional*): In case of an refinable location, this value takes the ID of the refinable one of a previous result. Defaults to None. + * meta (str, *optional*): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None. + * stations (Union[str, list], *optional*): Filter for stations. Matches if the given value is prefix of any station in the itinerary. Multiple values are separated by comma. Defaults to None. + * sattributes (Union[str, list], *optional*): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None. + * filterMode (Literal["DIST_PERI", "EXCL_PERI", "SLCT_PERI"], *optional*): Filter modes for nearby searches. Defaults to "DIST_PERI". ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/src/pyrmv/raw/trip_find.py b/src/pyrmv/raw/trip_find.py index 659632f..8465074 100644 --- a/src/pyrmv/raw/trip_find.py +++ b/src/pyrmv/raw/trip_find.py @@ -109,90 +109,90 @@ def trip_find( ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). - * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], optional): The language of response. Defaults to "en". - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. - * originId (str, optional): Specifies the station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * originExtId (str, optional): Deprecated. Please use originId as it supports external IDs. Specifies the external station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * originCoordLat (Union[str, float], optional): Latitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * originCoordLong (Union[str, float], optional): Longitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * originCoordName (str, optional): Name of the trip's origin if coordinate cannot be resolved to an address or poi. Defaults to None. - * destId (str, optional): Specifies the station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * destExtId (str, optional): Deprecated. Please use destId as it supports external IDs. Specifies the external station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * destCoordLat (Union[str, float], optional): Latitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * destCoordLong (Union[str, float], optional): Longitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. - * destCoordName (str, optional): Name of the trip's destination if coordinate cannot be resolved to an address or poi. Defaults to None. - * via (str, optional): Complex structure to provide multiple via points separated by semicolon. This structure is build like this: `viaId|waittime|viastatus|products|direct|sleepingCar|couchetteCoach|attributes`. Read more about this in HAFAS ReST Documentation. Defaults to None. - * viaId (str, optional): ID of a station/stop used as a via for the trip. Specifying a via station forces the trip search to look for trips which must pass through this station. Such ID can be retrieved from stopByName() or stopByCoords(). If `via` is used, `viaId` and `viaWaitTime ` are having no effect. Defaults to None. - * viaWaitTime (int, optional): Defines the waiting time spent at via station in minutes. If `via` is used, `viaId` and `viaWaitTime` are having no effect. Defaults to 0. - * avoid (str, optional): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), optional but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to None. - * avoidId (str, optional): ID of a station/stop to be avoided as transfer stop for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). If `avoid` is used, `avoidId` has no effect. Defaults to None. - * viaGis (str, optional): Complex structure to provide multiple GIS via locations separated by semicolon. This structure is build like this: `locationId|locationMode|transportMode|placeType|usageType|mode|durationOfStay`. Read more about this in HAFAS ReST Documentation. Defaults to None. - * changeTimePercent (int, optional): Configures the walking speed when changing from one leg of the journey to the next one. It extends the time required for changes by a specified percentage. A value of 200 doubles the change time as initially calculated by the system. In the response, change time is presented in full minutes. If the calculation based on changeTime-Percent does not result in a full minute, it is rounded using "round half up" method. Defaults to 100. - * minChangeTime (int, optional): Minimum change time at stop in minutes. Defaults to None. - * maxChangeTime (int, optional): Maximum change time at stop in minutes. Defaults to None. - * addChangeTime (int, optional): This amount of minutes is added to the change time at each stop. Defaults to None. - * maxChange (int, optional): Maximum number of changes. In range 0-11. Defaults to None. - * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. - * time (Union[str, datetime], optional): Sets the start time for which the departures shall be retrieved. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. - * searchForArrival (bool, optional): If set, the date and time parameters specify the arrival time for the trip search instead of the departure time. Defaults to False. - * numF (int, optional): Minimum number of trips after the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 1-6. Defaults to None. - * numB (int, optional): Minimum number of trips before the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 0-6. Defaults to None. - * context (str, optional): Defines the starting point for the scroll back or forth operation. Use the scrB value from a previous result to scroll backwards in time and use the scrF value to scroll forth. Defaults to None. - * poly (bool, optional): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. - * polyEnc (Literal["DLT", "GPA", "N"], optional): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". - * passlist (bool, optional): Enables/disables the return of the passlist for each leg of the trip. Defaults to False. - * products (str, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. - * operators (Union[str, list], optional): Only trips provided by the given operators are part of the result. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=["A","B"]`. Defaults to None. - * attributes (Union[str, list], optional): Filter trips by one or more attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. - * sattributes (Union[str, list], optional): Filter trips by one or more station attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. - * fattributes (Union[str, list], optional): Filter trips by one or more footway attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. - * lines (Union[str, list], optional): Only journeys running the given line are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. - * lineids (Union[str, list], optional): Only journeys running the given line (identified by its line ID) are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. - * avoidPaths (List[Literal["SW", "EA", "ES", "RA", "CB"]], optional): Only path not having the given properties will be part of the result. "SW": Stairway; "EA": Elevator; "ES": Escalator; "RA": Ramp; "CB": Convey Belt. Example: Use paths without ramp and stairway: `avoidPaths="SW", "RA"`. Defaults to None. - * originWalk (Union[str, list], optional): Enables/disables using footpaths in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * originBike (Union[str, list], optional): Enables/disables using bike routes in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station or mode change point, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * originCar (Union[str, list], optional): Enables/disables using car in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * originTaxi (Union[str, list], optional): Enables/disables using taxi rides in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * originPark (Union[str, list], optional): Enables/disables using Park and Ride in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * originMeta (Union[str, list], optional): Enables using one or more predefined individual transport meta profile at the beginning of a trip. Defaults to None. - * destWalk (Union[str, list], optional): Enables/disables using footpaths at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * destBike (Union[str, list], optional): Enables/disables using bike routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * destCar (Union[str, list], optional): Enables/disables using car routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * destTaxi (Union[str, list], optional): Enables/disables using taxi rides at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * destPark (Union[str, list], optional): Enables/disables using Park and Ride at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * destMeta (Union[str, list], optional): Enables using one or more predefined individual transport meta profile at the end of a trip. Defaults to None. - * totalWalk (Union[str, list], optional): Enables/disables using footpaths for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * totalBike (Union[str, list], optional): Enables/disables using bike routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * totalCar (Union[str, list], optional): Enables/disables using car routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * totalTaxi (Union[str, list], optional): Enables/disables using taxi rides for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. - * totalMeta (Union[str, list], optional): Enables using one or more predefined individual transport meta profile for a trip. Defaults to None. - * gisProducts (str, optional): Filter on GIS product, e.g. specific sharing provider. Currently, only exclusion of certain providers is available by adding ! in front of the provider meta code. Defaults to None. - * includeIv (bool, optional): Enables/disables search for individual transport routes. Defaults to False. - * ivOnly (bool, optional): Enables/disables search for individual transport routes only. Defaults to False. - * mobilityProfile (str, optional): Use a predefined filter by its name. The filters are defined in the HAFAS installation. If the filter should be negated, put a ! in front of its name. Defaults to None. - * bikeCarriage (bool, optional): Enables/disables search for trips explicit allowing bike carriage. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. - * bikeCarriageType (Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"], optional): Filter for a specific bike carriage type. Defaults to None. - * sleepingCar (bool, optional): Enables/disables search for trips having sleeping car. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. - * couchetteCoach (bool, optional): Enables/disables search for trips having couchette coach. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. - * showPassingPoints (bool, optional): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist enabled. Defaults to False. - * baim (bool, optional): Enables/disables BAIM search and response. Defaults to False. - * eco (bool, optional): Enables/disables eco value calculation. Defaults to False. - * ecoCmp (bool, optional): Enables/disables eco comparison. Defaults to False. - * ecoParams (str, optional): Provide additional eco parameters. Defaults to None. - * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], optional): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. - * unsharp (bool, optional): Enables/disables unsharp search mode. Read more about this in section 2.12.2.1. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False. - * trainFilter (str, optional): Filters a trip search for a certain train. First hit will be taken. Defaults to None. - * economic (bool, optional): Enables/disables economic search mode. Read more about this in section 2.12.2.2. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False. - * groupFilter (str, optional): Use a predefined group filter to query for certain modes. Defaults to None. - * blockingList (str, optional): Defines a section of a route of a journey not to be used within the trip search. Each route section is defined by a tuple of the following style: `||||||` A set of tuples can be separated by semicolon. Defaults to None. - * blockedEdges (str, optional): List of edges within the public transport network that should be excluded from the result. Each edge is defined by a tuple of the following style: `start location ID|end locationID|bidirectional|blockOnlyIfInOutAllowed` A set of tuples can be separated by semicolon. Defaults to None. - * trainComposition (bool, optional): Enables/disables train composition data. Defaults to False. - * includeEarlier (bool, optional): Disables search optimization in relation of duration. Defaults to False. - * withICTAlternatives (bool, optional): Enables/disables the search for alternatives with individualized change times (ICT). Defaults to False. - * tariff (bool, optional): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None. - * trafficMessages (bool, optional): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to False. - * travellerProfileData (str, optional): Traveller profile data. Structure depends on set up. Defaults to None. - * withFreq (bool, optional): Enables/disables the calculation of frequency information. Defaults to True. + * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], *optional*): The language of response. Defaults to "en". + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. + * originId (str, *optional*): Specifies the station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * originExtId (str, *optional*): Deprecated. Please use originId as it supports external IDs. Specifies the external station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * originCoordLat (Union[str, float], *optional*): Latitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * originCoordLong (Union[str, float], *optional*): Longitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * originCoordName (str, *optional*): Name of the trip's origin if coordinate cannot be resolved to an address or poi. Defaults to None. + * destId (str, *optional*): Specifies the station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * destExtId (str, *optional*): Deprecated. Please use destId as it supports external IDs. Specifies the external station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * destCoordLat (Union[str, float], *optional*): Latitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * destCoordLong (Union[str, float], *optional*): Longitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. + * destCoordName (str, *optional*): Name of the trip's destination if coordinate cannot be resolved to an address or poi. Defaults to None. + * via (str, *optional*): Complex structure to provide multiple via points separated by semicolon. This structure is build like this: `viaId|waittime|viastatus|products|direct|sleepingCar|couchetteCoach|attributes`. Read more about this in HAFAS ReST Documentation. Defaults to None. + * viaId (str, *optional*): ID of a station/stop used as a via for the trip. Specifying a via station forces the trip search to look for trips which must pass through this station. Such ID can be retrieved from stopByName() or stopByCoords(). If `via` is used, `viaId` and `viaWaitTime ` are having no effect. Defaults to None. + * viaWaitTime (int, *optional*): Defines the waiting time spent at via station in minutes. If `via` is used, `viaId` and `viaWaitTime` are having no effect. Defaults to 0. + * avoid (str, *optional*): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), *optional* but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to None. + * avoidId (str, *optional*): ID of a station/stop to be avoided as transfer stop for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). If `avoid` is used, `avoidId` has no effect. Defaults to None. + * viaGis (str, *optional*): Complex structure to provide multiple GIS via locations separated by semicolon. This structure is build like this: `locationId|locationMode|transportMode|placeType|usageType|mode|durationOfStay`. Read more about this in HAFAS ReST Documentation. Defaults to None. + * changeTimePercent (int, *optional*): Configures the walking speed when changing from one leg of the journey to the next one. It extends the time required for changes by a specified percentage. A value of 200 doubles the change time as initially calculated by the system. In the response, change time is presented in full minutes. If the calculation based on changeTime-Percent does not result in a full minute, it is rounded using "round half up" method. Defaults to 100. + * minChangeTime (int, *optional*): Minimum change time at stop in minutes. Defaults to None. + * maxChangeTime (int, *optional*): Maximum change time at stop in minutes. Defaults to None. + * addChangeTime (int, *optional*): This amount of minutes is added to the change time at each stop. Defaults to None. + * maxChange (int, *optional*): Maximum number of changes. In range 0-11. Defaults to None. + * date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. + * time (Union[str, datetime], *optional*): Sets the start time for which the departures shall be retrieved. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. + * searchForArrival (bool, *optional*): If set, the date and time parameters specify the arrival time for the trip search instead of the departure time. Defaults to False. + * numF (int, *optional*): Minimum number of trips after the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 1-6. Defaults to None. + * numB (int, *optional*): Minimum number of trips before the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 0-6. Defaults to None. + * context (str, *optional*): Defines the starting point for the scroll back or forth operation. Use the scrB value from a previous result to scroll backwards in time and use the scrF value to scroll forth. Defaults to None. + * poly (bool, *optional*): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. + * polyEnc (Literal["DLT", "GPA", "N"], *optional*): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". + * passlist (bool, *optional*): Enables/disables the return of the passlist for each leg of the trip. Defaults to False. + * products (str, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. + * operators (Union[str, list], *optional*): Only trips provided by the given operators are part of the result. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=["A","B"]`. Defaults to None. + * attributes (Union[str, list], *optional*): Filter trips by one or more attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. + * sattributes (Union[str, list], *optional*): Filter trips by one or more station attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. + * fattributes (Union[str, list], *optional*): Filter trips by one or more footway attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. + * lines (Union[str, list], *optional*): Only journeys running the given line are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. + * lineids (Union[str, list], *optional*): Only journeys running the given line (identified by its line ID) are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. + * avoidPaths (List[Literal["SW", "EA", "ES", "RA", "CB"]], *optional*): Only path not having the given properties will be part of the result. "SW": Stairway; "EA": Elevator; "ES": Escalator; "RA": Ramp; "CB": Convey Belt. Example: Use paths without ramp and stairway: `avoidPaths="SW", "RA"`. Defaults to None. + * originWalk (Union[str, list], *optional*): Enables/disables using footpaths in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * originBike (Union[str, list], *optional*): Enables/disables using bike routes in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station or mode change point, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * originCar (Union[str, list], *optional*): Enables/disables using car in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * originTaxi (Union[str, list], *optional*): Enables/disables using taxi rides in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * originPark (Union[str, list], *optional*): Enables/disables using Park and Ride in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * originMeta (Union[str, list], *optional*): Enables using one or more predefined individual transport meta profile at the beginning of a trip. Defaults to None. + * destWalk (Union[str, list], *optional*): Enables/disables using footpaths at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * destBike (Union[str, list], *optional*): Enables/disables using bike routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * destCar (Union[str, list], *optional*): Enables/disables using car routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * destTaxi (Union[str, list], *optional*): Enables/disables using taxi rides at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * destPark (Union[str, list], *optional*): Enables/disables using Park and Ride at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * destMeta (Union[str, list], *optional*): Enables using one or more predefined individual transport meta profile at the end of a trip. Defaults to None. + * totalWalk (Union[str, list], *optional*): Enables/disables using footpaths for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * totalBike (Union[str, list], *optional*): Enables/disables using bike routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * totalCar (Union[str, list], *optional*): Enables/disables using car routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * totalTaxi (Union[str, list], *optional*): Enables/disables using taxi rides for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. + * totalMeta (Union[str, list], *optional*): Enables using one or more predefined individual transport meta profile for a trip. Defaults to None. + * gisProducts (str, *optional*): Filter on GIS product, e.g. specific sharing provider. Currently, only exclusion of certain providers is available by adding ! in front of the provider meta code. Defaults to None. + * includeIv (bool, *optional*): Enables/disables search for individual transport routes. Defaults to False. + * ivOnly (bool, *optional*): Enables/disables search for individual transport routes only. Defaults to False. + * mobilityProfile (str, *optional*): Use a predefined filter by its name. The filters are defined in the HAFAS installation. If the filter should be negated, put a ! in front of its name. Defaults to None. + * bikeCarriage (bool, *optional*): Enables/disables search for trips explicit allowing bike carriage. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. + * bikeCarriageType (Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"], *optional*): Filter for a specific bike carriage type. Defaults to None. + * sleepingCar (bool, *optional*): Enables/disables search for trips having sleeping car. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. + * couchetteCoach (bool, *optional*): Enables/disables search for trips having couchette coach. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. + * showPassingPoints (bool, *optional*): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist enabled. Defaults to False. + * baim (bool, *optional*): Enables/disables BAIM search and response. Defaults to False. + * eco (bool, *optional*): Enables/disables eco value calculation. Defaults to False. + * ecoCmp (bool, *optional*): Enables/disables eco comparison. Defaults to False. + * ecoParams (str, *optional*): Provide additional eco parameters. Defaults to None. + * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], *optional*): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. + * unsharp (bool, *optional*): Enables/disables unsharp search mode. Read more about this in section 2.12.2.1. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False. + * trainFilter (str, *optional*): Filters a trip search for a certain train. First hit will be taken. Defaults to None. + * economic (bool, *optional*): Enables/disables economic search mode. Read more about this in section 2.12.2.2. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False. + * groupFilter (str, *optional*): Use a predefined group filter to query for certain modes. Defaults to None. + * blockingList (str, *optional*): Defines a section of a route of a journey not to be used within the trip search. Each route section is defined by a tuple of the following style: `||||||` A set of tuples can be separated by semicolon. Defaults to None. + * blockedEdges (str, *optional*): List of edges within the public transport network that should be excluded from the result. Each edge is defined by a tuple of the following style: `start location ID|end locationID|bidirectional|blockOnlyIfInOutAllowed` A set of tuples can be separated by semicolon. Defaults to None. + * trainComposition (bool, *optional*): Enables/disables train composition data. Defaults to False. + * includeEarlier (bool, *optional*): Disables search optimization in relation of duration. Defaults to False. + * withICTAlternatives (bool, *optional*): Enables/disables the search for alternatives with individualized change times (ICT). Defaults to False. + * tariff (bool, *optional*): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None. + * trafficMessages (bool, *optional*): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to False. + * travellerProfileData (str, *optional*): Traveller profile data. Structure depends on set up. Defaults to None. + * withFreq (bool, *optional*): Enables/disables the calculation of frequency information. Defaults to True. ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/src/pyrmv/raw/trip_recon.py b/src/pyrmv/raw/trip_recon.py index d0ac727..e916e1e 100644 --- a/src/pyrmv/raw/trip_recon.py +++ b/src/pyrmv/raw/trip_recon.py @@ -51,34 +51,34 @@ def trip_recon( ### Args: * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * ctx (str): Specifies the reconstruction context. - * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. - * poly (bool, optional): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. - * polyEnc (Literal["DLT", "GPA", "N"], optional): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". - * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. This parameter will force the ser-vice to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, the error code SVC_NO_RESULT will be returned. Defaults to None. - * useCombinedComparison (bool, optional): Compare based on combined output name - `False`: Compare parameters (category, line, train number) individually. Defaults to None. - * acceptGaps (bool, optional): Accept an incomplete description of the connection (with gaps) i.e. missing walks/transfers. Defaults to None. - * allowDummySections (bool, optional): Allow a partial reconstruction that will not lead to a reconstruction failure if sections are not reconstructable. Instead, for theses inconstructable sections, dummy sections will be created in the result. Defaults to None. - * flagAllNonReachable (bool, optional): Should all non-reachable journeys be flagged (`True`), or only the first one encountered? Defaults to None. - * matchCatStrict (bool, optional): Should the category (Gattung) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None. - * matchIdNonBlank (bool, optional): Should the train identifier (Zugbezeichner) without whitespace match? Defaults to None. - * matchIdStrict (bool, optional): Should the train identifier (Zugbezeichner) match exactly? Defaults to None. - * matchNumStrict (bool, optional): Should the train number (Zugnummer) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None. - * matchRtType (bool, optional): Should the realtime type that journeys are based on (e.g. SOLL, IST, additional, deviation, …) be considered? Defaults to None. - * enableRtFullSearch (bool, optional): By default, the reconstruction request makes one attempt for each journey within the scheduled data. However, the scheduled data may not necessarily reflect basic realtime properties of the journeys therein. In such a case, one may enable a two-step approach which we call "full search", i.e. search for matching journeys in the scheduled data in a first step. If this fails, then search for matching journeys in the realtime data. Defaults to None. - * enableReplacements (bool, optional): If set to true replaces cancelled journeys with their replacement journeys if possible. Defaults to None. - * arrL (int, optional): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original arrival". Defaults to None. - * arrU (int, optional): Upper deviation in minutes within interval [0, 720] indicating "how much later than original arrival". Defaults to None. - * depL (int, optional): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original departure". Defaults to None. - * depU (int, optional): Upper deviation in minutes within interval [0, 720] indicating "how much later than original departure". Defaults to None. - * passlist (bool, optional): Enables/disables the return of the passlist for each leg of the trip. Defaults to False. - * showPassingPoints (bool, optional): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist parameter enabled. Defaults to False. - * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], optional): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. - * eco (bool, optional): Enables/disables eco value calculation. Defaults to False. - * ecoCmp (bool, optional): Enables/disables eco comparison. Defaults to False. - * ecoParams (str, optional): Provide additional eco parameters. Values vary. Defaults to None. - * tariff (bool, optional): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None. - * trafficMessages (bool, optional): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to None. - * travellerProfileData (str, optional): Traveller profile data. Structure depends on set up. Defaults to None. + * json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. + * poly (bool, *optional*): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. + * polyEnc (Literal["DLT", "GPA", "N"], *optional*): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". + * date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. This parameter will force the ser-vice to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, the error code SVC_NO_RESULT will be returned. Defaults to None. + * useCombinedComparison (bool, *optional*): Compare based on combined output name - `False`: Compare parameters (category, line, train number) individually. Defaults to None. + * acceptGaps (bool, *optional*): Accept an incomplete description of the connection (with gaps) i.e. missing walks/transfers. Defaults to None. + * allowDummySections (bool, *optional*): Allow a partial reconstruction that will not lead to a reconstruction failure if sections are not reconstructable. Instead, for theses inconstructable sections, dummy sections will be created in the result. Defaults to None. + * flagAllNonReachable (bool, *optional*): Should all non-reachable journeys be flagged (`True`), or only the first one encountered? Defaults to None. + * matchCatStrict (bool, *optional*): Should the category (Gattung) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None. + * matchIdNonBlank (bool, *optional*): Should the train identifier (Zugbezeichner) without whitespace match? Defaults to None. + * matchIdStrict (bool, *optional*): Should the train identifier (Zugbezeichner) match exactly? Defaults to None. + * matchNumStrict (bool, *optional*): Should the train number (Zugnummer) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None. + * matchRtType (bool, *optional*): Should the realtime type that journeys are based on (e.g. SOLL, IST, additional, deviation, …) be considered? Defaults to None. + * enableRtFullSearch (bool, *optional*): By default, the reconstruction request makes one attempt for each journey within the scheduled data. However, the scheduled data may not necessarily reflect basic realtime properties of the journeys therein. In such a case, one may enable a two-step approach which we call "full search", i.e. search for matching journeys in the scheduled data in a first step. If this fails, then search for matching journeys in the realtime data. Defaults to None. + * enableReplacements (bool, *optional*): If set to true replaces cancelled journeys with their replacement journeys if possible. Defaults to None. + * arrL (int, *optional*): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original arrival". Defaults to None. + * arrU (int, *optional*): Upper deviation in minutes within interval [0, 720] indicating "how much later than original arrival". Defaults to None. + * depL (int, *optional*): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original departure". Defaults to None. + * depU (int, *optional*): Upper deviation in minutes within interval [0, 720] indicating "how much later than original departure". Defaults to None. + * passlist (bool, *optional*): Enables/disables the return of the passlist for each leg of the trip. Defaults to False. + * showPassingPoints (bool, *optional*): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist parameter enabled. Defaults to False. + * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], *optional*): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. + * eco (bool, *optional*): Enables/disables eco value calculation. Defaults to False. + * ecoCmp (bool, *optional*): Enables/disables eco comparison. Defaults to False. + * ecoParams (str, *optional*): Provide additional eco parameters. Values vary. Defaults to None. + * tariff (bool, *optional*): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None. + * trafficMessages (bool, *optional*): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to None. + * travellerProfileData (str, *optional*): Traveller profile data. Structure depends on set up. Defaults to None. ### Returns: * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. diff --git a/tests/test_client.py b/tests/test_client.py index 8577e4e..734bc4c 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -4,8 +4,7 @@ from typing import List import pytest from pyrmv import Client, enums -from pyrmv.classes import Journey, Message, Stop, Trip -from pyrmv.classes.board import BoardArrival, BoardDeparture +from pyrmv.classes import BoardArrival, BoardDeparture, Journey, Message, Stop, Trip def test_board_arrival(api_client: Client, sample_stop_id: str): @@ -22,12 +21,12 @@ def test_board_departure(api_client: Client, sample_stop_id: str): def test_him_search(api_client: Client): assert isinstance( - api_client.him_search(date_end=datetime.now() + timedelta(days=10))[0], Message + api_client.him_search(time_end=datetime.now() + timedelta(days=10))[0], Message ) def test_journey_detail(api_client: Client, sample_journey_id: str): - assert ( + assert isinstance( api_client.journey_detail( sample_journey_id, real_time_mode=enums.RealTimeMode.FULL, -- 2.39.2 From 66cb6766390f13784a878c115d5be4443dd8e532 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 27 Nov 2023 21:56:57 +0100 Subject: [PATCH 17/66] Added pyrmv[speed] with ujson as a speedup --- pyproject.toml | 1 + requirements/speed.txt | 1 + src/pyrmv/raw/__init__.py | 9 +++++++++ tox.ini | 1 + 4 files changed, 12 insertions(+) create mode 100644 requirements/speed.txt diff --git a/pyproject.toml b/pyproject.toml index 499db6e..a17c384 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,7 @@ dependencies = { file = "requirements/_.txt" } [tool.setuptools.dynamic.optional-dependencies] dev = { file = "requirements/dev.txt" } +speed = { file = "requirements/speed.txt" } [tool.setuptools.packages.find] where = ["src"] diff --git a/requirements/speed.txt b/requirements/speed.txt new file mode 100644 index 0000000..37c6a01 --- /dev/null +++ b/requirements/speed.txt @@ -0,0 +1 @@ +ujson~=5.8.0 \ No newline at end of file diff --git a/src/pyrmv/raw/__init__.py b/src/pyrmv/raw/__init__.py index 3c8c095..77fd736 100644 --- a/src/pyrmv/raw/__init__.py +++ b/src/pyrmv/raw/__init__.py @@ -1,3 +1,7 @@ +import contextlib + +import requests + from .board_arrival import board_arrival from .board_departure import board_departure from .him_search import him_search @@ -6,3 +10,8 @@ from .stop_by_coords import stop_by_coords from .stop_by_name import stop_by_name from .trip_find import trip_find from .trip_recon import trip_recon + +with contextlib.suppress(ImportError): + import ujson + + requests.models.complexjson = ujson diff --git a/tox.ini b/tox.ini index e4c6404..b3d08ff 100644 --- a/tox.ini +++ b/tox.ini @@ -18,6 +18,7 @@ passenv = deps = -r{toxinidir}/requirements/_.txt -r{toxinidir}/requirements/dev.txt + -r{toxinidir}/requirements/speed.txt commands = pytest --basetemp={envtmpdir} --cov=pyrmv --cov-report term-missing -- 2.39.2 From 303a534d38f16abc595a76ff5c28c2fa7d20e784 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 27 Nov 2023 21:57:48 +0100 Subject: [PATCH 18/66] Upgrade to version to 0.4.0-rc.2 --- src/pyrmv/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pyrmv/__init__.py b/src/pyrmv/__init__.py index 87e7955..7b86d89 100644 --- a/src/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -21,7 +21,7 @@ trip = client.trip_find(origin_id=origin.id, dest_id=destination.id) """ __name__ = "pyrmv" -__version__ = "0.4.0-rc.1" +__version__ = "0.4.0-rc.2" __license__ = "MIT License" __author__ = "Profitroll" -- 2.39.2 From f9540d61d695235624b1055395076b0eba96ac5b Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 14:27:59 +0200 Subject: [PATCH 19/66] Update dependency pytest to v7.4.4 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 4e999c4..4884ead 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -5,7 +5,7 @@ mypy==1.7.0 pylint==3.0.2 pytest-asyncio==0.22.0 pytest-cov==4.1.0 -pytest==7.4.3 +pytest==7.4.4 tox==4.11.3 twine==4.0.2 types-aiofiles==23.2.0.0 -- 2.39.2 From 0d95d85a8a2d3225522a8e801e7fb0a1caaf8f65 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 14:28:04 +0200 Subject: [PATCH 20/66] Update dependency types-aiofiles to v23.2.0.20240311 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 4e999c4..f0d2e80 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -8,5 +8,5 @@ pytest-cov==4.1.0 pytest==7.4.3 tox==4.11.3 twine==4.0.2 -types-aiofiles==23.2.0.0 +types-aiofiles==23.2.0.20240311 types-ujson==5.8.0.1 -- 2.39.2 From 2717835ed8aa739182cd7dfa7e80a588a5a9007f Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 15:30:27 +0200 Subject: [PATCH 21/66] Update dependency build to v1.1.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 327699b..d4f216d 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,5 +1,5 @@ black==23.11.0 -build==1.0.3 +build==1.1.1 isort==5.12.0 mypy==1.7.0 pylint==3.0.2 -- 2.39.2 From 3031a656977a2a423b51424acac3c6b4b5180bd6 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 16:32:57 +0200 Subject: [PATCH 22/66] Update dependency black to v23.12.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index d4f216d..daddbd0 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,4 +1,4 @@ -black==23.11.0 +black==23.12.1 build==1.1.1 isort==5.12.0 mypy==1.7.0 -- 2.39.2 From 83aac1cb1200313480030501f8edd6112d51b541 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 16:32:59 +0200 Subject: [PATCH 23/66] Update dependency isort to v5.13.2 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index d4f216d..86b6ad0 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,6 +1,6 @@ black==23.11.0 build==1.1.1 -isort==5.12.0 +isort==5.13.2 mypy==1.7.0 pylint==3.0.2 pytest-asyncio==0.22.0 -- 2.39.2 From 2dc5f9a5d8dcaf3e2fa5a8f7cb9c133cf1aab3d5 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 17:35:31 +0200 Subject: [PATCH 24/66] Update dependency pylint to v3.1.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index d4f216d..adfcf21 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black==23.11.0 build==1.1.1 isort==5.12.0 mypy==1.7.0 -pylint==3.0.2 +pylint==3.1.0 pytest-asyncio==0.22.0 pytest-cov==4.1.0 pytest==7.4.4 -- 2.39.2 From 24105715813bb79044b706d6e398565e60665ed9 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 18:38:07 +0200 Subject: [PATCH 25/66] Update dependency tox to v4.14.2 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index d4f216d..ef9bcac 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.0.2 pytest-asyncio==0.22.0 pytest-cov==4.1.0 pytest==7.4.4 -tox==4.11.3 +tox==4.14.2 twine==4.0.2 types-aiofiles==23.2.0.20240311 types-ujson==5.8.0.1 -- 2.39.2 From b08ace2ba2e9da4dbec954e297894d9019794bf0 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 26 Mar 2024 19:40:47 +0200 Subject: [PATCH 26/66] Update dependency ujson to ~=5.9.0 --- requirements/speed.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/speed.txt b/requirements/speed.txt index 37c6a01..934e0b8 100644 --- a/requirements/speed.txt +++ b/requirements/speed.txt @@ -1 +1 @@ -ujson~=5.8.0 \ No newline at end of file +ujson~=5.9.0 \ No newline at end of file -- 2.39.2 From 966b80e69bcdc33c2d0a9e6b4073e055079b1a35 Mon Sep 17 00:00:00 2001 From: Profitroll Date: Wed, 27 Mar 2024 11:26:48 +0100 Subject: [PATCH 27/66] Update the dependencies --- requirements/dev.txt | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 9f5f76f..5aefff3 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,12 +1,12 @@ -black==23.12.1 +black~=24.3.0 build==1.1.1 isort==5.13.2 -mypy==1.7.0 +mypy~=1.9.0 pylint==3.1.0 -pytest-asyncio==0.22.0 -pytest-cov==4.1.0 -pytest==7.4.4 +pytest-asyncio~=0.23.6 +pytest-cov~=5.0.0 +pytest~=8.1.1 tox==4.14.2 -twine==4.0.2 -types-aiofiles==23.2.0.20240311 -types-ujson==5.8.0.1 +twine~=5.0.0 +types-aiofiles~=23.2.0.20240311 +types-ujson~=5.8.0.1 -- 2.39.2 From d998a5c8d96493c418b0c30ebfac6b507ffdb93d Mon Sep 17 00:00:00 2001 From: Renovate Date: Wed, 27 Mar 2024 12:28:12 +0200 Subject: [PATCH 28/66] Update dependency types-ujson to ~=5.9.0.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 5aefff3..6c4e11b 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -9,4 +9,4 @@ pytest~=8.1.1 tox==4.14.2 twine~=5.0.0 types-aiofiles~=23.2.0.20240311 -types-ujson~=5.8.0.1 +types-ujson~=5.9.0.0 -- 2.39.2 From 231003c3c644de848687f37d1dc5eee8b747bffb Mon Sep 17 00:00:00 2001 From: Renovate Date: Thu, 28 Mar 2024 17:33:19 +0200 Subject: [PATCH 29/66] Update dependency build to v1.2.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 6c4e11b..30ea115 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,5 +1,5 @@ black~=24.3.0 -build==1.1.1 +build==1.2.1 isort==5.13.2 mypy~=1.9.0 pylint==3.1.0 -- 2.39.2 From 5d155a54856b1a12c9fe81b20826524c145e2321 Mon Sep 17 00:00:00 2001 From: Renovate Date: Fri, 12 Apr 2024 23:30:30 +0300 Subject: [PATCH 30/66] Update dependency black to ~=24.4.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 30ea115..b397fd6 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,4 +1,4 @@ -black~=24.3.0 +black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.9.0 -- 2.39.2 From bc4613dc573a9dde8ad0ef71b9e5f4bbf1ef68ed Mon Sep 17 00:00:00 2001 From: Renovate Date: Wed, 24 Apr 2024 17:17:26 +0300 Subject: [PATCH 31/66] Update dependency mypy to ~=1.10.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index b397fd6..b4494f6 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,7 +1,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 -mypy~=1.9.0 +mypy~=1.10.0 pylint==3.1.0 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 -- 2.39.2 From e6d6fee14b59eb1177f9133e099c1196649f3159 Mon Sep 17 00:00:00 2001 From: Renovate Date: Fri, 26 Apr 2024 22:20:43 +0300 Subject: [PATCH 32/66] Update dependency tox to v4.15.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index b4494f6..8a0a860 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.1.0 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.1.1 -tox==4.14.2 +tox==4.15.0 twine~=5.0.0 types-aiofiles~=23.2.0.20240311 types-ujson~=5.9.0.0 -- 2.39.2 From a125bdb72d460f52c82ee86ab24efe21824d3dad Mon Sep 17 00:00:00 2001 From: Renovate Date: Sun, 28 Apr 2024 03:27:52 +0300 Subject: [PATCH 33/66] Update dependency pytest to ~=8.2.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 8a0a860..d36bd52 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -5,7 +5,7 @@ mypy~=1.10.0 pylint==3.1.0 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 -pytest~=8.1.1 +pytest~=8.2.0 tox==4.15.0 twine~=5.0.0 types-aiofiles~=23.2.0.20240311 -- 2.39.2 From 271f9b54d893e89dabdee6045f5cc08b4660e0d6 Mon Sep 17 00:00:00 2001 From: Renovate Date: Mon, 13 May 2024 18:08:44 +0300 Subject: [PATCH 34/66] Update dependency pylint to v3.1.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index d36bd52..19f9838 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.10.0 -pylint==3.1.0 +pylint==3.1.1 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -- 2.39.2 From ed5a81d25e2665fbd2708e33dbbb5ec9996faf4a Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 14 May 2024 05:38:38 +0300 Subject: [PATCH 35/66] Update dependency ujson to ~=5.10.0 --- requirements/speed.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/speed.txt b/requirements/speed.txt index 934e0b8..5393963 100644 --- a/requirements/speed.txt +++ b/requirements/speed.txt @@ -1 +1 @@ -ujson~=5.9.0 \ No newline at end of file +ujson~=5.10.0 \ No newline at end of file -- 2.39.2 From 72d1d7b6e6696d0460fb04819af8942075077222 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 14 May 2024 15:03:58 +0300 Subject: [PATCH 36/66] Update dependency pylint to v3.2.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 19f9838..d88354b 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.10.0 -pylint==3.1.1 +pylint==3.2.0 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -- 2.39.2 From 86e233994e45d74dc604631949c7d7c6779dd16d Mon Sep 17 00:00:00 2001 From: Renovate Date: Wed, 15 May 2024 05:42:13 +0300 Subject: [PATCH 37/66] Update dependency types-ujson to ~=5.10.0.20240515 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index d88354b..0cc2624 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -9,4 +9,4 @@ pytest~=8.2.0 tox==4.15.0 twine~=5.0.0 types-aiofiles~=23.2.0.20240311 -types-ujson~=5.9.0.0 +types-ujson~=5.10.0.20240515 -- 2.39.2 From 60b0a44454256c118c830432c8e9f5cd0ee03f94 Mon Sep 17 00:00:00 2001 From: Renovate Date: Thu, 16 May 2024 17:09:45 +0300 Subject: [PATCH 38/66] Update dependency twine to ~=5.1.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 0cc2624..0cacc81 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -7,6 +7,6 @@ pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 tox==4.15.0 -twine~=5.0.0 +twine~=5.1.0 types-aiofiles~=23.2.0.20240311 types-ujson~=5.10.0.20240515 -- 2.39.2 From 7c5a56bb0a8603503c1415897854d0210aa0b3f8 Mon Sep 17 00:00:00 2001 From: Renovate Date: Sat, 18 May 2024 20:18:37 +0300 Subject: [PATCH 39/66] Update dependency pylint to v3.2.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 0cc2624..6e4a0a4 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.10.0 -pylint==3.2.0 +pylint==3.2.1 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -- 2.39.2 From 9d49b1b0c8b5af7c5716598dcacc0068add26021 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 19 May 2024 14:18:41 +0200 Subject: [PATCH 40/66] Fixed wrong license attribute --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index a17c384..41f7f72 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ maintainers = [{ name = "Profitroll", email = "profitroll@end-play.xyz" }] description = "Small module that makes your journey with RMV REST API somehow easier." readme = "README.md" requires-python = ">=3.8" -license = { text = "GPL3" } +license = { text = "MIT" } classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", -- 2.39.2 From f5daf31f3942f0cec665dc5d31300191f5cfc3b2 Mon Sep 17 00:00:00 2001 From: Renovate Date: Mon, 20 May 2024 11:11:30 +0300 Subject: [PATCH 41/66] Update dependency pylint to v3.2.2 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 0ec9065..ba1903a 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.10.0 -pylint==3.2.1 +pylint==3.2.2 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -- 2.39.2 From cbc705ae8e00d9bb8be96cc0df41a35a834d7d9e Mon Sep 17 00:00:00 2001 From: Renovate Date: Mon, 20 May 2024 19:36:23 +0300 Subject: [PATCH 42/66] Update dependency requests to ~=2.32.0 --- requirements/_.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/_.txt b/requirements/_.txt index 38ad334..9f72bdf 100644 --- a/requirements/_.txt +++ b/requirements/_.txt @@ -1,3 +1,3 @@ -requests~=2.31.0 +requests~=2.32.0 xmltodict~=0.13.0 isodate~=0.6.1 \ No newline at end of file -- 2.39.2 From 3acf96884eb3427e6f1c5d067415b199918120f9 Mon Sep 17 00:00:00 2001 From: Renovate Date: Thu, 6 Jun 2024 04:19:04 +0300 Subject: [PATCH 43/66] Update dependency tox to v4.15.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index ba1903a..5462cb3 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.2.2 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -tox==4.15.0 +tox==4.15.1 twine~=5.1.0 types-aiofiles~=23.2.0.20240311 types-ujson~=5.10.0.20240515 -- 2.39.2 From a3ef49b9a17849a9b9d2a2394fa1fa2dd6db2e19 Mon Sep 17 00:00:00 2001 From: Renovate Date: Thu, 6 Jun 2024 18:02:45 +0300 Subject: [PATCH 44/66] Update dependency pylint to v3.2.3 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 5462cb3..d8ad630 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.10.0 -pylint==3.2.2 +pylint==3.2.3 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -- 2.39.2 From 3531486ee67443c28cc73e32aa763ad5516637e8 Mon Sep 17 00:00:00 2001 From: Renovate Date: Wed, 26 Jun 2024 06:08:23 +0300 Subject: [PATCH 45/66] Update dependency types-aiofiles to v24 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index d8ad630..e4729c3 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -8,5 +8,5 @@ pytest-cov~=5.0.0 pytest~=8.2.0 tox==4.15.1 twine~=5.1.0 -types-aiofiles~=23.2.0.20240311 +types-aiofiles~=24.1.0.20240626 types-ujson~=5.10.0.20240515 -- 2.39.2 From beda60e7a865c13540165be2c01411f121adc0a6 Mon Sep 17 00:00:00 2001 From: Renovate Date: Wed, 26 Jun 2024 11:26:50 +0300 Subject: [PATCH 46/66] Update dependency pylint to v3.2.4 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index e4729c3..f297e19 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.10.0 -pylint==3.2.3 +pylint==3.2.4 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -- 2.39.2 From ae565481bcb5145a5b65d4a50688b2c82cec05b5 Mon Sep 17 00:00:00 2001 From: Renovate Date: Fri, 28 Jun 2024 17:03:45 +0300 Subject: [PATCH 47/66] Update dependency pylint to v3.2.5 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index f297e19..e63f902 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.10.0 -pylint==3.2.4 +pylint==3.2.5 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -- 2.39.2 From 8ebc8d4e5939eb2d9861541f19784757f5b8e1da Mon Sep 17 00:00:00 2001 From: Renovate Date: Wed, 3 Jul 2024 07:05:54 +0300 Subject: [PATCH 48/66] Update dependency tox to v4.16.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index e63f902..a536517 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.2.5 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.2.0 -tox==4.15.1 +tox==4.16.0 twine~=5.1.0 types-aiofiles~=24.1.0.20240626 types-ujson~=5.10.0.20240515 -- 2.39.2 From fd9199c8ae8cbba73f102768b589d3de60e114cb Mon Sep 17 00:00:00 2001 From: Renovate Date: Fri, 19 Jul 2024 21:30:25 +0300 Subject: [PATCH 49/66] Update dependency mypy to ~=1.11.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index a536517..70262e0 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,7 +1,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 -mypy~=1.10.0 +mypy~=1.11.0 pylint==3.2.5 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 -- 2.39.2 From b87e2ea3dea2c97a0d832fe7f87b3ce74316cb5d Mon Sep 17 00:00:00 2001 From: Renovate Date: Sat, 20 Jul 2024 19:40:05 +0300 Subject: [PATCH 50/66] Update dependency pytest to ~=8.3.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 70262e0..8ec8ffd 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -5,7 +5,7 @@ mypy~=1.11.0 pylint==3.2.5 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 -pytest~=8.2.0 +pytest~=8.3.1 tox==4.16.0 twine~=5.1.0 types-aiofiles~=24.1.0.20240626 -- 2.39.2 From 82d9f703d4eeab7da2f5b90340c93ce356b86e96 Mon Sep 17 00:00:00 2001 From: Renovate Date: Sun, 21 Jul 2024 23:08:48 +0300 Subject: [PATCH 51/66] Update dependency pylint to v3.2.6 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 8ec8ffd..4be3380 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.4.0 build==1.2.1 isort==5.13.2 mypy~=1.11.0 -pylint==3.2.5 +pylint==3.2.6 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.3.1 -- 2.39.2 From 92e99fe01ab215f5030210c7fec5c0a2585bbe04 Mon Sep 17 00:00:00 2001 From: Renovate Date: Fri, 2 Aug 2024 21:37:56 +0300 Subject: [PATCH 52/66] Update dependency black to ~=24.8.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 4be3380..453d69c 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,4 +1,4 @@ -black~=24.4.0 +black~=24.8.0 build==1.2.1 isort==5.13.2 mypy~=1.11.0 -- 2.39.2 From 519e083f577c75b3f5a244ea13aca1f55f645c87 Mon Sep 17 00:00:00 2001 From: Renovate Date: Mon, 5 Aug 2024 23:47:05 +0300 Subject: [PATCH 53/66] Update dependency tox to v4.17.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 453d69c..4e900e9 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.2.6 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.3.1 -tox==4.16.0 +tox==4.17.0 twine~=5.1.0 types-aiofiles~=24.1.0.20240626 types-ujson~=5.10.0.20240515 -- 2.39.2 From cb6106d4863dfd8b806daa861767a6ac4ee986b9 Mon Sep 17 00:00:00 2001 From: Renovate Date: Wed, 7 Aug 2024 21:23:00 +0300 Subject: [PATCH 54/66] Update dependency tox to v4.17.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 4e900e9..ba7ad83 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.2.6 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.3.1 -tox==4.17.0 +tox==4.17.1 twine~=5.1.0 types-aiofiles~=24.1.0.20240626 types-ujson~=5.10.0.20240515 -- 2.39.2 From e4574fb42df28aad1bc493419c329c78e45d3172 Mon Sep 17 00:00:00 2001 From: Renovate Date: Tue, 13 Aug 2024 20:33:11 +0300 Subject: [PATCH 55/66] Update dependency tox to v4.18.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index ba7ad83..edc83b5 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.2.6 pytest-asyncio~=0.23.6 pytest-cov~=5.0.0 pytest~=8.3.1 -tox==4.17.1 +tox==4.18.0 twine~=5.1.0 types-aiofiles~=24.1.0.20240626 types-ujson~=5.10.0.20240515 -- 2.39.2 From fa2a70efbf7b76904bede2d56d5b25a057f6cc3f Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 18 Aug 2024 22:51:57 +0200 Subject: [PATCH 56/66] Added PlatformType and PlatformTypeType (for #4) --- src/pyrmv/classes/__init__.py | 1 + src/pyrmv/classes/platform_type.py | 17 +++++++++ src/pyrmv/enums/__init__.py | 1 + src/pyrmv/enums/platform_type_type.py | 51 +++++++++++++++++++++++++++ 4 files changed, 70 insertions(+) create mode 100644 src/pyrmv/classes/platform_type.py create mode 100644 src/pyrmv/enums/platform_type_type.py diff --git a/src/pyrmv/classes/__init__.py b/src/pyrmv/classes/__init__.py index c87171b..356d8ea 100644 --- a/src/pyrmv/classes/__init__.py +++ b/src/pyrmv/classes/__init__.py @@ -3,6 +3,7 @@ from .gis import Gis from .journey import Journey from .leg import Leg from .message import Channel, Message, Url +from .platform_type import PlatformType from .stop import Stop, StopTrip from .ticket import Ticket from .trip import Trip diff --git a/src/pyrmv/classes/platform_type.py b/src/pyrmv/classes/platform_type.py new file mode 100644 index 0000000..a1afe49 --- /dev/null +++ b/src/pyrmv/classes/platform_type.py @@ -0,0 +1,17 @@ +from typing import Any, Mapping, Union + +from pyrmv.enums.platform_type_type import PlatformTypeType + + +class PlatformType: + """Platform information.""" + + def __init__(self, data: Mapping[str, Any]): + self.type: PlatformTypeType = ( + PlatformTypeType.U if "type" not in data else PlatformTypeType(data.get("type")) + ) + self.text: Union[str, None] = data.get("text") + self.hidden: bool = bool(data.get("hidden")) + self.lon: float = data["lon"] + self.lat: float = data["lat"] + self.alt: int = data["alt"] diff --git a/src/pyrmv/enums/__init__.py b/src/pyrmv/enums/__init__.py index 92cffb6..d8d4b74 100644 --- a/src/pyrmv/enums/__init__.py +++ b/src/pyrmv/enums/__init__.py @@ -4,6 +4,7 @@ from .board_type import BoardArrivalType, BoardDepartureType from .filter_mode import FilterMode from .lang import Language from .location_type import LocationType +from .platform_type_type import PlatformTypeType from .product import Product from .rt_mode import RealTimeMode from .search_mode import SearchMode diff --git a/src/pyrmv/enums/platform_type_type.py b/src/pyrmv/enums/platform_type_type.py new file mode 100644 index 0000000..4658bde --- /dev/null +++ b/src/pyrmv/enums/platform_type_type.py @@ -0,0 +1,51 @@ +from enum import Enum, auto + + +class PlatformTypeType(Enum): + """Enumeration used to declare types of platform type. + + * U - Undefined + * PL - Platform/track at train station + * ST - Stop at bus or tram station + * GA - Terminal/Gate at airport + * PI - Pier if ship or ferry + * SL - Slot/parking space if bike or car + * FL - Floor in buildings or at footpath + * CI - Check-in/entrance + * CO - Check-out/exit + * X - No explicit type + * H - Hide platform information + """ + + U = auto() + "Undefined" + + PL = auto() + "Platform/track at train station" + + ST = auto() + "Stop at bus or tram station" + + GA = auto() + "Terminal/Gate at airport" + + PI = auto() + "Pier if ship or ferry" + + SL = auto() + "Slot/parking space if bike or car" + + FL = auto() + "Floor in buildings or at footpath" + + CI = auto() + "Check-in/entrance" + + CO = auto() + "Check-out/exit" + + X = auto() + "No explicit type" + + H = auto() + "Hide platform information" -- 2.39.2 From d20a463ba0b65139f3c4eab6c7b4aa8f481cd4b6 Mon Sep 17 00:00:00 2001 From: Renovate Date: Thu, 22 Aug 2024 11:53:54 +0300 Subject: [PATCH 57/66] Update dependency pytest-asyncio to ~=0.24.0 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index edc83b5..8bc7881 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -3,7 +3,7 @@ build==1.2.1 isort==5.13.2 mypy~=1.11.0 pylint==3.2.6 -pytest-asyncio~=0.23.6 +pytest-asyncio~=0.24.0 pytest-cov~=5.0.0 pytest~=8.3.1 tox==4.18.0 -- 2.39.2 From 6df5f6993b2f4bcecc3c050330ceccf3b70bb08c Mon Sep 17 00:00:00 2001 From: Renovate Date: Sat, 31 Aug 2024 18:06:11 +0300 Subject: [PATCH 58/66] Update dependency pylint to v3.2.7 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 8bc7881..aff2c24 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -2,7 +2,7 @@ black~=24.8.0 build==1.2.1 isort==5.13.2 mypy~=1.11.0 -pylint==3.2.6 +pylint==3.2.7 pytest-asyncio~=0.24.0 pytest-cov~=5.0.0 pytest~=8.3.1 -- 2.39.2 From 3284fb845216e9eacda344ea5aedc578ccc3db2f Mon Sep 17 00:00:00 2001 From: Renovate Date: Sat, 7 Sep 2024 00:00:46 +0300 Subject: [PATCH 59/66] Update dependency build to v1.2.2 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index aff2c24..15ec5e0 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,5 +1,5 @@ black~=24.8.0 -build==1.2.1 +build==1.2.2 isort==5.13.2 mypy~=1.11.0 pylint==3.2.7 -- 2.39.2 From cb5ec2df90ef09afc1ad5d89e568ef1556ae6b1d Mon Sep 17 00:00:00 2001 From: Profitroll Date: Sat, 7 Sep 2024 12:01:27 +0300 Subject: [PATCH 60/66] Changed runner's label to ubuntu-latest-de --- .gitea/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/workflows/tests.yml b/.gitea/workflows/tests.yml index 7c680f2..f8daeed 100644 --- a/.gitea/workflows/tests.yml +++ b/.gitea/workflows/tests.yml @@ -11,7 +11,7 @@ on: jobs: test: - runs-on: ubuntu-latest + runs-on: ubuntu-latest-de container: catthehacker/ubuntu:act-latest strategy: matrix: -- 2.39.2 From 11eddfab68d8995bbfdcb0cb362e586680eff701 Mon Sep 17 00:00:00 2001 From: Renovate Date: Sat, 7 Sep 2024 19:48:59 +0300 Subject: [PATCH 61/66] Update dependency tox to v4.18.1 --- requirements/dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 15ec5e0..112db2f 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -6,7 +6,7 @@ pylint==3.2.7 pytest-asyncio~=0.24.0 pytest-cov~=5.0.0 pytest~=8.3.1 -tox==4.18.0 +tox==4.18.1 twine~=5.1.0 types-aiofiles~=24.1.0.20240626 types-ujson~=5.10.0.20240515 -- 2.39.2 From 34953dd73938d5ed7ce05170a6d2ec71a527b685 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sat, 7 Sep 2024 20:21:52 +0200 Subject: [PATCH 62/66] Added Python 3.12 support --- pyproject.toml | 3 ++- tox.ini | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 41f7f72..ffaa568 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,6 +21,7 @@ classifiers = [ "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Utilities", ] @@ -44,7 +45,7 @@ speed = { file = "requirements/speed.txt" } where = ["src"] [tool.black] -target-version = ['py38', 'py39', 'py310', 'py311'] +target-version = ['py38', 'py39', 'py310', 'py311', 'py312'] line-length = 94 [tool.isort] diff --git a/tox.ini b/tox.ini index b3d08ff..e35f504 100644 --- a/tox.ini +++ b/tox.ini @@ -1,6 +1,6 @@ [tox] minversion = 3.8.0 -envlist = py38, py39, py310, py311 +envlist = py38, py39, py310, py311, py312 isolated_build = true [gh-actions] @@ -9,6 +9,7 @@ python = 3.9: py39 3.10: py310 3.11: py311 + 3.12: py312 [testenv] setenv = @@ -21,4 +22,3 @@ deps = -r{toxinidir}/requirements/speed.txt commands = pytest --basetemp={envtmpdir} --cov=pyrmv --cov-report term-missing - -- 2.39.2 From 0096581595597b9129ad236cdafc0effa08250d5 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 8 Sep 2024 00:51:21 +0200 Subject: [PATCH 63/66] Disabled unused async libraries --- requirements/dev.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements/dev.txt b/requirements/dev.txt index 15ec5e0..5418d17 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -3,10 +3,10 @@ build==1.2.2 isort==5.13.2 mypy~=1.11.0 pylint==3.2.7 -pytest-asyncio~=0.24.0 +# pytest-asyncio~=0.24.0 pytest-cov~=5.0.0 pytest~=8.3.1 tox==4.18.0 twine~=5.1.0 -types-aiofiles~=24.1.0.20240626 +# types-aiofiles~=24.1.0.20240626 types-ujson~=5.10.0.20240515 -- 2.39.2 From 34a601424bd27418f3d26a2f5b628cf20a0ef238 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 8 Sep 2024 01:27:58 +0200 Subject: [PATCH 64/66] Dependencies bumped and .gitignore updated --- .gitignore | 1 + requirements/_.txt | 2 +- requirements/dev.txt | 14 +++++++------- requirements/dist.txt | 2 ++ 4 files changed, 11 insertions(+), 8 deletions(-) create mode 100644 requirements/dist.txt diff --git a/.gitignore b/.gitignore index b34c603..1fab850 100644 --- a/.gitignore +++ b/.gitignore @@ -154,6 +154,7 @@ cython_debug/ # Custom +.mise.toml .vscode/ .venv_linux/ .venv_windows/ diff --git a/requirements/_.txt b/requirements/_.txt index 9f72bdf..317f56d 100644 --- a/requirements/_.txt +++ b/requirements/_.txt @@ -1,3 +1,3 @@ -requests~=2.32.0 +requests~=2.32.3 xmltodict~=0.13.0 isodate~=0.6.1 \ No newline at end of file diff --git a/requirements/dev.txt b/requirements/dev.txt index 5418d17..5cafd9f 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,12 +1,12 @@ black~=24.8.0 -build==1.2.2 isort==5.13.2 -mypy~=1.11.0 +mypy~=1.11.2 pylint==3.2.7 -# pytest-asyncio~=0.24.0 pytest-cov~=5.0.0 -pytest~=8.3.1 -tox==4.18.0 -twine~=5.1.0 -# types-aiofiles~=24.1.0.20240626 +pytest~=8.3.2 +tox==4.18.1 types-ujson~=5.10.0.20240515 + +# Disabled async libraries for now +# types-aiofiles~=24.1.0.20240626 +# pytest-asyncio~=0.24.0 \ No newline at end of file diff --git a/requirements/dist.txt b/requirements/dist.txt new file mode 100644 index 0000000..cf431e7 --- /dev/null +++ b/requirements/dist.txt @@ -0,0 +1,2 @@ +build==1.2.2 +twine~=5.1.1 -- 2.39.2 From cbcfc8604fd19ed94a6a84bde387284af0987f61 Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 8 Sep 2024 01:28:18 +0200 Subject: [PATCH 65/66] Changed testing method for Client.him_search() --- tests/test_client.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 734bc4c..c1471df 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -20,9 +20,12 @@ def test_board_departure(api_client: Client, sample_stop_id: str): def test_him_search(api_client: Client): - assert isinstance( - api_client.him_search(time_end=datetime.now() + timedelta(days=10))[0], Message - ) + response = api_client.him_search(time_end=datetime.now() + timedelta(days=10)) + + if len(response) != 0: + assert isinstance(response[0], Message) + else: + assert isinstance(response, list) def test_journey_detail(api_client: Client, sample_journey_id: str): -- 2.39.2 From 759e6f3703ecde736f6b2d1d7a974880dc0622fc Mon Sep 17 00:00:00 2001 From: profitroll Date: Sun, 8 Sep 2024 01:44:18 +0200 Subject: [PATCH 66/66] Updated to 0.4.0 --- pyproject.toml | 1 + src/pyrmv/__init__.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index ffaa568..ac2b3b5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ dependencies = { file = "requirements/_.txt" } [tool.setuptools.dynamic.optional-dependencies] dev = { file = "requirements/dev.txt" } +dist = { file = "requirements/dist.txt" } speed = { file = "requirements/speed.txt" } [tool.setuptools.packages.find] diff --git a/src/pyrmv/__init__.py b/src/pyrmv/__init__.py index 7b86d89..e331cda 100644 --- a/src/pyrmv/__init__.py +++ b/src/pyrmv/__init__.py @@ -21,7 +21,7 @@ trip = client.trip_find(origin_id=origin.id, dest_id=destination.id) """ __name__ = "pyrmv" -__version__ = "0.4.0-rc.2" +__version__ = "0.4.0" __license__ = "MIT License" __author__ = "Profitroll" -- 2.39.2