python-jejakmasjid 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_jejakmasjid-0.1.0/LICENSE +21 -0
- python_jejakmasjid-0.1.0/PKG-INFO +74 -0
- python_jejakmasjid-0.1.0/README.md +45 -0
- python_jejakmasjid-0.1.0/pyproject.toml +53 -0
- python_jejakmasjid-0.1.0/setup.cfg +4 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/__init__.py +35 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/__main__.py +4 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/cli.py +50 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/client.py +187 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/constants.py +12 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/exceptions.py +6 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/geo.py +60 -0
- python_jejakmasjid-0.1.0/src/jejakmasjid/models.py +65 -0
- python_jejakmasjid-0.1.0/src/python_jejakmasjid.egg-info/PKG-INFO +74 -0
- python_jejakmasjid-0.1.0/src/python_jejakmasjid.egg-info/SOURCES.txt +21 -0
- python_jejakmasjid-0.1.0/src/python_jejakmasjid.egg-info/dependency_links.txt +1 -0
- python_jejakmasjid-0.1.0/src/python_jejakmasjid.egg-info/entry_points.txt +2 -0
- python_jejakmasjid-0.1.0/src/python_jejakmasjid.egg-info/requires.txt +5 -0
- python_jejakmasjid-0.1.0/src/python_jejakmasjid.egg-info/top_level.txt +1 -0
- python_jejakmasjid-0.1.0/tests/test_cli.py +39 -0
- python_jejakmasjid-0.1.0/tests/test_client.py +133 -0
- python_jejakmasjid-0.1.0/tests/test_geo.py +44 -0
- python_jejakmasjid-0.1.0/tests/test_models.py +23 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zubir Jamal
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-jejakmasjid
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous Python client for the Jejak Masjid API
|
|
5
|
+
Author: Zubir Jamal
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/zubirjamal/python-jejakmasjid
|
|
8
|
+
Project-URL: Repository, https://github.com/zubirjamal/python-jejakmasjid
|
|
9
|
+
Project-URL: Issues, https://github.com/zubirjamal/python-jejakmasjid/issues
|
|
10
|
+
Keywords: jejakmasjid,masjid,surau,mosque,prayer,malaysia,home-assistant
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Home Automation
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Intended Audience :: Developers
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: aiohttp>=3.9.0
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
27
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# python-jejakmasjid
|
|
31
|
+
|
|
32
|
+
Asynchronous Python client library for the Jejak Masjid API.
|
|
33
|
+
|
|
34
|
+
Used by the Home Assistant Jejak Masjid integration to discover nearby masjids, suraus, and musollas across Malaysia.
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
|
|
38
|
+
- **Asynchronous**: Built on `aiohttp` for non-blocking I/O.
|
|
39
|
+
- **GeoJSON Parsing**: Extracts places, coordinates, place types, and amenities from the Jejak Masjid service.
|
|
40
|
+
- **Haversine Distance**: Ranks places by proximity to coordinates.
|
|
41
|
+
- **Dedicated Endpoint Ready**: Abstracted client configuration allowing seamless migration when custom endpoints are provided.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install python-jejakmasjid
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import asyncio
|
|
53
|
+
import aiohttp
|
|
54
|
+
from jejakmasjid import async_fetch_nearby, rank
|
|
55
|
+
|
|
56
|
+
async def main():
|
|
57
|
+
async with aiohttp.ClientSession() as session:
|
|
58
|
+
places = await async_fetch_nearby(session, lat=3.02, lon=101.79, radius_km=3)
|
|
59
|
+
ranked = rank(places, lat=3.02, lon=101.79)
|
|
60
|
+
for place in ranked:
|
|
61
|
+
print(f"{place['name']} ({place['type']}) - {place['distance_km']} km")
|
|
62
|
+
|
|
63
|
+
asyncio.run(main())
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## CLI Usage
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
jejakmasjid --lat 3.02 --lon 101.79 --radius 3
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
MIT
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# python-jejakmasjid
|
|
2
|
+
|
|
3
|
+
Asynchronous Python client library for the Jejak Masjid API.
|
|
4
|
+
|
|
5
|
+
Used by the Home Assistant Jejak Masjid integration to discover nearby masjids, suraus, and musollas across Malaysia.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Asynchronous**: Built on `aiohttp` for non-blocking I/O.
|
|
10
|
+
- **GeoJSON Parsing**: Extracts places, coordinates, place types, and amenities from the Jejak Masjid service.
|
|
11
|
+
- **Haversine Distance**: Ranks places by proximity to coordinates.
|
|
12
|
+
- **Dedicated Endpoint Ready**: Abstracted client configuration allowing seamless migration when custom endpoints are provided.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install python-jejakmasjid
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick Start
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import asyncio
|
|
24
|
+
import aiohttp
|
|
25
|
+
from jejakmasjid import async_fetch_nearby, rank
|
|
26
|
+
|
|
27
|
+
async def main():
|
|
28
|
+
async with aiohttp.ClientSession() as session:
|
|
29
|
+
places = await async_fetch_nearby(session, lat=3.02, lon=101.79, radius_km=3)
|
|
30
|
+
ranked = rank(places, lat=3.02, lon=101.79)
|
|
31
|
+
for place in ranked:
|
|
32
|
+
print(f"{place['name']} ({place['type']}) - {place['distance_km']} km")
|
|
33
|
+
|
|
34
|
+
asyncio.run(main())
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## CLI Usage
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
jejakmasjid --lat 3.02 --lon 101.79 --radius 3
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## License
|
|
44
|
+
|
|
45
|
+
MIT
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "python-jejakmasjid"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Asynchronous Python client for the Jejak Masjid API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Zubir Jamal" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["jejakmasjid", "masjid", "surau", "mosque", "prayer", "malaysia", "home-assistant"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Programming Language :: Python :: 3.14",
|
|
22
|
+
"License :: OSI Approved :: MIT License",
|
|
23
|
+
"Operating System :: OS Independent",
|
|
24
|
+
"Topic :: Home Automation",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
"Intended Audience :: Developers",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"aiohttp>=3.9.0",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
test = [
|
|
34
|
+
"pytest>=8.0.0",
|
|
35
|
+
"pytest-asyncio>=0.23.0",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/zubirjamal/python-jejakmasjid"
|
|
40
|
+
Repository = "https://github.com/zubirjamal/python-jejakmasjid"
|
|
41
|
+
Issues = "https://github.com/zubirjamal/python-jejakmasjid/issues"
|
|
42
|
+
|
|
43
|
+
[project.scripts]
|
|
44
|
+
jejakmasjid = "jejakmasjid.cli:main"
|
|
45
|
+
|
|
46
|
+
[tool.setuptools.packages.find]
|
|
47
|
+
where = ["src"]
|
|
48
|
+
|
|
49
|
+
[tool.pytest.ini_options]
|
|
50
|
+
asyncio_mode = "auto"
|
|
51
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
52
|
+
pythonpath = ["src"]
|
|
53
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Asynchronous Python client for Jejak Masjid."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .client import JejakMasjidClient, async_fetch_nearby, parse_places
|
|
5
|
+
from .constants import (
|
|
6
|
+
API_BASE,
|
|
7
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
8
|
+
DEFAULT_USER_AGENT,
|
|
9
|
+
HEALTH_URL,
|
|
10
|
+
NEARBY_PATH,
|
|
11
|
+
NEARBY_URL,
|
|
12
|
+
PLACE_TYPES,
|
|
13
|
+
)
|
|
14
|
+
from .exceptions import JejakMasjidError
|
|
15
|
+
from .geo import haversine_km, place_type, rank, type_from_payload
|
|
16
|
+
from .models import Place
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"API_BASE",
|
|
20
|
+
"DEFAULT_TIMEOUT_SECONDS",
|
|
21
|
+
"DEFAULT_USER_AGENT",
|
|
22
|
+
"HEALTH_URL",
|
|
23
|
+
"JejakMasjidClient",
|
|
24
|
+
"JejakMasjidError",
|
|
25
|
+
"NEARBY_PATH",
|
|
26
|
+
"NEARBY_URL",
|
|
27
|
+
"PLACE_TYPES",
|
|
28
|
+
"Place",
|
|
29
|
+
"async_fetch_nearby",
|
|
30
|
+
"haversine_km",
|
|
31
|
+
"parse_places",
|
|
32
|
+
"place_type",
|
|
33
|
+
"rank",
|
|
34
|
+
"type_from_payload",
|
|
35
|
+
]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""CLI for testing Jejak Masjid nearby lookups."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import asyncio
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
import aiohttp
|
|
9
|
+
|
|
10
|
+
from .client import async_fetch_nearby
|
|
11
|
+
from .constants import NEARBY_URL
|
|
12
|
+
from .exceptions import JejakMasjidError
|
|
13
|
+
from .geo import rank
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def _run(args: argparse.Namespace) -> int:
|
|
17
|
+
async with aiohttp.ClientSession() as session:
|
|
18
|
+
try:
|
|
19
|
+
print(f"Querying places within {args.radius}km of ({args.lat}, {args.lon})...")
|
|
20
|
+
places = await async_fetch_nearby(
|
|
21
|
+
session,
|
|
22
|
+
args.lat,
|
|
23
|
+
args.lon,
|
|
24
|
+
args.radius,
|
|
25
|
+
endpoint_url=args.endpoint,
|
|
26
|
+
)
|
|
27
|
+
ranked = rank(places, args.lat, args.lon)
|
|
28
|
+
print(f"Found {len(ranked)} place(s):")
|
|
29
|
+
for idx, p in enumerate(ranked[: args.limit], start=1):
|
|
30
|
+
haji = " [Kursus Haji]" if p.get("kursus_haji") else ""
|
|
31
|
+
print(f"{idx:2d}. {p['name']} ({p['type']}) - {p['distance_km']} km{haji}")
|
|
32
|
+
return 0
|
|
33
|
+
except JejakMasjidError as err:
|
|
34
|
+
print(f"Error: {err}", file=sys.stderr)
|
|
35
|
+
return 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main() -> None:
|
|
39
|
+
parser = argparse.ArgumentParser(description="Jejak Masjid Nearby Finder")
|
|
40
|
+
parser.add_argument("--lat", type=float, required=True, help="Latitude")
|
|
41
|
+
parser.add_argument("--lon", type=float, required=True, help="Longitude")
|
|
42
|
+
parser.add_argument("--radius", type=int, default=3, help="Search radius in km (default: 3)")
|
|
43
|
+
parser.add_argument("--limit", type=int, default=10, help="Max places to display (default: 10)")
|
|
44
|
+
parser.add_argument("--endpoint", type=str, default=NEARBY_URL, help="Custom endpoint URL")
|
|
45
|
+
args = parser.parse_args()
|
|
46
|
+
sys.exit(asyncio.run(_run(args)))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
if __name__ == "__main__":
|
|
50
|
+
main()
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Client and fetch functions for Jejak Masjid."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
|
|
9
|
+
from .constants import DEFAULT_TIMEOUT_SECONDS, DEFAULT_USER_AGENT, NEARBY_URL
|
|
10
|
+
from .exceptions import JejakMasjidError
|
|
11
|
+
from .geo import place_type, type_from_payload
|
|
12
|
+
|
|
13
|
+
_LOGGER = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parse_place_item(item: dict[str, Any]) -> dict[str, Any] | None:
|
|
17
|
+
"""Parse a single item from the new dedicated endpoint structure."""
|
|
18
|
+
try:
|
|
19
|
+
place_id = str(item.get("masjidId") or item.get("id"))
|
|
20
|
+
name = str(item.get("name") or "").strip()
|
|
21
|
+
lat = float(item.get("lat") or item.get("latitude"))
|
|
22
|
+
lon = float(item.get("lng") or item.get("longitude"))
|
|
23
|
+
|
|
24
|
+
# Calculate or extract distance
|
|
25
|
+
dist = item.get("distance")
|
|
26
|
+
if dist is not None:
|
|
27
|
+
dist_km = round(float(dist), 2)
|
|
28
|
+
elif item.get("distanceM") is not None:
|
|
29
|
+
dist_km = round(float(item["distanceM"]) / 1000.0, 2)
|
|
30
|
+
elif item.get("distance_km") is not None:
|
|
31
|
+
dist_km = round(float(item["distance_km"]), 2)
|
|
32
|
+
else:
|
|
33
|
+
dist_km = None
|
|
34
|
+
|
|
35
|
+
place = {
|
|
36
|
+
"id": place_id,
|
|
37
|
+
"name": name,
|
|
38
|
+
"type": type_from_payload(item.get("type")) or place_type(name),
|
|
39
|
+
"latitude": lat,
|
|
40
|
+
"longitude": lon,
|
|
41
|
+
"kursus_haji": bool(
|
|
42
|
+
item.get("hasKursusAsasHaji")
|
|
43
|
+
or item.get("has_kursus_asas_haji")
|
|
44
|
+
or item.get("kursus_haji")
|
|
45
|
+
),
|
|
46
|
+
}
|
|
47
|
+
if dist_km is not None:
|
|
48
|
+
place["distance_km"] = dist_km
|
|
49
|
+
if item.get("districtName"):
|
|
50
|
+
place["district_name"] = str(item["districtName"])
|
|
51
|
+
if item.get("stateName"):
|
|
52
|
+
place["state_name"] = str(item["stateName"])
|
|
53
|
+
if item.get("checkinRadiusM") is not None:
|
|
54
|
+
place["checkin_radius_m"] = int(item["checkinRadiusM"])
|
|
55
|
+
if item.get("canCheckin") is not None:
|
|
56
|
+
place["can_checkin"] = bool(item["canCheckin"])
|
|
57
|
+
if item.get("avgRating") is not None:
|
|
58
|
+
place["avg_rating"] = float(item["avgRating"])
|
|
59
|
+
|
|
60
|
+
return place
|
|
61
|
+
except (KeyError, TypeError, ValueError):
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_places(payload: Any) -> list[dict[str, Any]]:
|
|
66
|
+
"""Parse Jejak Masjid response payload supporting both GeoJSON and new REST structures.
|
|
67
|
+
|
|
68
|
+
- GeoJSON: FeatureCollection with coordinates and properties.
|
|
69
|
+
- New API: Array of objects or wrapped dict {"data": [...]} with masjidId, lat, lng, etc.
|
|
70
|
+
"""
|
|
71
|
+
places: list[dict[str, Any]] = []
|
|
72
|
+
|
|
73
|
+
# 1. New API: Direct list of dicts
|
|
74
|
+
if isinstance(payload, list):
|
|
75
|
+
for item in payload:
|
|
76
|
+
if isinstance(item, dict):
|
|
77
|
+
p = _parse_place_item(item)
|
|
78
|
+
if p:
|
|
79
|
+
places.append(p)
|
|
80
|
+
return places
|
|
81
|
+
|
|
82
|
+
if not isinstance(payload, dict):
|
|
83
|
+
raise JejakMasjidError("Unexpected response from Jejak Masjid (not a JSON object or array)")
|
|
84
|
+
|
|
85
|
+
# 2. Legacy API: GeoJSON FeatureCollection
|
|
86
|
+
if payload.get("type") == "FeatureCollection":
|
|
87
|
+
for feature in payload.get("features") or []:
|
|
88
|
+
try:
|
|
89
|
+
lon, lat = feature["geometry"]["coordinates"][:2]
|
|
90
|
+
props = feature.get("properties") or {}
|
|
91
|
+
name = str(props.get("name") or "").strip()
|
|
92
|
+
places.append(
|
|
93
|
+
{
|
|
94
|
+
"id": str(props["id"]),
|
|
95
|
+
"name": name,
|
|
96
|
+
"type": type_from_payload(props.get("type")) or place_type(name),
|
|
97
|
+
"latitude": float(lat),
|
|
98
|
+
"longitude": float(lon),
|
|
99
|
+
"kursus_haji": bool(props.get("has_kursus_asas_haji")),
|
|
100
|
+
}
|
|
101
|
+
)
|
|
102
|
+
except (KeyError, TypeError, ValueError):
|
|
103
|
+
continue
|
|
104
|
+
return places
|
|
105
|
+
|
|
106
|
+
# 3. New API wrapped: {"data": [...]} or {"places": [...]}
|
|
107
|
+
wrapped_list = payload.get("data") or payload.get("places")
|
|
108
|
+
if isinstance(wrapped_list, list):
|
|
109
|
+
for item in wrapped_list:
|
|
110
|
+
if isinstance(item, dict):
|
|
111
|
+
p = _parse_place_item(item)
|
|
112
|
+
if p:
|
|
113
|
+
places.append(p)
|
|
114
|
+
return places
|
|
115
|
+
|
|
116
|
+
raise JejakMasjidError("Unrecognized Jejak Masjid payload format")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def async_fetch_nearby(
|
|
120
|
+
session: aiohttp.ClientSession,
|
|
121
|
+
lat: float,
|
|
122
|
+
lon: float,
|
|
123
|
+
radius_km: int,
|
|
124
|
+
*,
|
|
125
|
+
endpoint_url: str | None = None,
|
|
126
|
+
user_agent: str | None = None,
|
|
127
|
+
headers: dict[str, str] | None = None,
|
|
128
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
129
|
+
) -> list[dict[str, Any]]:
|
|
130
|
+
"""Fetch places within radius_km of a coordinate point."""
|
|
131
|
+
url = endpoint_url or NEARBY_URL
|
|
132
|
+
req_headers = {"User-Agent": user_agent or DEFAULT_USER_AGENT}
|
|
133
|
+
if headers:
|
|
134
|
+
req_headers.update(headers)
|
|
135
|
+
|
|
136
|
+
params = {"lat": f"{lat:.3f}", "lng": f"{lon:.3f}", "radius": str(radius_km)}
|
|
137
|
+
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
async with session.get(url, params=params, headers=req_headers, timeout=timeout) as resp:
|
|
141
|
+
if resp.status != 200:
|
|
142
|
+
raise JejakMasjidError(f"Jejak Masjid answered HTTP {resp.status}")
|
|
143
|
+
payload = await resp.json(content_type=None)
|
|
144
|
+
except (aiohttp.ClientError, TimeoutError, ValueError) as err:
|
|
145
|
+
raise JejakMasjidError(f"Cannot reach Jejak Masjid: {err}") from err
|
|
146
|
+
|
|
147
|
+
return parse_places(payload)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class JejakMasjidClient:
|
|
151
|
+
"""Configurable client instance for Jejak Masjid API."""
|
|
152
|
+
|
|
153
|
+
def __init__(
|
|
154
|
+
self,
|
|
155
|
+
session: aiohttp.ClientSession,
|
|
156
|
+
*,
|
|
157
|
+
endpoint_url: str = NEARBY_URL,
|
|
158
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
159
|
+
api_key: str | None = None,
|
|
160
|
+
) -> None:
|
|
161
|
+
self._session = session
|
|
162
|
+
self._endpoint_url = endpoint_url
|
|
163
|
+
self._user_agent = user_agent
|
|
164
|
+
self._api_key = api_key
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def endpoint_url(self) -> str:
|
|
168
|
+
return self._endpoint_url
|
|
169
|
+
|
|
170
|
+
def set_endpoint_url(self, url: str) -> None:
|
|
171
|
+
"""Allow dynamically switching to a dedicated endpoint."""
|
|
172
|
+
self._endpoint_url = url
|
|
173
|
+
|
|
174
|
+
async def fetch_nearby(self, lat: float, lon: float, radius_km: int) -> list[dict[str, Any]]:
|
|
175
|
+
"""Fetch nearby places using configured client options."""
|
|
176
|
+
headers = {}
|
|
177
|
+
if self._api_key:
|
|
178
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
179
|
+
return await async_fetch_nearby(
|
|
180
|
+
self._session,
|
|
181
|
+
lat,
|
|
182
|
+
lon,
|
|
183
|
+
radius_km,
|
|
184
|
+
endpoint_url=self._endpoint_url,
|
|
185
|
+
user_agent=self._user_agent,
|
|
186
|
+
headers=headers,
|
|
187
|
+
)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Constants for the Jejak Masjid client library."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
API_BASE = "https://apiv2.jejakmasjid.my"
|
|
5
|
+
NEARBY_PATH = "/api/map/nearby"
|
|
6
|
+
NEARBY_URL = f"{API_BASE}{NEARBY_PATH}"
|
|
7
|
+
HEALTH_URL = f"{API_BASE}/"
|
|
8
|
+
|
|
9
|
+
DEFAULT_TIMEOUT_SECONDS = 20
|
|
10
|
+
DEFAULT_USER_AGENT = "python-jejakmasjid/0.1.0 (+https://github.com/zubirjamal/python-jejakmasjid)"
|
|
11
|
+
|
|
12
|
+
PLACE_TYPES = ["masjid", "surau", "madrasah", "other"]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Geographic and categorization helpers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
_TYPES = (
|
|
9
|
+
("masjid", re.compile(r"^\W*(masjid|mosque)\b", re.I)),
|
|
10
|
+
("surau", re.compile(r"^\W*(surau|mini\s*surau|musolla|musolah|musalla|prayer room|bilik solat)\b", re.I)),
|
|
11
|
+
("madrasah", re.compile(r"^\W*madrasah?\b", re.I)),
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
16
|
+
"""Great-circle distance in kilometers using the Haversine formula."""
|
|
17
|
+
r = 6371.0088
|
|
18
|
+
p1, p2 = math.radians(lat1), math.radians(lat2)
|
|
19
|
+
dp, dl = p2 - p1, math.radians(lon2 - lon1)
|
|
20
|
+
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
|
21
|
+
return 2 * r * math.asin(math.sqrt(a))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def type_from_payload(raw: Any) -> str | None:
|
|
25
|
+
"""Map the API's own type field to ours, if it sends one; None when absent or unknown."""
|
|
26
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
27
|
+
return None
|
|
28
|
+
value = raw.strip().lower()
|
|
29
|
+
if re.search(r"masjid|mosque", value):
|
|
30
|
+
return "masjid"
|
|
31
|
+
if re.search(r"surau|musolla|musalla|musolah|prayer|solat", value):
|
|
32
|
+
return "surau"
|
|
33
|
+
if re.search(r"madrasah?", value):
|
|
34
|
+
return "madrasah"
|
|
35
|
+
return "other"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def place_type(name: str) -> str:
|
|
39
|
+
"""Masjid, surau, madrasah or other, deduced from the place name."""
|
|
40
|
+
for kind, pattern in _TYPES:
|
|
41
|
+
if pattern.search(name or ""):
|
|
42
|
+
return kind
|
|
43
|
+
if re.search(r"\b(surau|musolla|musalla|prayer room)\b", name or "", re.I):
|
|
44
|
+
return "surau"
|
|
45
|
+
if re.search(r"\b(masjid|mosque)\b", name or "", re.I):
|
|
46
|
+
return "masjid"
|
|
47
|
+
return "other"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def rank(places: list[dict[str, Any]], lat: float, lon: float) -> list[dict[str, Any]]:
|
|
51
|
+
"""Places with distance_km from (lat, lon), sorted nearest first."""
|
|
52
|
+
out = []
|
|
53
|
+
for p in places:
|
|
54
|
+
# If the API already calculated distance, use it unless re-ranking from a different point
|
|
55
|
+
dist = p.get("distance_km")
|
|
56
|
+
if dist is None:
|
|
57
|
+
dist = round(haversine_km(lat, lon, p["latitude"], p["longitude"]), 2)
|
|
58
|
+
out.append({**p, "distance_km": dist})
|
|
59
|
+
out.sort(key=lambda p: p["distance_km"])
|
|
60
|
+
return out
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Data models for Jejak Masjid places."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import asdict, dataclass
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class Place:
|
|
10
|
+
"""Represents a masjid, surau, or prayer facility."""
|
|
11
|
+
|
|
12
|
+
id: str
|
|
13
|
+
name: str
|
|
14
|
+
type: str
|
|
15
|
+
latitude: float
|
|
16
|
+
longitude: float
|
|
17
|
+
kursus_haji: bool = False
|
|
18
|
+
distance_km: float | None = None
|
|
19
|
+
district_name: str | None = None
|
|
20
|
+
state_name: str | None = None
|
|
21
|
+
checkin_radius_m: int | None = None
|
|
22
|
+
can_checkin: bool | None = None
|
|
23
|
+
avg_rating: float | None = None
|
|
24
|
+
|
|
25
|
+
def as_dict(self) -> dict[str, Any]:
|
|
26
|
+
"""Convert to dictionary representation matching Home Assistant integration format."""
|
|
27
|
+
res: dict[str, Any] = {
|
|
28
|
+
"id": self.id,
|
|
29
|
+
"name": self.name,
|
|
30
|
+
"type": self.type,
|
|
31
|
+
"latitude": self.latitude,
|
|
32
|
+
"longitude": self.longitude,
|
|
33
|
+
"kursus_haji": self.kursus_haji,
|
|
34
|
+
}
|
|
35
|
+
if self.distance_km is not None:
|
|
36
|
+
res["distance_km"] = self.distance_km
|
|
37
|
+
if self.district_name is not None:
|
|
38
|
+
res["district_name"] = self.district_name
|
|
39
|
+
if self.state_name is not None:
|
|
40
|
+
res["state_name"] = self.state_name
|
|
41
|
+
if self.checkin_radius_m is not None:
|
|
42
|
+
res["checkin_radius_m"] = self.checkin_radius_m
|
|
43
|
+
if self.can_checkin is not None:
|
|
44
|
+
res["can_checkin"] = self.can_checkin
|
|
45
|
+
if self.avg_rating is not None:
|
|
46
|
+
res["avg_rating"] = self.avg_rating
|
|
47
|
+
return res
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_dict(cls, data: dict[str, Any]) -> Place:
|
|
51
|
+
"""Create a Place from a dictionary."""
|
|
52
|
+
return cls(
|
|
53
|
+
id=str(data["id"]),
|
|
54
|
+
name=str(data["name"]),
|
|
55
|
+
type=str(data.get("type", "other")),
|
|
56
|
+
latitude=float(data["latitude"]),
|
|
57
|
+
longitude=float(data["longitude"]),
|
|
58
|
+
kursus_haji=bool(data.get("kursus_haji", False)),
|
|
59
|
+
distance_km=float(data["distance_km"]) if data.get("distance_km") is not None else None,
|
|
60
|
+
district_name=data.get("district_name"),
|
|
61
|
+
state_name=data.get("state_name"),
|
|
62
|
+
checkin_radius_m=int(data["checkin_radius_m"]) if data.get("checkin_radius_m") is not None else None,
|
|
63
|
+
can_checkin=bool(data["can_checkin"]) if data.get("can_checkin") is not None else None,
|
|
64
|
+
avg_rating=float(data["avg_rating"]) if data.get("avg_rating") is not None else None,
|
|
65
|
+
)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-jejakmasjid
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous Python client for the Jejak Masjid API
|
|
5
|
+
Author: Zubir Jamal
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/zubirjamal/python-jejakmasjid
|
|
8
|
+
Project-URL: Repository, https://github.com/zubirjamal/python-jejakmasjid
|
|
9
|
+
Project-URL: Issues, https://github.com/zubirjamal/python-jejakmasjid/issues
|
|
10
|
+
Keywords: jejakmasjid,masjid,surau,mosque,prayer,malaysia,home-assistant
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Home Automation
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Intended Audience :: Developers
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: aiohttp>=3.9.0
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
27
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# python-jejakmasjid
|
|
31
|
+
|
|
32
|
+
Asynchronous Python client library for the Jejak Masjid API.
|
|
33
|
+
|
|
34
|
+
Used by the Home Assistant Jejak Masjid integration to discover nearby masjids, suraus, and musollas across Malaysia.
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
|
|
38
|
+
- **Asynchronous**: Built on `aiohttp` for non-blocking I/O.
|
|
39
|
+
- **GeoJSON Parsing**: Extracts places, coordinates, place types, and amenities from the Jejak Masjid service.
|
|
40
|
+
- **Haversine Distance**: Ranks places by proximity to coordinates.
|
|
41
|
+
- **Dedicated Endpoint Ready**: Abstracted client configuration allowing seamless migration when custom endpoints are provided.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install python-jejakmasjid
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import asyncio
|
|
53
|
+
import aiohttp
|
|
54
|
+
from jejakmasjid import async_fetch_nearby, rank
|
|
55
|
+
|
|
56
|
+
async def main():
|
|
57
|
+
async with aiohttp.ClientSession() as session:
|
|
58
|
+
places = await async_fetch_nearby(session, lat=3.02, lon=101.79, radius_km=3)
|
|
59
|
+
ranked = rank(places, lat=3.02, lon=101.79)
|
|
60
|
+
for place in ranked:
|
|
61
|
+
print(f"{place['name']} ({place['type']}) - {place['distance_km']} km")
|
|
62
|
+
|
|
63
|
+
asyncio.run(main())
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## CLI Usage
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
jejakmasjid --lat 3.02 --lon 101.79 --radius 3
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
MIT
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/jejakmasjid/__init__.py
|
|
5
|
+
src/jejakmasjid/__main__.py
|
|
6
|
+
src/jejakmasjid/cli.py
|
|
7
|
+
src/jejakmasjid/client.py
|
|
8
|
+
src/jejakmasjid/constants.py
|
|
9
|
+
src/jejakmasjid/exceptions.py
|
|
10
|
+
src/jejakmasjid/geo.py
|
|
11
|
+
src/jejakmasjid/models.py
|
|
12
|
+
src/python_jejakmasjid.egg-info/PKG-INFO
|
|
13
|
+
src/python_jejakmasjid.egg-info/SOURCES.txt
|
|
14
|
+
src/python_jejakmasjid.egg-info/dependency_links.txt
|
|
15
|
+
src/python_jejakmasjid.egg-info/entry_points.txt
|
|
16
|
+
src/python_jejakmasjid.egg-info/requires.txt
|
|
17
|
+
src/python_jejakmasjid.egg-info/top_level.txt
|
|
18
|
+
tests/test_cli.py
|
|
19
|
+
tests/test_client.py
|
|
20
|
+
tests/test_geo.py
|
|
21
|
+
tests/test_models.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jejakmasjid
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Tests for the CLI module."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from unittest.mock import AsyncMock, patch
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from jejakmasjid.cli import _run, main
|
|
9
|
+
from jejakmasjid.exceptions import JejakMasjidError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def test_cli_run_success():
|
|
13
|
+
class Args:
|
|
14
|
+
lat = 3.02
|
|
15
|
+
lon = 101.79
|
|
16
|
+
radius = 3
|
|
17
|
+
limit = 5
|
|
18
|
+
endpoint = "https://custom.api/nearby"
|
|
19
|
+
|
|
20
|
+
mock_places = [
|
|
21
|
+
{"id": "1", "name": "Masjid Test", "type": "masjid", "latitude": 3.02, "longitude": 101.79, "kursus_haji": True}
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
with patch("jejakmasjid.cli.async_fetch_nearby", AsyncMock(return_value=mock_places)):
|
|
25
|
+
exit_code = await _run(Args())
|
|
26
|
+
assert exit_code == 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def test_cli_run_error():
|
|
30
|
+
class Args:
|
|
31
|
+
lat = 3.02
|
|
32
|
+
lon = 101.79
|
|
33
|
+
radius = 3
|
|
34
|
+
limit = 5
|
|
35
|
+
endpoint = "https://custom.api/nearby"
|
|
36
|
+
|
|
37
|
+
with patch("jejakmasjid.cli.async_fetch_nearby", AsyncMock(side_effect=JejakMasjidError("API Down"))):
|
|
38
|
+
exit_code = await _run(Args())
|
|
39
|
+
assert exit_code == 1
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Tests for parser and client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from unittest.mock import AsyncMock, MagicMock
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from jejakmasjid.client import JejakMasjidClient, async_fetch_nearby, parse_places
|
|
9
|
+
from jejakmasjid.exceptions import JejakMasjidError
|
|
10
|
+
from jejakmasjid.geo import rank
|
|
11
|
+
|
|
12
|
+
MOCK_LEGACY_PAYLOAD = {
|
|
13
|
+
"type": "FeatureCollection",
|
|
14
|
+
"features": [
|
|
15
|
+
{
|
|
16
|
+
"type": "Feature",
|
|
17
|
+
"geometry": {"type": "Point", "coordinates": [101.790497, 3.020018]},
|
|
18
|
+
"properties": {
|
|
19
|
+
"id": "place-1",
|
|
20
|
+
"name": "Surau Ar-Raudhah",
|
|
21
|
+
"has_kursus_asas_haji": False,
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"type": "Feature",
|
|
26
|
+
"geometry": {"type": "Point", "coordinates": [101.785287, 3.024986]},
|
|
27
|
+
"properties": {
|
|
28
|
+
"id": "place-2",
|
|
29
|
+
"name": "Masjid Saujana Impian",
|
|
30
|
+
"type": "Masjid",
|
|
31
|
+
"has_kursus_asas_haji": True,
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
],
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
MOCK_NEW_ITEM = {
|
|
38
|
+
"masjidId": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
|
|
39
|
+
"name": "Surau Suria KLCC",
|
|
40
|
+
"lat": 3.1572757,
|
|
41
|
+
"lng": 101.7122335,
|
|
42
|
+
"districtName": "Kuala Lumpur",
|
|
43
|
+
"stateName": "Wilayah Persekutuan Kuala Lumpur",
|
|
44
|
+
"checkinRadiusM": 100,
|
|
45
|
+
"type": "mini surau",
|
|
46
|
+
"hasKursusAsasHaji": False,
|
|
47
|
+
"distance": 0.0424233531125441,
|
|
48
|
+
"distanceM": 42,
|
|
49
|
+
"canCheckin": True,
|
|
50
|
+
"avgRating": 4.875,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_parse_legacy_places():
|
|
55
|
+
places = parse_places(MOCK_LEGACY_PAYLOAD)
|
|
56
|
+
assert len(places) == 2
|
|
57
|
+
assert places[0]["id"] == "place-1"
|
|
58
|
+
assert places[0]["name"] == "Surau Ar-Raudhah"
|
|
59
|
+
assert places[0]["type"] == "surau"
|
|
60
|
+
assert places[0]["kursus_haji"] is False
|
|
61
|
+
assert places[1]["id"] == "place-2"
|
|
62
|
+
assert places[1]["type"] == "masjid"
|
|
63
|
+
assert places[1]["kursus_haji"] is True
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_parse_new_endpoint_array():
|
|
67
|
+
places = parse_places([MOCK_NEW_ITEM])
|
|
68
|
+
assert len(places) == 1
|
|
69
|
+
p = places[0]
|
|
70
|
+
assert p["id"] == "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
|
|
71
|
+
assert p["name"] == "Surau Suria KLCC"
|
|
72
|
+
assert p["type"] == "surau"
|
|
73
|
+
assert p["latitude"] == 3.1572757
|
|
74
|
+
assert p["longitude"] == 101.7122335
|
|
75
|
+
assert p["kursus_haji"] is False
|
|
76
|
+
assert p["distance_km"] == 0.04
|
|
77
|
+
assert p["district_name"] == "Kuala Lumpur"
|
|
78
|
+
assert p["state_name"] == "Wilayah Persekutuan Kuala Lumpur"
|
|
79
|
+
assert p["checkin_radius_m"] == 100
|
|
80
|
+
assert p["can_checkin"] is True
|
|
81
|
+
assert p["avg_rating"] == 4.875
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_parse_new_endpoint_wrapped():
|
|
85
|
+
places = parse_places({"data": [MOCK_NEW_ITEM]})
|
|
86
|
+
assert len(places) == 1
|
|
87
|
+
assert places[0]["id"] == "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_parse_places_invalid():
|
|
91
|
+
with pytest.raises(JejakMasjidError):
|
|
92
|
+
parse_places({"unexpected": "structure"})
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def test_async_fetch_nearby_success():
|
|
96
|
+
mock_resp = AsyncMock()
|
|
97
|
+
mock_resp.status = 200
|
|
98
|
+
mock_resp.json = AsyncMock(return_value=[MOCK_NEW_ITEM])
|
|
99
|
+
|
|
100
|
+
mock_session = MagicMock()
|
|
101
|
+
mock_session.get.return_value.__aenter__.return_value = mock_resp
|
|
102
|
+
|
|
103
|
+
places = await async_fetch_nearby(mock_session, 3.02, 101.79, 3)
|
|
104
|
+
assert len(places) == 1
|
|
105
|
+
assert places[0]["name"] == "Surau Suria KLCC"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def test_async_fetch_nearby_http_error():
|
|
109
|
+
mock_resp = AsyncMock()
|
|
110
|
+
mock_resp.status = 500
|
|
111
|
+
|
|
112
|
+
mock_session = MagicMock()
|
|
113
|
+
mock_session.get.return_value.__aenter__.return_value = mock_resp
|
|
114
|
+
|
|
115
|
+
with pytest.raises(JejakMasjidError):
|
|
116
|
+
await async_fetch_nearby(mock_session, 3.02, 101.79, 3)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def test_client_custom_endpoint():
|
|
120
|
+
mock_resp = AsyncMock()
|
|
121
|
+
mock_resp.status = 200
|
|
122
|
+
mock_resp.json = AsyncMock(return_value=[MOCK_NEW_ITEM])
|
|
123
|
+
|
|
124
|
+
mock_session = MagicMock()
|
|
125
|
+
mock_session.get.return_value.__aenter__.return_value = mock_resp
|
|
126
|
+
|
|
127
|
+
client = JejakMasjidClient(mock_session, endpoint_url="https://custom.api/nearby", api_key="secret123")
|
|
128
|
+
places = await client.fetch_nearby(3.02, 101.79, 5)
|
|
129
|
+
assert len(places) == 1
|
|
130
|
+
|
|
131
|
+
call_args = mock_session.get.call_args
|
|
132
|
+
assert call_args[0][0] == "https://custom.api/nearby"
|
|
133
|
+
assert call_args[1]["headers"]["Authorization"] == "Bearer secret123"
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Tests for geographic and naming functions."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from jejakmasjid.geo import haversine_km, place_type, rank, type_from_payload
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_haversine_same_point():
|
|
8
|
+
assert haversine_km(3.02, 101.79, 3.02, 101.79) == 0.0
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_haversine_distance():
|
|
12
|
+
# Distance between Saujana Impian (3.02, 101.79) and Kajang Town (2.99, 101.79) is approx 3.3 km
|
|
13
|
+
d = haversine_km(3.02, 101.79, 2.99, 101.79)
|
|
14
|
+
assert 3.0 < d < 3.6
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_place_type_detection():
|
|
18
|
+
assert place_type("Masjid Saujana Impian") == "masjid"
|
|
19
|
+
assert place_type("Mosque of Wilayah") == "masjid"
|
|
20
|
+
assert place_type("Surau Ar-Raudhah") == "surau"
|
|
21
|
+
assert place_type("Musolla Al-Amin") == "surau"
|
|
22
|
+
assert place_type("Prayer Room Level 3") == "surau"
|
|
23
|
+
assert place_type("Madrasah Tahfiz") == "madrasah"
|
|
24
|
+
assert place_type("Dewan Komuniti") == "other"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_type_from_payload():
|
|
28
|
+
assert type_from_payload("Masjid") == "masjid"
|
|
29
|
+
assert type_from_payload("Surau") == "surau"
|
|
30
|
+
assert type_from_payload("Madrasah") == "madrasah"
|
|
31
|
+
assert type_from_payload("Unknown") == "other"
|
|
32
|
+
assert type_from_payload(None) is None
|
|
33
|
+
assert type_from_payload("") is None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_rank_ordering():
|
|
37
|
+
places = [
|
|
38
|
+
{"id": "1", "name": "Far", "latitude": 3.10, "longitude": 101.79},
|
|
39
|
+
{"id": "2", "name": "Near", "latitude": 3.03, "longitude": 101.79},
|
|
40
|
+
]
|
|
41
|
+
ranked = rank(places, 3.02, 101.79)
|
|
42
|
+
assert ranked[0]["id"] == "2"
|
|
43
|
+
assert ranked[1]["id"] == "1"
|
|
44
|
+
assert ranked[0]["distance_km"] < ranked[1]["distance_km"]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Tests for data models."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from jejakmasjid.models import Place
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_place_model():
|
|
8
|
+
p = Place(
|
|
9
|
+
id="123",
|
|
10
|
+
name="Masjid Test",
|
|
11
|
+
type="masjid",
|
|
12
|
+
latitude=3.02,
|
|
13
|
+
longitude=101.79,
|
|
14
|
+
kursus_haji=True,
|
|
15
|
+
distance_km=1.25,
|
|
16
|
+
)
|
|
17
|
+
d = p.as_dict()
|
|
18
|
+
assert d["id"] == "123"
|
|
19
|
+
assert d["distance_km"] == 1.25
|
|
20
|
+
assert d["kursus_haji"] is True
|
|
21
|
+
|
|
22
|
+
restored = Place.from_dict(d)
|
|
23
|
+
assert restored == p
|