diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b1fa719 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,20 @@ +name: ci + +on: [push, pull_request, workflow_dispatch] +jobs: + test-and-coverage: + runs-on: ubuntu-latest + steps: + - name: checkout repo content + uses: actions/checkout@v4 + + - name: Install Python requirements + run: | + pip install --upgrade pip + pip install pytest pytest-cov + + - name: Test + run: pytest --cov + + - name: Coveralls + uses: coverallsapp/github-action@v2 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b149da0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,162 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +*.ipynb diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..eda1a89 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +wutingfeng@outlook.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CREDITS.md b/CREDITS.md new file mode 100644 index 0000000..7c08eb8 --- /dev/null +++ b/CREDITS.md @@ -0,0 +1,17 @@ +# Credits + +This application uses code from other open-source projects. The copyright statements of these open-source projects are listed below. + +## RailRouter SG + +Source: + +```markdown +Copyright © 2023 Lim Chee Aun, http://cheeaun.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7ebd231 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Wu Tingfeng + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..45d6ab6 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +
+ +

Train Arrival

+ Train + +

+ Extract train arrival information from the SMRT Train Arrival Information API. +

+ +

+ Output format: JSON string +

+ +

+ Python +

+ +

+ MIT license + Coveralls + +

+ +
+ +**Disclaimer:** This project is not sponsored, endorsed, or otherwise affiliated with SMRT Corporation. + +## Requirements + +Python 2.7 or 3 + +## Usage + +```python +get_all_station_info() +""" +'{"count": 166, "next": null, "previous": null, "results": [{"name": "Admiralty", "code": "NS10", ...' +""" + +get_all_station_names() +""" +['Admiralty', + 'Aljunied', + 'Ang Mo Kio', + 'Bakau', + ... +] +""" + +get_train_arrival_time_by_id("Paya Lebar") +""" +'{"results":[{"status":1,"platform_ID":"CPYL_A","code":"CC9,EW8","next_train_arr":"7","mrt":"Paya Lebar", ...' +""" + +get_all_train_arrival_time() +""" +'{"Admiralty": {"results": [{"status": 1, "platform_ID": "ADM_A", "code": "NS10", "next_train_arr": "6", ...' +""" +``` + +## Warning + +- This API appears not to be intended by SMRT for public use. You are solely [responsible](LICENSE) for your use of this application. + +## Credits + +- [RailRouter SG](https://github.com/cheeaun/railrouter-sg) for information on accessing the SMRT API. +- Logo modified from public domain vector at [svgrepo.com](https://www.svgrepo.com/svg/63666/singapore-metro-logo). diff --git a/images/train.svg b/images/train.svg new file mode 100644 index 0000000..6aac9f7 --- /dev/null +++ b/images/train.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..90861ac --- /dev/null +++ b/renovate.json @@ -0,0 +1,10 @@ +{ + "extends": ["config:base"], + "ignoreTests": true, + "packageRules": [ + { + "updateTypes": ["minor", "patch"], + "automerge": true + } + ] +} diff --git a/test_train_arrival.py b/test_train_arrival.py new file mode 100644 index 0000000..2f87cd7 --- /dev/null +++ b/test_train_arrival.py @@ -0,0 +1,41 @@ +import json + +from train_arrival import ( + get_all_station_names, + get_all_train_arrival_time, + get_train_arrival_time_by_id, +) + + +def _verify_arrival_time_response(d): + assert "results" in d + assert isinstance(d["results"], list) + assert d["results"] + first_result = d["results"][0] + assert isinstance(first_result, dict) + + +def test_get_all_station_names(): + assert len(get_all_station_names()) >= 166 + + +def test_get_train_arrival_time_by_id(): + test_cases = (("Raffles Place", "EW14,NS26"), ("Farrer Road", "CC20")) + for test_case in test_cases: + expected_station_name, expected_station_code = test_case[0], test_case[1] + res = get_train_arrival_time_by_id(expected_station_name) + arrival_time_response = json.loads(res) + _verify_arrival_time_response(arrival_time_response) + first_result = arrival_time_response["results"][0] + assert first_result.get("code", "") == expected_station_code + assert first_result.get("mrt", expected_station_name) + + +def test_get_all_train_arrival_time(): + res = get_all_train_arrival_time(3) + arrival_time_responses = json.loads(res) + assert len(arrival_time_responses) == 3 + for station_name, arrival_time_response in arrival_time_responses.items(): + _verify_arrival_time_response(arrival_time_response) + first_result = arrival_time_response["results"][0] + assert first_result.get("mrt", station_name) diff --git a/train_arrival.py b/train_arrival.py new file mode 100644 index 0000000..731526e --- /dev/null +++ b/train_arrival.py @@ -0,0 +1,171 @@ +import json +import logging +import sys +import time +from contextlib import closing +from typing import Any + +try: + import urllib.parse as parse + import urllib.request as request +except ImportError: + import urllib as parse + import urllib2 as request + +logger = logging.getLogger(__name__) +handler = logging.StreamHandler() +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") +handler.setFormatter(formatter) +logger.addHandler(handler) + +REFERER = "http://journey.smrt.com.sg/journey/station_info/" # Credits: https://github.com/cheeaun/railrouter-sg + + +def _is_str_or_unicode(s): + # type: (Any) -> bool + """Check if `s` is str type in both Python 2 and 3, else if it is + unicode type in Python 2. + + Args: + s (Any): Argument to be checked. + + Returns: + bool: True if `s` is str or unicode type. + """ + if isinstance(s, str): + return True + is_python3 = sys.version_info[0] == 3 + if is_python3: + return False + return type(s).__name__ == "unicode" + + +def _get(url, params=None): + # type: (str, dict[str, str] | None) -> str + """Make a GET request to `url` with optional query parameters `params`. + + Return the body as a string if it is a valid JSON string, otherwise {}. + + Args: + url (str): Target URL. + params (dict[str, str], optional): Optional query parameters. Defaults to None. + + Returns: + str: GET request body. + """ + if params: + r = request.Request(url + "?" + parse.urlencode(params)) + else: + r = request.Request(url) + r.add_header("Referer", REFERER) + + try: + with closing(request.urlopen(r, timeout=60)) as f: + status_code = f.status if hasattr(f, "status") else f.getcode() + if status_code == 200: + data = f.read().decode("utf-8") + json.loads(data) # Validate JSON string. + return data + logger.error(status_code) + return "{}" + except Exception as e: + logger.error(e) + return "{}" + + +def get_all_station_info(): + # type: () -> str + """Get all train station information from SMRT API. + + Returns: + str: Train station information as JSON string. + """ + return _get("https://connect.smrt.wwprojects.com/smrt/api/stations") + + +def get_all_station_names(): + # type: () -> list[str] + """Get all train station names from SMRT API. + + Returns: + list[str]: List of train station names in ascending alphabetical order. + """ + all_stations_info = json.loads(get_all_station_info()) # type: dict + if not isinstance(all_stations_info, dict): + all_stations_info = {} + station_names = set() + + for station_info in all_stations_info.get("results", []): + if isinstance(station_info, dict) and "name" in station_info: + station_name = station_info[ + "name" + ] # Use station name to get its arrival timings + if _is_str_or_unicode and station_name: + station_names.add(station_name) + return sorted(station_names) + + +def get_train_arrival_time_by_id(station_name): + # type: (str) -> str + """Get train arrival times for a given train station as a JSON string. + + Args: + station_name (str): Name of train station (e.g. City Hall, Eunos etc.) + + Returns: + str: Train arrival times as a JSON string. If no relevant data is available, return {"results": []}. + """ + params = {"station": station_name} + + max_attempts = 5 + + for attempt in range(max_attempts): + if attempt: + time.sleep( + 2 ** (attempt - 1) + ) # Sleep with exponential backoff for rate-limiting. + data = _get( + "https://connectv3.smrt.wwprojects.com/smrt/api/train_arrival_time_by_id", + params, + ) + d = json.loads(data) + if not d.get("results", []): + continue + mrt_name = d["results"][0].get("mrt", "") + if ( + mrt_name != station_name + ): # Ensure that the 'mrt' field matches station name. + continue + return data # Output guaranteed to be valid JSON. + return '{"results": []}' + + +def get_all_train_arrival_time(limit=None): + # type: (int | None) -> str + """Get train arrival times for all train stations as a JSON string. + + Warning: Estimated execution time is at least 5 minutes. + + Args: + limit (int | None, optional): Limit search results to + first N station names in ascending alphabetical order. + Has no effect if `limit` is not a positive integer or is + larger than total number of station names. Defaults to None. + + Returns: + str: Train arrival times for all train stations in + ascending alphabetical order as a JSON string. + """ + station_names = get_all_station_names() + limit = ( + min(limit, len(station_names)) + if isinstance(limit, int) and (0 < limit <= len(station_names)) + else len(station_names) + ) + + results = { + station_name: json.loads(get_train_arrival_time_by_id(station_name)) + for station_name in station_names[:limit] + } + + return json.dumps(results)