python-jejakmasjid 0.1.0__tar.gz → 0.2.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 → python_jejakmasjid-0.2.0}/PKG-INFO +1 -1
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/pyproject.toml +1 -1
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/jejakmasjid/__init__.py +18 -1
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/jejakmasjid/client.py +88 -37
- python_jejakmasjid-0.2.0/src/jejakmasjid/constants.py +17 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/jejakmasjid/geo.py +41 -1
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/jejakmasjid/models.py +12 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/PKG-INFO +1 -1
- python_jejakmasjid-0.2.0/tests/test_client.py +145 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/tests/test_geo.py +15 -2
- python_jejakmasjid-0.1.0/src/jejakmasjid/constants.py +0 -12
- python_jejakmasjid-0.1.0/tests/test_client.py +0 -133
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/LICENSE +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/README.md +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/setup.cfg +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/jejakmasjid/__main__.py +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/jejakmasjid/cli.py +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/jejakmasjid/exceptions.py +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/SOURCES.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/dependency_links.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/entry_points.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/requires.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/top_level.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/tests/test_cli.py +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/tests/test_models.py +0 -0
|
@@ -6,30 +6,47 @@ from .constants import (
|
|
|
6
6
|
API_BASE,
|
|
7
7
|
DEFAULT_TIMEOUT_SECONDS,
|
|
8
8
|
DEFAULT_USER_AGENT,
|
|
9
|
+
FALLBACK_NEARBY_URL,
|
|
10
|
+
HA_V1_NEARBY_PATH,
|
|
9
11
|
HEALTH_URL,
|
|
12
|
+
LEGACY_NEARBY_PATH,
|
|
10
13
|
NEARBY_PATH,
|
|
11
14
|
NEARBY_URL,
|
|
12
15
|
PLACE_TYPES,
|
|
16
|
+
PRIMARY_NEARBY_URL,
|
|
13
17
|
)
|
|
14
18
|
from .exceptions import JejakMasjidError
|
|
15
|
-
from .geo import
|
|
19
|
+
from .geo import (
|
|
20
|
+
DIRECTIONS,
|
|
21
|
+
haversine_km,
|
|
22
|
+
place_type,
|
|
23
|
+
project_coordinates,
|
|
24
|
+
rank,
|
|
25
|
+
type_from_payload,
|
|
26
|
+
)
|
|
16
27
|
from .models import Place
|
|
17
28
|
|
|
18
29
|
__all__ = [
|
|
19
30
|
"API_BASE",
|
|
20
31
|
"DEFAULT_TIMEOUT_SECONDS",
|
|
21
32
|
"DEFAULT_USER_AGENT",
|
|
33
|
+
"DIRECTIONS",
|
|
34
|
+
"FALLBACK_NEARBY_URL",
|
|
35
|
+
"HA_V1_NEARBY_PATH",
|
|
22
36
|
"HEALTH_URL",
|
|
23
37
|
"JejakMasjidClient",
|
|
24
38
|
"JejakMasjidError",
|
|
39
|
+
"LEGACY_NEARBY_PATH",
|
|
25
40
|
"NEARBY_PATH",
|
|
26
41
|
"NEARBY_URL",
|
|
27
42
|
"PLACE_TYPES",
|
|
43
|
+
"PRIMARY_NEARBY_URL",
|
|
28
44
|
"Place",
|
|
29
45
|
"async_fetch_nearby",
|
|
30
46
|
"haversine_km",
|
|
31
47
|
"parse_places",
|
|
32
48
|
"place_type",
|
|
49
|
+
"project_coordinates",
|
|
33
50
|
"rank",
|
|
34
51
|
"type_from_payload",
|
|
35
52
|
]
|
|
@@ -6,33 +6,54 @@ from typing import Any
|
|
|
6
6
|
|
|
7
7
|
import aiohttp
|
|
8
8
|
|
|
9
|
-
from .constants import
|
|
9
|
+
from .constants import (
|
|
10
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
11
|
+
DEFAULT_USER_AGENT,
|
|
12
|
+
FALLBACK_NEARBY_URL,
|
|
13
|
+
PRIMARY_NEARBY_URL,
|
|
14
|
+
)
|
|
10
15
|
from .exceptions import JejakMasjidError
|
|
11
|
-
from .geo import place_type, type_from_payload
|
|
16
|
+
from .geo import place_type, project_coordinates, type_from_payload
|
|
12
17
|
|
|
13
18
|
_LOGGER = logging.getLogger(__name__)
|
|
14
19
|
|
|
15
20
|
|
|
16
|
-
def _parse_place_item(
|
|
17
|
-
|
|
21
|
+
def _parse_place_item(
|
|
22
|
+
item: dict[str, Any], origin_lat: float | None = None, origin_lon: float | None = None
|
|
23
|
+
) -> dict[str, Any] | None:
|
|
24
|
+
"""Parse a single item from dedicated HA v1 or mobile app JSON structures."""
|
|
18
25
|
try:
|
|
19
|
-
place_id = str(item.get("
|
|
26
|
+
place_id = str(item.get("id") or item.get("masjidId"))
|
|
20
27
|
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
28
|
|
|
24
|
-
#
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
29
|
+
# Extract or project coordinates
|
|
30
|
+
if item.get("lat") is not None or item.get("latitude") is not None:
|
|
31
|
+
lat = float(item.get("lat") or item.get("latitude"))
|
|
32
|
+
lon = float(item.get("lng") or item.get("longitude"))
|
|
33
|
+
elif origin_lat is not None and origin_lon is not None:
|
|
34
|
+
dist_val = float(item.get("distance_m") or item.get("distanceM") or 500)
|
|
35
|
+
dir_val = item.get("direction")
|
|
36
|
+
lat, lon = project_coordinates(origin_lat, origin_lon, dist_val, dir_val)
|
|
37
|
+
else:
|
|
38
|
+
lat, lon = 0.0, 0.0
|
|
39
|
+
|
|
40
|
+
# Calculate or extract distances
|
|
41
|
+
dist_m: int | None = None
|
|
42
|
+
dist_km: float | None = None
|
|
43
|
+
if item.get("distance_m") is not None:
|
|
44
|
+
dist_m = int(item["distance_m"])
|
|
45
|
+
dist_km = round(dist_m / 1000.0, 2)
|
|
28
46
|
elif item.get("distanceM") is not None:
|
|
29
|
-
|
|
47
|
+
dist_m = int(item["distanceM"])
|
|
48
|
+
dist_km = round(dist_m / 1000.0, 2)
|
|
49
|
+
elif item.get("distance") is not None:
|
|
50
|
+
dist_km = round(float(item["distance"]), 2)
|
|
51
|
+
dist_m = int(dist_km * 1000)
|
|
30
52
|
elif item.get("distance_km") is not None:
|
|
31
53
|
dist_km = round(float(item["distance_km"]), 2)
|
|
32
|
-
|
|
33
|
-
dist_km = None
|
|
54
|
+
dist_m = int(dist_km * 1000)
|
|
34
55
|
|
|
35
|
-
place = {
|
|
56
|
+
place: dict[str, Any] = {
|
|
36
57
|
"id": place_id,
|
|
37
58
|
"name": name,
|
|
38
59
|
"type": type_from_payload(item.get("type")) or place_type(name),
|
|
@@ -46,6 +67,12 @@ def _parse_place_item(item: dict[str, Any]) -> dict[str, Any] | None:
|
|
|
46
67
|
}
|
|
47
68
|
if dist_km is not None:
|
|
48
69
|
place["distance_km"] = dist_km
|
|
70
|
+
if dist_m is not None:
|
|
71
|
+
place["distance_m"] = dist_m
|
|
72
|
+
if item.get("direction"):
|
|
73
|
+
place["direction"] = str(item["direction"])
|
|
74
|
+
if item.get("url"):
|
|
75
|
+
place["url"] = str(item["url"])
|
|
49
76
|
if item.get("districtName"):
|
|
50
77
|
place["district_name"] = str(item["districtName"])
|
|
51
78
|
if item.get("stateName"):
|
|
@@ -62,19 +89,26 @@ def _parse_place_item(item: dict[str, Any]) -> dict[str, Any] | None:
|
|
|
62
89
|
return None
|
|
63
90
|
|
|
64
91
|
|
|
65
|
-
def parse_places(
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
- New API: Array of objects or wrapped dict {"data": [...]} with masjidId, lat, lng, etc.
|
|
70
|
-
"""
|
|
92
|
+
def parse_places(
|
|
93
|
+
payload: Any, origin_lat: float | None = None, origin_lon: float | None = None
|
|
94
|
+
) -> list[dict[str, Any]]:
|
|
95
|
+
"""Parse Jejak Masjid response payload supporting dedicated HA v1, REST arrays, and GeoJSON."""
|
|
71
96
|
places: list[dict[str, Any]] = []
|
|
72
97
|
|
|
73
|
-
# 1.
|
|
98
|
+
# 1. Dedicated HA v1 format: {"masjids": [...], "count": 5, ...}
|
|
99
|
+
if isinstance(payload, dict) and "masjids" in payload:
|
|
100
|
+
for item in payload.get("masjids") or []:
|
|
101
|
+
if isinstance(item, dict):
|
|
102
|
+
p = _parse_place_item(item, origin_lat, origin_lon)
|
|
103
|
+
if p:
|
|
104
|
+
places.append(p)
|
|
105
|
+
return places
|
|
106
|
+
|
|
107
|
+
# 2. Direct list of items: [{...}, {...}]
|
|
74
108
|
if isinstance(payload, list):
|
|
75
109
|
for item in payload:
|
|
76
110
|
if isinstance(item, dict):
|
|
77
|
-
p = _parse_place_item(item)
|
|
111
|
+
p = _parse_place_item(item, origin_lat, origin_lon)
|
|
78
112
|
if p:
|
|
79
113
|
places.append(p)
|
|
80
114
|
return places
|
|
@@ -82,7 +116,7 @@ def parse_places(payload: Any) -> list[dict[str, Any]]:
|
|
|
82
116
|
if not isinstance(payload, dict):
|
|
83
117
|
raise JejakMasjidError("Unexpected response from Jejak Masjid (not a JSON object or array)")
|
|
84
118
|
|
|
85
|
-
#
|
|
119
|
+
# 3. Legacy GeoJSON format: {"type": "FeatureCollection", ...}
|
|
86
120
|
if payload.get("type") == "FeatureCollection":
|
|
87
121
|
for feature in payload.get("features") or []:
|
|
88
122
|
try:
|
|
@@ -103,12 +137,12 @@ def parse_places(payload: Any) -> list[dict[str, Any]]:
|
|
|
103
137
|
continue
|
|
104
138
|
return places
|
|
105
139
|
|
|
106
|
-
#
|
|
140
|
+
# 4. Generic wrapped list: {"data": [...]} or {"places": [...]}
|
|
107
141
|
wrapped_list = payload.get("data") or payload.get("places")
|
|
108
142
|
if isinstance(wrapped_list, list):
|
|
109
143
|
for item in wrapped_list:
|
|
110
144
|
if isinstance(item, dict):
|
|
111
|
-
p = _parse_place_item(item)
|
|
145
|
+
p = _parse_place_item(item, origin_lat, origin_lon)
|
|
112
146
|
if p:
|
|
113
147
|
places.append(p)
|
|
114
148
|
return places
|
|
@@ -120,31 +154,48 @@ async def async_fetch_nearby(
|
|
|
120
154
|
session: aiohttp.ClientSession,
|
|
121
155
|
lat: float,
|
|
122
156
|
lon: float,
|
|
123
|
-
radius_km: int,
|
|
157
|
+
radius_km: int = 5,
|
|
124
158
|
*,
|
|
125
159
|
endpoint_url: str | None = None,
|
|
126
160
|
user_agent: str | None = None,
|
|
127
161
|
headers: dict[str, str] | None = None,
|
|
128
162
|
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
129
163
|
) -> list[dict[str, Any]]:
|
|
130
|
-
"""Fetch places within radius_km of a coordinate point."""
|
|
131
|
-
|
|
164
|
+
"""Fetch places within radius_km of a coordinate point with fallback support."""
|
|
165
|
+
primary_url = endpoint_url or PRIMARY_NEARBY_URL
|
|
132
166
|
req_headers = {"User-Agent": user_agent or DEFAULT_USER_AGENT}
|
|
133
167
|
if headers:
|
|
134
168
|
req_headers.update(headers)
|
|
135
169
|
|
|
136
|
-
params = {"lat": f"{lat:.3f}", "lng": f"{lon:.3f}", "radius": str(radius_km)}
|
|
137
170
|
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
|
|
138
171
|
|
|
172
|
+
# 1. Attempt primary dedicated endpoint
|
|
173
|
+
params = {"lat": f"{lat:.4f}", "lng": f"{lon:.4f}"}
|
|
139
174
|
try:
|
|
140
|
-
async with session.get(
|
|
141
|
-
if resp.status
|
|
175
|
+
async with session.get(primary_url, params=params, headers=req_headers, timeout=timeout) as resp:
|
|
176
|
+
if resp.status == 200:
|
|
177
|
+
payload = await resp.json(content_type=None)
|
|
178
|
+
return parse_places(payload, origin_lat=lat, origin_lon=lon)
|
|
179
|
+
if resp.status != 404 or endpoint_url:
|
|
142
180
|
raise JejakMasjidError(f"Jejak Masjid answered HTTP {resp.status}")
|
|
143
|
-
|
|
181
|
+
_LOGGER.warning("Dedicated endpoint returned 404, falling back to legacy endpoint")
|
|
144
182
|
except (aiohttp.ClientError, TimeoutError, ValueError) as err:
|
|
145
|
-
|
|
183
|
+
if endpoint_url:
|
|
184
|
+
raise JejakMasjidError(f"Cannot reach Jejak Masjid: {err}") from err
|
|
185
|
+
_LOGGER.warning("Dedicated endpoint failed (%s), falling back to legacy endpoint", err)
|
|
146
186
|
|
|
147
|
-
|
|
187
|
+
# 2. Fallback to legacy endpoint if primary returned 404 or connection failed
|
|
188
|
+
fallback_params = {"lat": f"{lat:.3f}", "lng": f"{lon:.3f}", "radius": str(radius_km)}
|
|
189
|
+
try:
|
|
190
|
+
async with session.get(
|
|
191
|
+
FALLBACK_NEARBY_URL, params=fallback_params, headers=req_headers, timeout=timeout
|
|
192
|
+
) as resp:
|
|
193
|
+
if resp.status != 200:
|
|
194
|
+
raise JejakMasjidError(f"Jejak Masjid fallback answered HTTP {resp.status}")
|
|
195
|
+
payload = await resp.json(content_type=None)
|
|
196
|
+
return parse_places(payload, origin_lat=lat, origin_lon=lon)
|
|
197
|
+
except (aiohttp.ClientError, TimeoutError, ValueError) as err:
|
|
198
|
+
raise JejakMasjidError(f"Cannot reach Jejak Masjid (fallback): {err}") from err
|
|
148
199
|
|
|
149
200
|
|
|
150
201
|
class JejakMasjidClient:
|
|
@@ -154,7 +205,7 @@ class JejakMasjidClient:
|
|
|
154
205
|
self,
|
|
155
206
|
session: aiohttp.ClientSession,
|
|
156
207
|
*,
|
|
157
|
-
endpoint_url: str =
|
|
208
|
+
endpoint_url: str = PRIMARY_NEARBY_URL,
|
|
158
209
|
user_agent: str = DEFAULT_USER_AGENT,
|
|
159
210
|
api_key: str | None = None,
|
|
160
211
|
) -> None:
|
|
@@ -171,7 +222,7 @@ class JejakMasjidClient:
|
|
|
171
222
|
"""Allow dynamically switching to a dedicated endpoint."""
|
|
172
223
|
self._endpoint_url = url
|
|
173
224
|
|
|
174
|
-
async def fetch_nearby(self, lat: float, lon: float, radius_km: int) -> list[dict[str, Any]]:
|
|
225
|
+
async def fetch_nearby(self, lat: float, lon: float, radius_km: int = 5) -> list[dict[str, Any]]:
|
|
175
226
|
"""Fetch nearby places using configured client options."""
|
|
176
227
|
headers = {}
|
|
177
228
|
if self._api_key:
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Constants for the Jejak Masjid client library."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
API_BASE = "https://apiv2.jejakmasjid.my"
|
|
5
|
+
HA_V1_NEARBY_PATH = "/api/ha/v1/masjids/nearby"
|
|
6
|
+
LEGACY_NEARBY_PATH = "/api/map/nearby"
|
|
7
|
+
NEARBY_PATH = HA_V1_NEARBY_PATH
|
|
8
|
+
|
|
9
|
+
PRIMARY_NEARBY_URL = f"{API_BASE}{HA_V1_NEARBY_PATH}"
|
|
10
|
+
FALLBACK_NEARBY_URL = f"{API_BASE}{LEGACY_NEARBY_PATH}"
|
|
11
|
+
NEARBY_URL = PRIMARY_NEARBY_URL
|
|
12
|
+
HEALTH_URL = f"{API_BASE}/"
|
|
13
|
+
|
|
14
|
+
DEFAULT_TIMEOUT_SECONDS = 20
|
|
15
|
+
DEFAULT_USER_AGENT = "python-jejakmasjid/0.2.0 (+https://github.com/zubirjamal/python-jejakmasjid)"
|
|
16
|
+
|
|
17
|
+
PLACE_TYPES = ["masjid", "surau", "madrasah", "other"]
|
|
@@ -11,6 +11,25 @@ _TYPES = (
|
|
|
11
11
|
("madrasah", re.compile(r"^\W*madrasah?\b", re.I)),
|
|
12
12
|
)
|
|
13
13
|
|
|
14
|
+
DIRECTIONS = {
|
|
15
|
+
"N": 0.0,
|
|
16
|
+
"NNE": 22.5,
|
|
17
|
+
"NE": 45.0,
|
|
18
|
+
"ENE": 67.5,
|
|
19
|
+
"E": 90.0,
|
|
20
|
+
"ESE": 112.5,
|
|
21
|
+
"SE": 135.0,
|
|
22
|
+
"SSE": 157.5,
|
|
23
|
+
"S": 180.0,
|
|
24
|
+
"SSW": 202.5,
|
|
25
|
+
"SW": 225.0,
|
|
26
|
+
"WSW": 247.5,
|
|
27
|
+
"W": 270.0,
|
|
28
|
+
"WNW": 292.5,
|
|
29
|
+
"NW": 315.0,
|
|
30
|
+
"NNW": 337.5,
|
|
31
|
+
}
|
|
32
|
+
|
|
14
33
|
|
|
15
34
|
def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
16
35
|
"""Great-circle distance in kilometers using the Haversine formula."""
|
|
@@ -21,6 +40,28 @@ def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
|
21
40
|
return 2 * r * math.asin(math.sqrt(a))
|
|
22
41
|
|
|
23
42
|
|
|
43
|
+
def project_coordinates(
|
|
44
|
+
lat: float, lon: float, distance_m: float, direction: str | None
|
|
45
|
+
) -> tuple[float, float]:
|
|
46
|
+
"""Calculate target coordinates given origin, distance in meters, and compass direction."""
|
|
47
|
+
bearing_deg = DIRECTIONS.get(str(direction or "N").upper(), 0.0)
|
|
48
|
+
bearing_rad = math.radians(bearing_deg)
|
|
49
|
+
d = distance_m / 1000.0
|
|
50
|
+
r = 6371.0088
|
|
51
|
+
lat1 = math.radians(lat)
|
|
52
|
+
lon1 = math.radians(lon)
|
|
53
|
+
|
|
54
|
+
lat2 = math.asin(
|
|
55
|
+
math.sin(lat1) * math.cos(d / r)
|
|
56
|
+
+ math.cos(lat1) * math.sin(d / r) * math.cos(bearing_rad)
|
|
57
|
+
)
|
|
58
|
+
lon2 = lon1 + math.atan2(
|
|
59
|
+
math.sin(bearing_rad) * math.sin(d / r) * math.cos(lat1),
|
|
60
|
+
math.cos(d / r) - math.sin(lat1) * math.sin(lat2),
|
|
61
|
+
)
|
|
62
|
+
return round(math.degrees(lat2), 6), round(math.degrees(lon2), 6)
|
|
63
|
+
|
|
64
|
+
|
|
24
65
|
def type_from_payload(raw: Any) -> str | None:
|
|
25
66
|
"""Map the API's own type field to ours, if it sends one; None when absent or unknown."""
|
|
26
67
|
if not isinstance(raw, str) or not raw.strip():
|
|
@@ -51,7 +92,6 @@ def rank(places: list[dict[str, Any]], lat: float, lon: float) -> list[dict[str,
|
|
|
51
92
|
"""Places with distance_km from (lat, lon), sorted nearest first."""
|
|
52
93
|
out = []
|
|
53
94
|
for p in places:
|
|
54
|
-
# If the API already calculated distance, use it unless re-ranking from a different point
|
|
55
95
|
dist = p.get("distance_km")
|
|
56
96
|
if dist is None:
|
|
57
97
|
dist = round(haversine_km(lat, lon, p["latitude"], p["longitude"]), 2)
|
|
@@ -16,6 +16,9 @@ class Place:
|
|
|
16
16
|
longitude: float
|
|
17
17
|
kursus_haji: bool = False
|
|
18
18
|
distance_km: float | None = None
|
|
19
|
+
distance_m: int | None = None
|
|
20
|
+
direction: str | None = None
|
|
21
|
+
url: str | None = None
|
|
19
22
|
district_name: str | None = None
|
|
20
23
|
state_name: str | None = None
|
|
21
24
|
checkin_radius_m: int | None = None
|
|
@@ -34,6 +37,12 @@ class Place:
|
|
|
34
37
|
}
|
|
35
38
|
if self.distance_km is not None:
|
|
36
39
|
res["distance_km"] = self.distance_km
|
|
40
|
+
if self.distance_m is not None:
|
|
41
|
+
res["distance_m"] = self.distance_m
|
|
42
|
+
if self.direction is not None:
|
|
43
|
+
res["direction"] = self.direction
|
|
44
|
+
if self.url is not None:
|
|
45
|
+
res["url"] = self.url
|
|
37
46
|
if self.district_name is not None:
|
|
38
47
|
res["district_name"] = self.district_name
|
|
39
48
|
if self.state_name is not None:
|
|
@@ -57,6 +66,9 @@ class Place:
|
|
|
57
66
|
longitude=float(data["longitude"]),
|
|
58
67
|
kursus_haji=bool(data.get("kursus_haji", False)),
|
|
59
68
|
distance_km=float(data["distance_km"]) if data.get("distance_km") is not None else None,
|
|
69
|
+
distance_m=int(data["distance_m"]) if data.get("distance_m") is not None else None,
|
|
70
|
+
direction=data.get("direction"),
|
|
71
|
+
url=data.get("url"),
|
|
60
72
|
district_name=data.get("district_name"),
|
|
61
73
|
state_name=data.get("state_name"),
|
|
62
74
|
checkin_radius_m=int(data["checkin_radius_m"]) if data.get("checkin_radius_m") is not None else None,
|
|
@@ -0,0 +1,145 @@
|
|
|
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.constants import FALLBACK_NEARBY_URL, PRIMARY_NEARBY_URL
|
|
10
|
+
from jejakmasjid.exceptions import JejakMasjidError
|
|
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_HA_V1_PAYLOAD = {
|
|
38
|
+
"masjids": [
|
|
39
|
+
{
|
|
40
|
+
"id": "surau-kl-sentral-kuala-lumpur",
|
|
41
|
+
"name": "Surau KL Sentral",
|
|
42
|
+
"type": "surau",
|
|
43
|
+
"distance_m": 520,
|
|
44
|
+
"direction": "S",
|
|
45
|
+
"url": "https://jejakmasjid.my/masjid/surau-kl-sentral-kuala-lumpur",
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"id": "masjid-negara-kuala-lumpur",
|
|
49
|
+
"name": "MASJID NEGARA",
|
|
50
|
+
"type": "masjid",
|
|
51
|
+
"distance_m": 590,
|
|
52
|
+
"direction": "NE",
|
|
53
|
+
"url": "https://jejakmasjid.my/masjid/masjid-negara-kuala-lumpur",
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
"count": 2,
|
|
57
|
+
"radius_km": 5,
|
|
58
|
+
"attribution": "Masjid data © Jejak Masjid (jejakmasjid.my)",
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_parse_legacy_places():
|
|
63
|
+
places = parse_places(MOCK_LEGACY_PAYLOAD)
|
|
64
|
+
assert len(places) == 2
|
|
65
|
+
assert places[0]["id"] == "place-1"
|
|
66
|
+
assert places[0]["name"] == "Surau Ar-Raudhah"
|
|
67
|
+
assert places[0]["type"] == "surau"
|
|
68
|
+
assert places[0]["kursus_haji"] is False
|
|
69
|
+
assert places[1]["id"] == "place-2"
|
|
70
|
+
assert places[1]["type"] == "masjid"
|
|
71
|
+
assert places[1]["kursus_haji"] is True
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_parse_ha_v1_masjids():
|
|
75
|
+
places = parse_places(MOCK_HA_V1_PAYLOAD, origin_lat=3.1390, origin_lon=101.6869)
|
|
76
|
+
assert len(places) == 2
|
|
77
|
+
p1 = places[0]
|
|
78
|
+
assert p1["id"] == "surau-kl-sentral-kuala-lumpur"
|
|
79
|
+
assert p1["name"] == "Surau KL Sentral"
|
|
80
|
+
assert p1["type"] == "surau"
|
|
81
|
+
assert p1["distance_m"] == 520
|
|
82
|
+
assert p1["distance_km"] == 0.52
|
|
83
|
+
assert p1["direction"] == "S"
|
|
84
|
+
assert p1["url"] == "https://jejakmasjid.my/masjid/surau-kl-sentral-kuala-lumpur"
|
|
85
|
+
# Verify projected coordinates
|
|
86
|
+
assert p1["latitude"] < 3.1390
|
|
87
|
+
|
|
88
|
+
p2 = places[1]
|
|
89
|
+
assert p2["id"] == "masjid-negara-kuala-lumpur"
|
|
90
|
+
assert p2["type"] == "masjid"
|
|
91
|
+
assert p2["distance_m"] == 590
|
|
92
|
+
assert p2["distance_km"] == 0.59
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def test_async_fetch_nearby_primary_success():
|
|
96
|
+
mock_resp = AsyncMock()
|
|
97
|
+
mock_resp.status = 200
|
|
98
|
+
mock_resp.json = AsyncMock(return_value=MOCK_HA_V1_PAYLOAD)
|
|
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.1390, 101.6869, 5)
|
|
104
|
+
assert len(places) == 2
|
|
105
|
+
assert places[0]["id"] == "surau-kl-sentral-kuala-lumpur"
|
|
106
|
+
|
|
107
|
+
# Verify primary URL was called
|
|
108
|
+
call_args = mock_session.get.call_args_list[0]
|
|
109
|
+
assert call_args[0][0] == PRIMARY_NEARBY_URL
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def test_async_fetch_nearby_fallback_on_404():
|
|
113
|
+
# 1st call (primary) -> 404, 2nd call (fallback) -> 200
|
|
114
|
+
resp_404 = AsyncMock()
|
|
115
|
+
resp_404.status = 404
|
|
116
|
+
|
|
117
|
+
resp_200 = AsyncMock()
|
|
118
|
+
resp_200.status = 200
|
|
119
|
+
resp_200.json = AsyncMock(return_value=MOCK_LEGACY_PAYLOAD)
|
|
120
|
+
|
|
121
|
+
mock_session = MagicMock()
|
|
122
|
+
mock_session.get.return_value.__aenter__.side_effect = [resp_404, resp_200]
|
|
123
|
+
|
|
124
|
+
places = await async_fetch_nearby(mock_session, 3.02, 101.79, 3)
|
|
125
|
+
assert len(places) == 2
|
|
126
|
+
assert places[0]["id"] == "place-1"
|
|
127
|
+
|
|
128
|
+
# Verify both URLs were attempted
|
|
129
|
+
assert mock_session.get.call_count == 2
|
|
130
|
+
assert mock_session.get.call_args_list[0][0][0] == PRIMARY_NEARBY_URL
|
|
131
|
+
assert mock_session.get.call_args_list[1][0][0] == FALLBACK_NEARBY_URL
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def test_async_fetch_nearby_all_failed():
|
|
135
|
+
resp_404 = AsyncMock()
|
|
136
|
+
resp_404.status = 404
|
|
137
|
+
|
|
138
|
+
resp_500 = AsyncMock()
|
|
139
|
+
resp_500.status = 500
|
|
140
|
+
|
|
141
|
+
mock_session = MagicMock()
|
|
142
|
+
mock_session.get.return_value.__aenter__.side_effect = [resp_404, resp_500]
|
|
143
|
+
|
|
144
|
+
with pytest.raises(JejakMasjidError):
|
|
145
|
+
await async_fetch_nearby(mock_session, 3.02, 101.79, 3)
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
"""Tests for geographic and naming functions."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
-
from jejakmasjid.geo import
|
|
4
|
+
from jejakmasjid.geo import (
|
|
5
|
+
haversine_km,
|
|
6
|
+
place_type,
|
|
7
|
+
project_coordinates,
|
|
8
|
+
rank,
|
|
9
|
+
type_from_payload,
|
|
10
|
+
)
|
|
5
11
|
|
|
6
12
|
|
|
7
13
|
def test_haversine_same_point():
|
|
@@ -9,11 +15,17 @@ def test_haversine_same_point():
|
|
|
9
15
|
|
|
10
16
|
|
|
11
17
|
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
18
|
d = haversine_km(3.02, 101.79, 2.99, 101.79)
|
|
14
19
|
assert 3.0 < d < 3.6
|
|
15
20
|
|
|
16
21
|
|
|
22
|
+
def test_project_coordinates():
|
|
23
|
+
# 520m South of 3.1390 should decrease latitude slightly
|
|
24
|
+
lat2, lon2 = project_coordinates(3.1390, 101.6869, 520, "S")
|
|
25
|
+
assert lat2 < 3.1390
|
|
26
|
+
assert abs(lon2 - 101.6869) < 0.001
|
|
27
|
+
|
|
28
|
+
|
|
17
29
|
def test_place_type_detection():
|
|
18
30
|
assert place_type("Masjid Saujana Impian") == "masjid"
|
|
19
31
|
assert place_type("Mosque of Wilayah") == "masjid"
|
|
@@ -27,6 +39,7 @@ def test_place_type_detection():
|
|
|
27
39
|
def test_type_from_payload():
|
|
28
40
|
assert type_from_payload("Masjid") == "masjid"
|
|
29
41
|
assert type_from_payload("Surau") == "surau"
|
|
42
|
+
assert type_from_payload("mini surau") == "surau"
|
|
30
43
|
assert type_from_payload("Madrasah") == "madrasah"
|
|
31
44
|
assert type_from_payload("Unknown") == "other"
|
|
32
45
|
assert type_from_payload(None) is None
|
|
@@ -1,12 +0,0 @@
|
|
|
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"]
|
|
@@ -1,133 +0,0 @@
|
|
|
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"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/requires.txt
RENAMED
|
File without changes
|
{python_jejakmasjid-0.1.0 → python_jejakmasjid-0.2.0}/src/python_jejakmasjid.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|