python-getdoa 0.1.0__py3-none-any.whl

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.
getdoa/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """Asynchronous Python client for GetDoa."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .client import GetDoaClient
6
+ from .constants import (
7
+ API_BASE_URL,
8
+ API_ENDPOINT_LIST,
9
+ API_ENDPOINT_RANDOM,
10
+ DEFAULT_LIMIT,
11
+ DEFAULT_TIMEOUT,
12
+ )
13
+ from .exceptions import GetDoaConnectionError, GetDoaError, GetDoaResponseError
14
+ from .models import Doa
15
+
16
+ __all__ = [
17
+ "API_BASE_URL",
18
+ "API_ENDPOINT_LIST",
19
+ "API_ENDPOINT_RANDOM",
20
+ "DEFAULT_LIMIT",
21
+ "DEFAULT_TIMEOUT",
22
+ "Doa",
23
+ "GetDoaClient",
24
+ "GetDoaConnectionError",
25
+ "GetDoaError",
26
+ "GetDoaResponseError",
27
+ ]
getdoa/client.py ADDED
@@ -0,0 +1,111 @@
1
+ """Asynchronous client for GetDoa."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import random
7
+ from typing import Any
8
+
9
+ import aiohttp
10
+
11
+ from .constants import (
12
+ API_ENDPOINT_LIST,
13
+ API_ENDPOINT_RANDOM,
14
+ DEFAULT_LIMIT,
15
+ DEFAULT_TIMEOUT,
16
+ )
17
+ from .exceptions import GetDoaConnectionError, GetDoaResponseError
18
+ from .models import Doa
19
+
20
+
21
+ class GetDoaClient:
22
+ """Async client for fetching Doa from getdoa.com."""
23
+
24
+ def __init__(
25
+ self,
26
+ session: aiohttp.ClientSession | None = None,
27
+ timeout: float = DEFAULT_TIMEOUT,
28
+ ) -> None:
29
+ """Initialize the GetDoa client."""
30
+ self._session = session
31
+ self._close_session = False
32
+ self.timeout = timeout
33
+
34
+ async def _get_session(self) -> aiohttp.ClientSession:
35
+ """Get or create an aiohttp ClientSession."""
36
+ if self._session is None or self._session.closed:
37
+ self._session = aiohttp.ClientSession()
38
+ self._close_session = True
39
+ return self._session
40
+
41
+ async def close(self) -> None:
42
+ """Close the internal session if created by this client."""
43
+ if self._close_session and self._session and not self._session.closed:
44
+ await self._session.close()
45
+
46
+ async def __aenter__(self) -> GetDoaClient:
47
+ """Async context manager entry."""
48
+ return self
49
+
50
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
51
+ """Async context manager exit."""
52
+ await self.close()
53
+
54
+ async def _get_json(self, url: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
55
+ """Perform a GET request and return parsed JSON."""
56
+ session = await self._get_session()
57
+ try:
58
+ async with asyncio.timeout(self.timeout):
59
+ async with session.get(url, params=params) as resp:
60
+ if resp.status != 200:
61
+ raise GetDoaResponseError(f"GetDoa API returned HTTP {resp.status}")
62
+ payload = await resp.json()
63
+ except TimeoutError as err:
64
+ raise GetDoaConnectionError("Connection timed out while calling GetDoa API") from err
65
+ except aiohttp.ClientError as err:
66
+ raise GetDoaConnectionError(f"Network error while calling GetDoa API: {err}") from err
67
+
68
+ if not isinstance(payload, dict):
69
+ raise GetDoaResponseError("Unexpected response payload format from GetDoa API")
70
+ return payload
71
+
72
+ async def async_get_random(self) -> Doa:
73
+ """Fetch a random Doa from /api/doa/random."""
74
+ payload = await self._get_json(API_ENDPOINT_RANDOM)
75
+ data = payload.get("data")
76
+ if not isinstance(data, dict) or not data.get("slug"):
77
+ raise GetDoaResponseError("Missing 'data' object in GetDoa random response")
78
+ return Doa.from_api_payload(data)
79
+
80
+ async def async_get_list(self, page: int = 1, limit: int = DEFAULT_LIMIT) -> tuple[list[Doa], dict[str, Any]]:
81
+ """Fetch a paginated list of Doas from /api/doa."""
82
+ payload = await self._get_json(API_ENDPOINT_LIST, params={"page": page, "limit": limit})
83
+ items = payload.get("data")
84
+ if not isinstance(items, list):
85
+ raise GetDoaResponseError("Missing 'data' list in GetDoa list response")
86
+ doas = [Doa.from_api_payload(item) for item in items if isinstance(item, dict)]
87
+ pagination = payload.get("pagination") if isinstance(payload.get("pagination"), dict) else {}
88
+ return doas, pagination
89
+
90
+ async def async_get_all(self, limit: int = DEFAULT_LIMIT) -> list[Doa]:
91
+ """Fetch all Doas across all pages."""
92
+ all_doas: list[Doa] = []
93
+ page = 1
94
+ while True:
95
+ doas, pagination = await self.async_get_list(page=page, limit=limit)
96
+ all_doas.extend(doas)
97
+ if not pagination.get("hasNextPage"):
98
+ break
99
+ page += 1
100
+ return all_doas
101
+
102
+ async def async_get_random_by_category(self, category: str | None = None) -> Doa:
103
+ """Fetch a random Doa, optionally filtered by category name."""
104
+ if not category:
105
+ return await self.async_get_random()
106
+ all_doas = await self.async_get_all()
107
+ target = category.casefold()
108
+ matches = [d for d in all_doas if any(c.casefold() == target for c in d.category_names)]
109
+ if not matches:
110
+ raise GetDoaResponseError(f"No Doa found for category '{category}'")
111
+ return random.choice(matches)
getdoa/constants.py ADDED
@@ -0,0 +1,9 @@
1
+ """Constants for python-getdoa."""
2
+
3
+ from __future__ import annotations
4
+
5
+ API_BASE_URL = "https://getdoa.com"
6
+ API_ENDPOINT_LIST = f"{API_BASE_URL}/api/doa"
7
+ API_ENDPOINT_RANDOM = f"{API_BASE_URL}/api/doa/random"
8
+ DEFAULT_TIMEOUT = 15.0
9
+ DEFAULT_LIMIT = 100
getdoa/exceptions.py ADDED
@@ -0,0 +1,15 @@
1
+ """Exceptions for python-getdoa."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class GetDoaError(Exception):
7
+ """Base exception for GetDoa client errors."""
8
+
9
+
10
+ class GetDoaConnectionError(GetDoaError):
11
+ """Raised when a network or timeout error occurs."""
12
+
13
+
14
+ class GetDoaResponseError(GetDoaError):
15
+ """Raised when the GetDoa API returns an unexpected response."""
getdoa/models.py ADDED
@@ -0,0 +1,74 @@
1
+ """Data models for python-getdoa."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(slots=True, frozen=True)
10
+ class Doa:
11
+ """Represents a Doa (supplication) record from GetDoa."""
12
+
13
+ slug: str
14
+ name_my: str
15
+ name_en: str
16
+ content: str
17
+ reference_my: str
18
+ reference_en: str
19
+ meaning_my: str
20
+ meaning_en: str
21
+ category_names: tuple[str, ...]
22
+ description_my: str | None = None
23
+ description_en: str | None = None
24
+ context_my: str | None = None
25
+ context_en: str | None = None
26
+ content_hash: str = ""
27
+ created_at: str = ""
28
+ updated_at: str = ""
29
+
30
+ @classmethod
31
+ def from_api_payload(cls, payload: dict[str, Any]) -> Doa:
32
+ """Create a Doa instance from a GetDoa API item dictionary."""
33
+ raw_cats = payload.get("categoryNames") or []
34
+ categories = tuple(str(c) for c in raw_cats if c)
35
+
36
+ return cls(
37
+ slug=str(payload.get("slug") or ""),
38
+ name_my=str(payload.get("nameMy") or ""),
39
+ name_en=str(payload.get("nameEn") or ""),
40
+ content=str(payload.get("content") or ""),
41
+ reference_my=str(payload.get("referenceMy") or ""),
42
+ reference_en=str(payload.get("referenceEn") or ""),
43
+ meaning_my=str(payload.get("meaningMy") or ""),
44
+ meaning_en=str(payload.get("meaningEn") or ""),
45
+ category_names=categories,
46
+ description_my=payload.get("descriptionMy"),
47
+ description_en=payload.get("descriptionEn"),
48
+ context_my=payload.get("contextMy"),
49
+ context_en=payload.get("contextEn"),
50
+ content_hash=str(payload.get("contentHash") or ""),
51
+ created_at=str(payload.get("createdAt") or ""),
52
+ updated_at=str(payload.get("updatedAt") or ""),
53
+ )
54
+
55
+ def to_dict(self) -> dict[str, Any]:
56
+ """Serialize Doa to a JSON-friendly dictionary."""
57
+ return {
58
+ "slug": self.slug,
59
+ "nameMy": self.name_my,
60
+ "nameEn": self.name_en,
61
+ "content": self.content,
62
+ "referenceMy": self.reference_my,
63
+ "referenceEn": self.reference_en,
64
+ "meaningMy": self.meaning_my,
65
+ "meaningEn": self.meaning_en,
66
+ "categoryNames": list(self.category_names),
67
+ "descriptionMy": self.description_my,
68
+ "descriptionEn": self.description_en,
69
+ "contextMy": self.context_my,
70
+ "contextEn": self.context_en,
71
+ "contentHash": self.content_hash,
72
+ "createdAt": self.created_at,
73
+ "updatedAt": self.updated_at,
74
+ }
getdoa/py.typed ADDED
File without changes
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-getdoa
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Python client for GetDoa (getdoa.com) Islamic supplications API
5
+ Author: Zubir Jamal
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/zubirjamal/python-getdoa
8
+ Project-URL: Repository, https://github.com/zubirjamal/python-getdoa
9
+ Project-URL: Issues, https://github.com/zubirjamal/python-getdoa/issues
10
+ Keywords: doa,dua,supplication,islam,getdoa,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: Operating System :: OS Independent
17
+ Classifier: Topic :: Home Automation
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Intended Audience :: Developers
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: aiohttp>=3.9.0
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=8.0.0; extra == "test"
26
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
27
+ Requires-Dist: aresponses>=3.0.0; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # python-getdoa
31
+
32
+ Asynchronous Python client for [GetDoa](https://getdoa.com/) (`getdoa.com`), providing bilingual (English & Bahasa Melayu) Islamic supplications (*Doa*) with Arabic text and references.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install python-getdoa
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ import asyncio
44
+ from getdoa import GetDoaClient
45
+
46
+
47
+ async def main() -> None:
48
+ async with GetDoaClient() as client:
49
+ doa = await client.async_get_random()
50
+ print(doa.name_en)
51
+ print(doa.content)
52
+ print(doa.meaning_en)
53
+
54
+
55
+ asyncio.run(main())
56
+ ```
@@ -0,0 +1,11 @@
1
+ getdoa/__init__.py,sha256=dOPcNOtYiMb21cdwSD37mIGsc_BEoyOvsh0-rbGEkwE,589
2
+ getdoa/client.py,sha256=8APOW52Vxk641y1EE5wqRFsu8pxug3IcmA_NV2j65to,4478
3
+ getdoa/constants.py,sha256=UvUW6ivgppoV1tT0C4tFdGgdBd94aCKnxhS0UdZ_H5s,252
4
+ getdoa/exceptions.py,sha256=iFpwwnveU-9YGADitbiK_mzAsH5tBNwbdebFDGhYSlk,367
5
+ getdoa/models.py,sha256=mPw6AxO90MzOTbz7kf7qe_Oc8vr10wEM5Tx12IiqOBA,2653
6
+ getdoa/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ python_getdoa-0.1.0.dist-info/licenses/LICENSE,sha256=CV9UcjHZBMuVjUPCSgOJpqCp8L0ekkcK1UAomLpdW9Y,1068
8
+ python_getdoa-0.1.0.dist-info/METADATA,sha256=qAEQNuAuVZcYbxTzMDZPvrBTEI1UMEn5-zcyUzLJdak,1770
9
+ python_getdoa-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ python_getdoa-0.1.0.dist-info/top_level.txt,sha256=_CCupLhhbCxcU0nBPb5KOxmc_sUbXfibhCfDKl1FMZw,7
11
+ python_getdoa-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ getdoa