python-jejakmasjid 0.1.0__tar.gz → 0.3.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.3.0}/PKG-INFO +1 -1
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/pyproject.toml +1 -1
- python_jejakmasjid-0.3.0/src/jejakmasjid/__init__.py +80 -0
- python_jejakmasjid-0.3.0/src/jejakmasjid/client.py +370 -0
- python_jejakmasjid-0.3.0/src/jejakmasjid/constants.py +25 -0
- python_jejakmasjid-0.3.0/src/jejakmasjid/exceptions.py +14 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/geo.py +41 -1
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/models.py +12 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/PKG-INFO +1 -1
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/SOURCES.txt +1 -0
- python_jejakmasjid-0.3.0/tests/test_auth.py +158 -0
- python_jejakmasjid-0.3.0/tests/test_client.py +145 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/tests/test_geo.py +15 -2
- python_jejakmasjid-0.1.0/src/jejakmasjid/__init__.py +0 -35
- python_jejakmasjid-0.1.0/src/jejakmasjid/client.py +0 -187
- python_jejakmasjid-0.1.0/src/jejakmasjid/constants.py +0 -12
- python_jejakmasjid-0.1.0/src/jejakmasjid/exceptions.py +0 -6
- python_jejakmasjid-0.1.0/tests/test_client.py +0 -133
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/LICENSE +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/README.md +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/setup.cfg +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/__main__.py +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/jejakmasjid/cli.py +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/dependency_links.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/entry_points.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/requires.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/top_level.txt +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/tests/test_cli.py +0 -0
- {python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/tests/test_models.py +0 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Asynchronous Python client for Jejak Masjid."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .client import (
|
|
5
|
+
JejakMasjidClient,
|
|
6
|
+
async_fetch_nearby,
|
|
7
|
+
async_fetch_user_profile,
|
|
8
|
+
async_send_email_otp,
|
|
9
|
+
async_verify_email_otp,
|
|
10
|
+
parse_places,
|
|
11
|
+
)
|
|
12
|
+
from .constants import (
|
|
13
|
+
API_BASE,
|
|
14
|
+
AUTH_SEND_OTP_PATH,
|
|
15
|
+
AUTH_SEND_OTP_URL,
|
|
16
|
+
AUTH_VERIFY_OTP_PATH,
|
|
17
|
+
AUTH_VERIFY_OTP_URL,
|
|
18
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
19
|
+
DEFAULT_USER_AGENT,
|
|
20
|
+
FALLBACK_NEARBY_URL,
|
|
21
|
+
HA_V1_NEARBY_PATH,
|
|
22
|
+
HEALTH_URL,
|
|
23
|
+
LEGACY_NEARBY_PATH,
|
|
24
|
+
NEARBY_PATH,
|
|
25
|
+
NEARBY_URL,
|
|
26
|
+
PLACE_TYPES,
|
|
27
|
+
PRIMARY_NEARBY_URL,
|
|
28
|
+
USER_PROFILE_PATH,
|
|
29
|
+
USER_PROFILE_URL,
|
|
30
|
+
)
|
|
31
|
+
from .exceptions import (
|
|
32
|
+
JejakMasjidAuthError,
|
|
33
|
+
JejakMasjidConnectionError,
|
|
34
|
+
JejakMasjidError,
|
|
35
|
+
)
|
|
36
|
+
from .geo import (
|
|
37
|
+
DIRECTIONS,
|
|
38
|
+
haversine_km,
|
|
39
|
+
place_type,
|
|
40
|
+
project_coordinates,
|
|
41
|
+
rank,
|
|
42
|
+
type_from_payload,
|
|
43
|
+
)
|
|
44
|
+
from .models import Place
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"API_BASE",
|
|
48
|
+
"AUTH_SEND_OTP_PATH",
|
|
49
|
+
"AUTH_SEND_OTP_URL",
|
|
50
|
+
"AUTH_VERIFY_OTP_PATH",
|
|
51
|
+
"AUTH_VERIFY_OTP_URL",
|
|
52
|
+
"DEFAULT_TIMEOUT_SECONDS",
|
|
53
|
+
"DEFAULT_USER_AGENT",
|
|
54
|
+
"DIRECTIONS",
|
|
55
|
+
"FALLBACK_NEARBY_URL",
|
|
56
|
+
"HA_V1_NEARBY_PATH",
|
|
57
|
+
"HEALTH_URL",
|
|
58
|
+
"JejakMasjidAuthError",
|
|
59
|
+
"JejakMasjidClient",
|
|
60
|
+
"JejakMasjidConnectionError",
|
|
61
|
+
"JejakMasjidError",
|
|
62
|
+
"LEGACY_NEARBY_PATH",
|
|
63
|
+
"NEARBY_PATH",
|
|
64
|
+
"NEARBY_URL",
|
|
65
|
+
"PLACE_TYPES",
|
|
66
|
+
"PRIMARY_NEARBY_URL",
|
|
67
|
+
"Place",
|
|
68
|
+
"USER_PROFILE_PATH",
|
|
69
|
+
"USER_PROFILE_URL",
|
|
70
|
+
"async_fetch_nearby",
|
|
71
|
+
"async_fetch_user_profile",
|
|
72
|
+
"async_send_email_otp",
|
|
73
|
+
"async_verify_email_otp",
|
|
74
|
+
"haversine_km",
|
|
75
|
+
"parse_places",
|
|
76
|
+
"place_type",
|
|
77
|
+
"project_coordinates",
|
|
78
|
+
"rank",
|
|
79
|
+
"type_from_payload",
|
|
80
|
+
]
|
|
@@ -0,0 +1,370 @@
|
|
|
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 (
|
|
10
|
+
AUTH_SEND_OTP_URL,
|
|
11
|
+
AUTH_VERIFY_OTP_URL,
|
|
12
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
13
|
+
DEFAULT_USER_AGENT,
|
|
14
|
+
FALLBACK_NEARBY_URL,
|
|
15
|
+
PRIMARY_NEARBY_URL,
|
|
16
|
+
USER_PROFILE_URL,
|
|
17
|
+
)
|
|
18
|
+
from .exceptions import JejakMasjidAuthError, JejakMasjidConnectionError, JejakMasjidError
|
|
19
|
+
from .geo import place_type, project_coordinates, type_from_payload
|
|
20
|
+
|
|
21
|
+
_LOGGER = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _parse_place_item(
|
|
25
|
+
item: dict[str, Any], origin_lat: float | None = None, origin_lon: float | None = None
|
|
26
|
+
) -> dict[str, Any] | None:
|
|
27
|
+
"""Parse a single item from dedicated HA v1 or mobile app JSON structures."""
|
|
28
|
+
try:
|
|
29
|
+
place_id = str(item.get("id") or item.get("masjidId"))
|
|
30
|
+
name = str(item.get("name") or "").strip()
|
|
31
|
+
|
|
32
|
+
# Extract or project coordinates
|
|
33
|
+
if item.get("lat") is not None or item.get("latitude") is not None:
|
|
34
|
+
lat = float(item.get("lat") or item.get("latitude"))
|
|
35
|
+
lon = float(item.get("lng") or item.get("longitude"))
|
|
36
|
+
elif origin_lat is not None and origin_lon is not None:
|
|
37
|
+
dist_val = float(item.get("distance_m") or item.get("distanceM") or 500)
|
|
38
|
+
dir_val = item.get("direction")
|
|
39
|
+
lat, lon = project_coordinates(origin_lat, origin_lon, dist_val, dir_val)
|
|
40
|
+
else:
|
|
41
|
+
lat, lon = 0.0, 0.0
|
|
42
|
+
|
|
43
|
+
# Calculate or extract distances
|
|
44
|
+
dist_m: int | None = None
|
|
45
|
+
dist_km: float | None = None
|
|
46
|
+
if item.get("distance_m") is not None:
|
|
47
|
+
dist_m = int(item["distance_m"])
|
|
48
|
+
dist_km = round(dist_m / 1000.0, 2)
|
|
49
|
+
elif item.get("distanceM") is not None:
|
|
50
|
+
dist_m = int(item["distanceM"])
|
|
51
|
+
dist_km = round(dist_m / 1000.0, 2)
|
|
52
|
+
elif item.get("distance") is not None:
|
|
53
|
+
dist_km = round(float(item["distance"]), 2)
|
|
54
|
+
dist_m = int(dist_km * 1000)
|
|
55
|
+
elif item.get("distance_km") is not None:
|
|
56
|
+
dist_km = round(float(item["distance_km"]), 2)
|
|
57
|
+
dist_m = int(dist_km * 1000)
|
|
58
|
+
|
|
59
|
+
place: dict[str, Any] = {
|
|
60
|
+
"id": place_id,
|
|
61
|
+
"name": name,
|
|
62
|
+
"type": type_from_payload(item.get("type")) or place_type(name),
|
|
63
|
+
"latitude": lat,
|
|
64
|
+
"longitude": lon,
|
|
65
|
+
"kursus_haji": bool(
|
|
66
|
+
item.get("hasKursusAsasHaji")
|
|
67
|
+
or item.get("has_kursus_asas_haji")
|
|
68
|
+
or item.get("kursus_haji")
|
|
69
|
+
),
|
|
70
|
+
}
|
|
71
|
+
if dist_km is not None:
|
|
72
|
+
place["distance_km"] = dist_km
|
|
73
|
+
if dist_m is not None:
|
|
74
|
+
place["distance_m"] = dist_m
|
|
75
|
+
if item.get("direction"):
|
|
76
|
+
place["direction"] = str(item["direction"])
|
|
77
|
+
if item.get("url"):
|
|
78
|
+
place["url"] = str(item["url"])
|
|
79
|
+
if item.get("districtName"):
|
|
80
|
+
place["district_name"] = str(item["districtName"])
|
|
81
|
+
if item.get("stateName"):
|
|
82
|
+
place["state_name"] = str(item["stateName"])
|
|
83
|
+
if item.get("checkinRadiusM") is not None:
|
|
84
|
+
place["checkin_radius_m"] = int(item["checkinRadiusM"])
|
|
85
|
+
if item.get("canCheckin") is not None:
|
|
86
|
+
place["can_checkin"] = bool(item["canCheckin"])
|
|
87
|
+
if item.get("avgRating") is not None:
|
|
88
|
+
place["avg_rating"] = float(item["avgRating"])
|
|
89
|
+
|
|
90
|
+
return place
|
|
91
|
+
except (KeyError, TypeError, ValueError):
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse_places(
|
|
96
|
+
payload: Any, origin_lat: float | None = None, origin_lon: float | None = None
|
|
97
|
+
) -> list[dict[str, Any]]:
|
|
98
|
+
"""Parse Jejak Masjid response payload supporting dedicated HA v1, REST arrays, and GeoJSON."""
|
|
99
|
+
places: list[dict[str, Any]] = []
|
|
100
|
+
|
|
101
|
+
# 1. Dedicated HA v1 format: {"masjids": [...], "count": 5, ...}
|
|
102
|
+
if isinstance(payload, dict) and "masjids" in payload:
|
|
103
|
+
for item in payload.get("masjids") or []:
|
|
104
|
+
if isinstance(item, dict):
|
|
105
|
+
p = _parse_place_item(item, origin_lat, origin_lon)
|
|
106
|
+
if p:
|
|
107
|
+
places.append(p)
|
|
108
|
+
return places
|
|
109
|
+
|
|
110
|
+
# 2. Direct list of items: [{...}, {...}]
|
|
111
|
+
if isinstance(payload, list):
|
|
112
|
+
for item in payload:
|
|
113
|
+
if isinstance(item, dict):
|
|
114
|
+
p = _parse_place_item(item, origin_lat, origin_lon)
|
|
115
|
+
if p:
|
|
116
|
+
places.append(p)
|
|
117
|
+
return places
|
|
118
|
+
|
|
119
|
+
if not isinstance(payload, dict):
|
|
120
|
+
raise JejakMasjidError("Unexpected response from Jejak Masjid (not a JSON object or array)")
|
|
121
|
+
|
|
122
|
+
# 3. Legacy GeoJSON format: {"type": "FeatureCollection", ...}
|
|
123
|
+
if payload.get("type") == "FeatureCollection":
|
|
124
|
+
for feature in payload.get("features") or []:
|
|
125
|
+
try:
|
|
126
|
+
lon, lat = feature["geometry"]["coordinates"][:2]
|
|
127
|
+
props = feature.get("properties") or {}
|
|
128
|
+
name = str(props.get("name") or "").strip()
|
|
129
|
+
places.append(
|
|
130
|
+
{
|
|
131
|
+
"id": str(props["id"]),
|
|
132
|
+
"name": name,
|
|
133
|
+
"type": type_from_payload(props.get("type")) or place_type(name),
|
|
134
|
+
"latitude": float(lat),
|
|
135
|
+
"longitude": float(lon),
|
|
136
|
+
"kursus_haji": bool(props.get("has_kursus_asas_haji")),
|
|
137
|
+
}
|
|
138
|
+
)
|
|
139
|
+
except (KeyError, TypeError, ValueError):
|
|
140
|
+
continue
|
|
141
|
+
return places
|
|
142
|
+
|
|
143
|
+
# 4. Generic wrapped list: {"data": [...]} or {"places": [...]}
|
|
144
|
+
wrapped_list = payload.get("data") or payload.get("places")
|
|
145
|
+
if isinstance(wrapped_list, list):
|
|
146
|
+
for item in wrapped_list:
|
|
147
|
+
if isinstance(item, dict):
|
|
148
|
+
p = _parse_place_item(item, origin_lat, origin_lon)
|
|
149
|
+
if p:
|
|
150
|
+
places.append(p)
|
|
151
|
+
return places
|
|
152
|
+
|
|
153
|
+
raise JejakMasjidError("Unrecognized Jejak Masjid payload format")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
async def async_fetch_nearby(
|
|
157
|
+
session: aiohttp.ClientSession,
|
|
158
|
+
lat: float,
|
|
159
|
+
lon: float,
|
|
160
|
+
radius_km: int = 5,
|
|
161
|
+
*,
|
|
162
|
+
endpoint_url: str | None = None,
|
|
163
|
+
user_agent: str | None = None,
|
|
164
|
+
headers: dict[str, str] | None = None,
|
|
165
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
166
|
+
) -> list[dict[str, Any]]:
|
|
167
|
+
"""Fetch places within radius_km of a coordinate point with fallback support."""
|
|
168
|
+
primary_url = endpoint_url or PRIMARY_NEARBY_URL
|
|
169
|
+
req_headers = {"User-Agent": user_agent or DEFAULT_USER_AGENT}
|
|
170
|
+
if headers:
|
|
171
|
+
req_headers.update(headers)
|
|
172
|
+
|
|
173
|
+
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
|
|
174
|
+
|
|
175
|
+
# 1. Attempt primary dedicated endpoint
|
|
176
|
+
params = {"lat": f"{lat:.4f}", "lng": f"{lon:.4f}"}
|
|
177
|
+
try:
|
|
178
|
+
async with session.get(primary_url, params=params, headers=req_headers, timeout=timeout) as resp:
|
|
179
|
+
if resp.status == 200:
|
|
180
|
+
payload = await resp.json(content_type=None)
|
|
181
|
+
return parse_places(payload, origin_lat=lat, origin_lon=lon)
|
|
182
|
+
if resp.status != 404 or endpoint_url:
|
|
183
|
+
raise JejakMasjidError(f"Jejak Masjid answered HTTP {resp.status}")
|
|
184
|
+
_LOGGER.warning("Dedicated endpoint returned 404, falling back to legacy endpoint")
|
|
185
|
+
except (aiohttp.ClientError, TimeoutError, ValueError) as err:
|
|
186
|
+
if endpoint_url:
|
|
187
|
+
raise JejakMasjidError(f"Cannot reach Jejak Masjid: {err}") from err
|
|
188
|
+
_LOGGER.warning("Dedicated endpoint failed (%s), falling back to legacy endpoint", err)
|
|
189
|
+
|
|
190
|
+
# 2. Fallback to legacy endpoint if primary returned 404 or connection failed
|
|
191
|
+
fallback_params = {"lat": f"{lat:.3f}", "lng": f"{lon:.3f}", "radius": str(radius_km)}
|
|
192
|
+
try:
|
|
193
|
+
async with session.get(
|
|
194
|
+
FALLBACK_NEARBY_URL, params=fallback_params, headers=req_headers, timeout=timeout
|
|
195
|
+
) as resp:
|
|
196
|
+
if resp.status != 200:
|
|
197
|
+
raise JejakMasjidError(f"Jejak Masjid fallback answered HTTP {resp.status}")
|
|
198
|
+
payload = await resp.json(content_type=None)
|
|
199
|
+
return parse_places(payload, origin_lat=lat, origin_lon=lon)
|
|
200
|
+
except (aiohttp.ClientError, TimeoutError, ValueError) as err:
|
|
201
|
+
raise JejakMasjidError(f"Cannot reach Jejak Masjid (fallback): {err}") from err
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class JejakMasjidClient:
|
|
205
|
+
"""Configurable client instance for Jejak Masjid API."""
|
|
206
|
+
|
|
207
|
+
def __init__(
|
|
208
|
+
self,
|
|
209
|
+
session: aiohttp.ClientSession,
|
|
210
|
+
*,
|
|
211
|
+
endpoint_url: str = PRIMARY_NEARBY_URL,
|
|
212
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
213
|
+
api_key: str | None = None,
|
|
214
|
+
) -> None:
|
|
215
|
+
self._session = session
|
|
216
|
+
self._endpoint_url = endpoint_url
|
|
217
|
+
self._user_agent = user_agent
|
|
218
|
+
self._api_key = api_key
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def endpoint_url(self) -> str:
|
|
222
|
+
return self._endpoint_url
|
|
223
|
+
|
|
224
|
+
def set_endpoint_url(self, url: str) -> None:
|
|
225
|
+
"""Allow dynamically switching to a dedicated endpoint."""
|
|
226
|
+
self._endpoint_url = url
|
|
227
|
+
|
|
228
|
+
async def fetch_nearby(self, lat: float, lon: float, radius_km: int = 5) -> list[dict[str, Any]]:
|
|
229
|
+
"""Fetch nearby places using configured client options."""
|
|
230
|
+
headers = {}
|
|
231
|
+
if self._api_key:
|
|
232
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
233
|
+
return await async_fetch_nearby(
|
|
234
|
+
self._session,
|
|
235
|
+
lat,
|
|
236
|
+
lon,
|
|
237
|
+
radius_km,
|
|
238
|
+
endpoint_url=self._endpoint_url,
|
|
239
|
+
user_agent=self._user_agent,
|
|
240
|
+
headers=headers,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
async def send_email_otp(self, email: str) -> dict[str, Any]:
|
|
244
|
+
"""Request email OTP verification for user login."""
|
|
245
|
+
return await async_send_email_otp(
|
|
246
|
+
self._session,
|
|
247
|
+
email,
|
|
248
|
+
user_agent=self._user_agent,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
async def verify_email_otp(self, email: str, otp: str) -> str:
|
|
252
|
+
"""Verify emailed OTP and save session token."""
|
|
253
|
+
_data, token = await async_verify_email_otp(
|
|
254
|
+
self._session,
|
|
255
|
+
email,
|
|
256
|
+
otp,
|
|
257
|
+
user_agent=self._user_agent,
|
|
258
|
+
)
|
|
259
|
+
self._api_key = token
|
|
260
|
+
return token
|
|
261
|
+
|
|
262
|
+
async def fetch_user_profile(self, token: str | None = None) -> dict[str, Any]:
|
|
263
|
+
"""Fetch user profile and journey statistics."""
|
|
264
|
+
auth_token = token or self._api_key
|
|
265
|
+
if not auth_token:
|
|
266
|
+
raise JejakMasjidAuthError("No authentication token provided or configured")
|
|
267
|
+
return await async_fetch_user_profile(
|
|
268
|
+
self._session,
|
|
269
|
+
auth_token,
|
|
270
|
+
user_agent=self._user_agent,
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
async def async_send_email_otp(
|
|
275
|
+
session: aiohttp.ClientSession,
|
|
276
|
+
email: str,
|
|
277
|
+
*,
|
|
278
|
+
endpoint_url: str = AUTH_SEND_OTP_URL,
|
|
279
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
280
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
281
|
+
) -> dict[str, Any]:
|
|
282
|
+
"""Request an email verification code for user authentication."""
|
|
283
|
+
headers = {"User-Agent": user_agent}
|
|
284
|
+
payload = {"email": email.strip().lower(), "type": "sign-in"}
|
|
285
|
+
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
|
|
286
|
+
|
|
287
|
+
try:
|
|
288
|
+
async with session.post(endpoint_url, json=payload, headers=headers, timeout=timeout) as resp:
|
|
289
|
+
data = await resp.json(content_type=None) or {}
|
|
290
|
+
if resp.status >= 400:
|
|
291
|
+
raise JejakMasjidAuthError(
|
|
292
|
+
f"Send OTP failed with HTTP {resp.status}: {data.get('message') or data.get('code') or resp.status}"
|
|
293
|
+
)
|
|
294
|
+
return data
|
|
295
|
+
except aiohttp.ClientError as err:
|
|
296
|
+
raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid auth service: {err}") from err
|
|
297
|
+
except TimeoutError as err:
|
|
298
|
+
raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid auth service: {err}") from err
|
|
299
|
+
except ValueError as err:
|
|
300
|
+
raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
async def async_verify_email_otp(
|
|
304
|
+
session: aiohttp.ClientSession,
|
|
305
|
+
email: str,
|
|
306
|
+
otp: str,
|
|
307
|
+
*,
|
|
308
|
+
endpoint_url: str = AUTH_VERIFY_OTP_URL,
|
|
309
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
310
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
311
|
+
) -> tuple[dict[str, Any], str]:
|
|
312
|
+
"""Exchange emailed OTP for a user session token.
|
|
313
|
+
|
|
314
|
+
Returns tuple of (response_json, token_string).
|
|
315
|
+
"""
|
|
316
|
+
headers = {"User-Agent": user_agent}
|
|
317
|
+
payload = {"email": email.strip().lower(), "otp": otp.strip()}
|
|
318
|
+
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
|
|
319
|
+
|
|
320
|
+
try:
|
|
321
|
+
async with session.post(endpoint_url, json=payload, headers=headers, timeout=timeout) as resp:
|
|
322
|
+
data = await resp.json(content_type=None) or {}
|
|
323
|
+
if resp.status >= 400:
|
|
324
|
+
raise JejakMasjidAuthError(
|
|
325
|
+
f"Invalid OTP or authentication refused (HTTP {resp.status}): {data.get('message') or data.get('code') or resp.status}"
|
|
326
|
+
)
|
|
327
|
+
header_token = resp.headers.get("set-auth-token")
|
|
328
|
+
token = header_token or data.get("token")
|
|
329
|
+
if not token:
|
|
330
|
+
raise JejakMasjidAuthError("No authentication token returned by Jejak Masjid")
|
|
331
|
+
return data, token
|
|
332
|
+
except aiohttp.ClientError as err:
|
|
333
|
+
raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid auth service: {err}") from err
|
|
334
|
+
except TimeoutError as err:
|
|
335
|
+
raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid auth service: {err}") from err
|
|
336
|
+
except ValueError as err:
|
|
337
|
+
raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
async def async_fetch_user_profile(
|
|
341
|
+
session: aiohttp.ClientSession,
|
|
342
|
+
token: str,
|
|
343
|
+
*,
|
|
344
|
+
endpoint_url: str = USER_PROFILE_URL,
|
|
345
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
346
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
347
|
+
) -> dict[str, Any]:
|
|
348
|
+
"""Fetch user profile, journey statistics, streaks, and achievements."""
|
|
349
|
+
headers = {
|
|
350
|
+
"User-Agent": user_agent,
|
|
351
|
+
"Authorization": f"Bearer {token.strip()}",
|
|
352
|
+
}
|
|
353
|
+
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
|
|
354
|
+
|
|
355
|
+
try:
|
|
356
|
+
async with session.get(endpoint_url, headers=headers, timeout=timeout) as resp:
|
|
357
|
+
if resp.status == 401:
|
|
358
|
+
raise JejakMasjidAuthError("Jejak Masjid session token expired or revoked (HTTP 401)")
|
|
359
|
+
data = await resp.json(content_type=None) or {}
|
|
360
|
+
if resp.status >= 400:
|
|
361
|
+
raise JejakMasjidError(
|
|
362
|
+
f"Profile request answered HTTP {resp.status}: {data.get('message') or data.get('code') or resp.status}"
|
|
363
|
+
)
|
|
364
|
+
return data
|
|
365
|
+
except aiohttp.ClientError as err:
|
|
366
|
+
raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid profile service: {err}") from err
|
|
367
|
+
except TimeoutError as err:
|
|
368
|
+
raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid profile service: {err}") from err
|
|
369
|
+
except ValueError as err:
|
|
370
|
+
raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
|
|
@@ -0,0 +1,25 @@
|
|
|
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.3.0 (+https://github.com/zubirjamal/python-jejakmasjid)"
|
|
16
|
+
|
|
17
|
+
AUTH_SEND_OTP_PATH = "/api/auth/email-otp/send-verification-otp"
|
|
18
|
+
AUTH_VERIFY_OTP_PATH = "/api/auth/sign-in/email-otp"
|
|
19
|
+
USER_PROFILE_PATH = "/api/user/profile"
|
|
20
|
+
|
|
21
|
+
AUTH_SEND_OTP_URL = f"{API_BASE}{AUTH_SEND_OTP_PATH}"
|
|
22
|
+
AUTH_VERIFY_OTP_URL = f"{API_BASE}{AUTH_VERIFY_OTP_PATH}"
|
|
23
|
+
USER_PROFILE_URL = f"{API_BASE}{USER_PROFILE_PATH}"
|
|
24
|
+
|
|
25
|
+
PLACE_TYPES = ["masjid", "surau", "madrasah", "other"]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Exceptions for the Jejak Masjid client library."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class JejakMasjidError(Exception):
|
|
6
|
+
"""The API could not be reached or answered with something unexpected."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class JejakMasjidAuthError(JejakMasjidError):
|
|
10
|
+
"""Authentication failed or session token expired/invalid."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class JejakMasjidConnectionError(JejakMasjidError):
|
|
14
|
+
"""Network connection or timeout failure."""
|
|
@@ -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,
|
{python_jejakmasjid-0.1.0 → python_jejakmasjid-0.3.0}/src/python_jejakmasjid.egg-info/SOURCES.txt
RENAMED
|
@@ -15,6 +15,7 @@ src/python_jejakmasjid.egg-info/dependency_links.txt
|
|
|
15
15
|
src/python_jejakmasjid.egg-info/entry_points.txt
|
|
16
16
|
src/python_jejakmasjid.egg-info/requires.txt
|
|
17
17
|
src/python_jejakmasjid.egg-info/top_level.txt
|
|
18
|
+
tests/test_auth.py
|
|
18
19
|
tests/test_cli.py
|
|
19
20
|
tests/test_client.py
|
|
20
21
|
tests/test_geo.py
|