hosteday-python 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.
- hosteday/__init__.py +111 -0
- hosteday/_version.py +3 -0
- hosteday/auth/__init__.py +34 -0
- hosteday/auth/hosteday_auth.py +444 -0
- hosteday/auth/hosteday_auth_storage.py +130 -0
- hosteday/auth/hosteday_session.py +184 -0
- hosteday/auth/hosteday_token_provider.py +82 -0
- hosteday/auth/hosteday_user.py +223 -0
- hosteday/cli/__init__.py +5 -0
- hosteday/cli/setup.py +163 -0
- hosteday/config/__init__.py +15 -0
- hosteday/config/hosteday_config.py +576 -0
- hosteday/config/hosteday_option_keys.py +60 -0
- hosteday/config/hosteday_url_resolver.py +255 -0
- hosteday/connectivity/__init__.py +5 -0
- hosteday/connectivity/hosteday_connectivity.py +147 -0
- hosteday/exceptions.py +233 -0
- hosteday/features/__init__.py +5 -0
- hosteday/features/hosteday_features.py +78 -0
- hosteday/hosteday.py +346 -0
- hosteday/hosteday_client.py +579 -0
- hosteday/http/__init__.py +18 -0
- hosteday/http/hosteday_http_client.py +340 -0
- hosteday/http/hosteday_response_reader.py +171 -0
- hosteday/http/query_builder.py +204 -0
- hosteday/jobs/__init__.py +9 -0
- hosteday/jobs/hosteday_job_response.py +76 -0
- hosteday/jobs/hosteday_jobs_client.py +109 -0
- hosteday/notifications/__init__.py +13 -0
- hosteday/notifications/hosteday_notification_client.py +290 -0
- hosteday/notifications/hosteday_notification_response.py +79 -0
- hosteday/py.typed +1 -0
- hosteday/reactive/__init__.py +5 -0
- hosteday/reactive/observable_state.py +67 -0
- hosteday/realtime/__init__.py +31 -0
- hosteday/realtime/connection_state.py +14 -0
- hosteday/realtime/hosteday_channel.py +258 -0
- hosteday/realtime/hosteday_channel_auth.py +163 -0
- hosteday/realtime/hosteday_channel_type.py +68 -0
- hosteday/realtime/hosteday_realtime_client.py +790 -0
- hosteday/realtime/hosteday_realtime_event.py +130 -0
- hosteday/web/__init__.py +5 -0
- hosteday/web/server.py +637 -0
- hosteday_python/__init__.py +6 -0
- hosteday_python/py.typed +1 -0
- hosteday_python-0.1.0.dist-info/METADATA +205 -0
- hosteday_python-0.1.0.dist-info/RECORD +50 -0
- hosteday_python-0.1.0.dist-info/WHEEL +4 -0
- hosteday_python-0.1.0.dist-info/entry_points.txt +2 -0
- hosteday_python-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Single URL policy for HosteDay REST APIs, public static pages, storage media, and WebSockets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from urllib.parse import SplitResult, unquote, urlsplit, urlunsplit
|
|
7
|
+
|
|
8
|
+
_WHITESPACE_RE = re.compile(r"\s")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _origin_of(parts: SplitResult) -> str:
|
|
12
|
+
"""Computes the canonical HTTP(S) origin (scheme://host[:port]) without trailing slash."""
|
|
13
|
+
scheme = parts.scheme.lower()
|
|
14
|
+
host = (parts.hostname or "").lower()
|
|
15
|
+
if ":" in host and not host.startswith("["):
|
|
16
|
+
host = f"[{host}]"
|
|
17
|
+
port = parts.port
|
|
18
|
+
default_port = 443 if scheme == "https" else 80
|
|
19
|
+
if port is not None and port != default_port:
|
|
20
|
+
return f"{scheme}://{host}:{port}"
|
|
21
|
+
return f"{scheme}://{host}"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _http_uri(value: str) -> SplitResult:
|
|
25
|
+
text = value.strip()
|
|
26
|
+
if not text or _WHITESPACE_RE.search(text):
|
|
27
|
+
raise ValueError("A valid HTTP(S) domain or URL is required.")
|
|
28
|
+
|
|
29
|
+
candidate = text if "://" in text else f"https://{text}"
|
|
30
|
+
parsed = urlsplit(candidate)
|
|
31
|
+
|
|
32
|
+
scheme = parsed.scheme.lower()
|
|
33
|
+
if (
|
|
34
|
+
scheme not in {"http", "https"}
|
|
35
|
+
or not parsed.hostname
|
|
36
|
+
or parsed.username is not None
|
|
37
|
+
or parsed.password is not None
|
|
38
|
+
or parsed.query
|
|
39
|
+
or parsed.fragment
|
|
40
|
+
):
|
|
41
|
+
raise ValueError("A valid HTTP(S) domain or URL is required.")
|
|
42
|
+
|
|
43
|
+
# Force port validation (raises ValueError on invalid port numbers)
|
|
44
|
+
_ = parsed.port
|
|
45
|
+
return parsed
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _validate_raw_path(value: str) -> None:
|
|
49
|
+
path_only = value.split("?", 1)[0].split("#", 1)[0]
|
|
50
|
+
for part in path_only.split("/"):
|
|
51
|
+
if part in {".", ".."} or "\\" in part:
|
|
52
|
+
raise ValueError("Path traversal is not supported.")
|
|
53
|
+
decoded = unquote(part)
|
|
54
|
+
if decoded in {".", ".."} or "\\" in decoded or "/" in decoded:
|
|
55
|
+
raise ValueError("Path traversal is not supported.")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _segments(path: str) -> list[str]:
|
|
59
|
+
parts = [part for part in path.split("/") if part]
|
|
60
|
+
for part in parts:
|
|
61
|
+
if part in {".", ".."} or "\\" in part:
|
|
62
|
+
raise ValueError("Traversal and encoded path separators are not supported.")
|
|
63
|
+
decoded = unquote(part)
|
|
64
|
+
if decoded in {".", ".."} or "/" in decoded or "\\" in decoded:
|
|
65
|
+
raise ValueError("Traversal and encoded path separators are not supported.")
|
|
66
|
+
return parts
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class HostedayUrlResolver:
|
|
70
|
+
"""Enforces a single URL policy across REST, static pages, public media, and realtime."""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
*,
|
|
75
|
+
project_domain: str,
|
|
76
|
+
api_base_url: str | None = None,
|
|
77
|
+
) -> None:
|
|
78
|
+
self._host_origin: str = self.root(project_domain)
|
|
79
|
+
self._host_parts: SplitResult = urlsplit(self._host_origin)
|
|
80
|
+
self._api_parts: SplitResult = self._api_root(api_base_url or project_domain)
|
|
81
|
+
self._api_origin: str = _origin_of(self._api_parts)
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def host(self) -> str:
|
|
85
|
+
"""Project origin, without a trailing slash or ``/api`` prefix."""
|
|
86
|
+
return self._host_origin
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def api_base_url(self) -> str:
|
|
90
|
+
"""Effective API base URL, without a trailing slash."""
|
|
91
|
+
return urlunsplit(self._api_parts)
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def root(value: str) -> str:
|
|
95
|
+
"""Parses a project domain while preserving explicit HTTP scheme and port."""
|
|
96
|
+
parsed = _http_uri(value)
|
|
97
|
+
if parsed.path not in {"", "/", "/api", "/api/"}:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"Invalid project_domain '{value}': Use a domain or origin, not a resource path."
|
|
100
|
+
)
|
|
101
|
+
return _origin_of(parsed)
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def _api_root(value: str) -> SplitResult:
|
|
105
|
+
parsed = _http_uri(value)
|
|
106
|
+
segs = _segments(parsed.path)
|
|
107
|
+
prefix_path = f"/{'/'.join(segs)}" if segs else "/api"
|
|
108
|
+
origin = _origin_of(parsed)
|
|
109
|
+
origin_parts = urlsplit(origin)
|
|
110
|
+
return SplitResult(
|
|
111
|
+
scheme=origin_parts.scheme,
|
|
112
|
+
netloc=origin_parts.netloc,
|
|
113
|
+
path=prefix_path,
|
|
114
|
+
query="",
|
|
115
|
+
fragment="",
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
def normalize_realtime_host(host: str) -> str:
|
|
120
|
+
"""Normalizes legacy ``ws3.hosteday.com`` to ``ws.hosteday.com``."""
|
|
121
|
+
cleaned = host.strip()
|
|
122
|
+
if cleaned.lower() == "ws3.hosteday.com":
|
|
123
|
+
return "ws.hosteday.com"
|
|
124
|
+
return cleaned
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def resolve_realtime_port(cls, *, scheme: str, host: str, port: int) -> int:
|
|
128
|
+
"""Normalizes TLS port 8080 to 443 on ``*.hosteday.com`` hosts."""
|
|
129
|
+
normalized_scheme = scheme.strip().lower()
|
|
130
|
+
normalized_host = cls.normalize_realtime_host(host).lower()
|
|
131
|
+
if (
|
|
132
|
+
normalized_scheme == "wss"
|
|
133
|
+
and normalized_host.endswith(".hosteday.com")
|
|
134
|
+
and port == 8080
|
|
135
|
+
):
|
|
136
|
+
return 443
|
|
137
|
+
return port
|
|
138
|
+
|
|
139
|
+
def api(self, path: str) -> str:
|
|
140
|
+
"""Resolves a REST API path, preventing duplicate ``/api`` and enforcing Origin Lock."""
|
|
141
|
+
trimmed = path.strip()
|
|
142
|
+
if "#" in trimmed:
|
|
143
|
+
raise ValueError("REST URLs cannot contain fragments.")
|
|
144
|
+
|
|
145
|
+
parsed = urlsplit(trimmed)
|
|
146
|
+
if parsed.scheme or parsed.netloc:
|
|
147
|
+
scheme = parsed.scheme.lower()
|
|
148
|
+
if (
|
|
149
|
+
scheme not in {"http", "https"}
|
|
150
|
+
or not parsed.hostname
|
|
151
|
+
or parsed.username is not None
|
|
152
|
+
or parsed.password is not None
|
|
153
|
+
or _origin_of(parsed) != self._api_origin
|
|
154
|
+
):
|
|
155
|
+
raise ValueError("REST URLs must use the configured API origin.")
|
|
156
|
+
_validate_raw_path(parsed.path)
|
|
157
|
+
else:
|
|
158
|
+
_validate_raw_path(trimmed)
|
|
159
|
+
|
|
160
|
+
parts = _segments(parsed.path)
|
|
161
|
+
prefix = _segments(self._api_parts.path)
|
|
162
|
+
|
|
163
|
+
has_prefix = len(parts) >= len(prefix) and all(
|
|
164
|
+
parts[i] == prefix[i] for i in range(len(prefix))
|
|
165
|
+
)
|
|
166
|
+
if has_prefix:
|
|
167
|
+
parts = parts[len(prefix) :]
|
|
168
|
+
elif parts and parts[0] == "api":
|
|
169
|
+
parts = parts[1:]
|
|
170
|
+
|
|
171
|
+
combined = [*prefix, *parts]
|
|
172
|
+
final_path = f"/{'/'.join(combined)}"
|
|
173
|
+
return urlunsplit(
|
|
174
|
+
SplitResult(
|
|
175
|
+
scheme=self._api_parts.scheme,
|
|
176
|
+
netloc=self._api_parts.netloc,
|
|
177
|
+
path=final_path,
|
|
178
|
+
query=parsed.query,
|
|
179
|
+
fragment="",
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def page(self, slug: str) -> str:
|
|
184
|
+
"""Resolves a single public static page slug under the project host."""
|
|
185
|
+
trimmed = slug.strip()
|
|
186
|
+
_validate_raw_path(trimmed)
|
|
187
|
+
parsed = urlsplit(trimmed)
|
|
188
|
+
parts = _segments(parsed.path)
|
|
189
|
+
if (
|
|
190
|
+
parsed.scheme
|
|
191
|
+
or parsed.netloc
|
|
192
|
+
or parsed.query
|
|
193
|
+
or parsed.fragment
|
|
194
|
+
or len(parts) != 1
|
|
195
|
+
):
|
|
196
|
+
raise ValueError(f"Invalid slug '{slug}': One non-empty page slug is required.")
|
|
197
|
+
return urlunsplit(
|
|
198
|
+
SplitResult(
|
|
199
|
+
scheme=self._host_parts.scheme,
|
|
200
|
+
netloc=self._host_parts.netloc,
|
|
201
|
+
path=f"/{parts[0]}",
|
|
202
|
+
query="",
|
|
203
|
+
fragment="",
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
def storage(self, path: str) -> str:
|
|
208
|
+
"""Resolves public media under ``/storage``; preserves external HTTP(S) URLs."""
|
|
209
|
+
text = path.strip()
|
|
210
|
+
parsed = urlsplit(text)
|
|
211
|
+
if parsed.scheme:
|
|
212
|
+
scheme = parsed.scheme.lower()
|
|
213
|
+
if (
|
|
214
|
+
scheme not in {"http", "https"}
|
|
215
|
+
or not parsed.hostname
|
|
216
|
+
or parsed.username is not None
|
|
217
|
+
or parsed.password is not None
|
|
218
|
+
):
|
|
219
|
+
raise ValueError("Media URLs must use HTTP(S).")
|
|
220
|
+
return text
|
|
221
|
+
|
|
222
|
+
if parsed.netloc or parsed.query or parsed.fragment:
|
|
223
|
+
raise ValueError("Use a relative file path or a full HTTP(S) URL.")
|
|
224
|
+
|
|
225
|
+
_validate_raw_path(text)
|
|
226
|
+
parts = _segments(parsed.path)
|
|
227
|
+
if not parts:
|
|
228
|
+
raise ValueError("A file path is required.")
|
|
229
|
+
if parts[0] == "storage":
|
|
230
|
+
parts = parts[1:]
|
|
231
|
+
if not parts:
|
|
232
|
+
raise ValueError("A file path is required.")
|
|
233
|
+
|
|
234
|
+
return urlunsplit(
|
|
235
|
+
SplitResult(
|
|
236
|
+
scheme=self._host_parts.scheme,
|
|
237
|
+
netloc=self._host_parts.netloc,
|
|
238
|
+
path=f"/{'/'.join(['storage', *parts])}",
|
|
239
|
+
query="",
|
|
240
|
+
fragment="",
|
|
241
|
+
)
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class HostedayStaticPages:
|
|
246
|
+
"""Dictionary-style accessor for HosteDay public static pages (e.g. ``static_pages['info']``)."""
|
|
247
|
+
|
|
248
|
+
def __init__(self, resolver: HostedayUrlResolver) -> None:
|
|
249
|
+
self._resolver = resolver
|
|
250
|
+
|
|
251
|
+
def __getitem__(self, slug: str) -> str:
|
|
252
|
+
return self._resolver.page(slug)
|
|
253
|
+
|
|
254
|
+
def get(self, slug: str) -> str:
|
|
255
|
+
return self._resolver.page(slug)
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Hybrid connectivity monitor combining periodic active probes and passive HTTP hooks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from collections.abc import AsyncIterator
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from hosteday.config.hosteday_config import HostedayConfig
|
|
11
|
+
from hosteday.reactive.observable_state import ObservableState
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HostedayConnectivity:
|
|
15
|
+
"""Monitors connectivity to HosteDay via active probing (every 4.0s, 3.0s timeout) and passive HTTP callbacks."""
|
|
16
|
+
|
|
17
|
+
DEFAULT_CHECK_INTERVAL: float = 4.0
|
|
18
|
+
DEFAULT_PROBE_TIMEOUT: float = 3.0
|
|
19
|
+
FALLBACK_PROBE_URL: str = "https://hosteday.com"
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
*,
|
|
24
|
+
config: HostedayConfig,
|
|
25
|
+
probe_client: httpx.AsyncClient | None = None,
|
|
26
|
+
check_interval: float = DEFAULT_CHECK_INTERVAL,
|
|
27
|
+
probe_timeout: float = DEFAULT_PROBE_TIMEOUT,
|
|
28
|
+
initial_connected: bool = True,
|
|
29
|
+
enable_active_probe: bool = True,
|
|
30
|
+
) -> None:
|
|
31
|
+
self.config = config
|
|
32
|
+
self._check_interval = check_interval
|
|
33
|
+
self._probe_timeout = probe_timeout
|
|
34
|
+
self._enable_active_probe = enable_active_probe
|
|
35
|
+
self._owns_client = probe_client is None
|
|
36
|
+
self._probe_client: httpx.AsyncClient | None = probe_client
|
|
37
|
+
self._status = ObservableState(initial_connected, distinct_until_changed=True)
|
|
38
|
+
self._probe_task: asyncio.Task[None] | None = None
|
|
39
|
+
self._disposed: bool = False
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def is_connected(self) -> bool:
|
|
43
|
+
return self._status.value
|
|
44
|
+
|
|
45
|
+
def on_status_change(self) -> AsyncIterator[bool]:
|
|
46
|
+
"""Async iterator emitting distinct connectivity changes (True=online, False=offline)."""
|
|
47
|
+
return self._status.stream(replay_current=True)
|
|
48
|
+
|
|
49
|
+
def start(self) -> None:
|
|
50
|
+
"""Starts periodic active probing if enabled and an event loop is running."""
|
|
51
|
+
if self._disposed or not self._enable_active_probe:
|
|
52
|
+
return
|
|
53
|
+
if self._probe_task is not None and not self._probe_task.done():
|
|
54
|
+
return
|
|
55
|
+
try:
|
|
56
|
+
loop = asyncio.get_running_loop()
|
|
57
|
+
except RuntimeError:
|
|
58
|
+
return
|
|
59
|
+
self._probe_task = loop.create_task(self._probe_loop())
|
|
60
|
+
|
|
61
|
+
def report_success(self) -> None:
|
|
62
|
+
"""Passive hook invoked by ``HostedayHttpClient`` upon any HTTP response."""
|
|
63
|
+
if not self._disposed:
|
|
64
|
+
self._status.emit(True)
|
|
65
|
+
|
|
66
|
+
def report_failure(self, _error: object = None) -> None:
|
|
67
|
+
"""Passive hook invoked by ``HostedayHttpClient`` upon network/timeout failure."""
|
|
68
|
+
if not self._disposed:
|
|
69
|
+
self._status.emit(False)
|
|
70
|
+
|
|
71
|
+
def update_status(self, is_online: bool) -> None:
|
|
72
|
+
if not self._disposed:
|
|
73
|
+
self._status.emit(is_online)
|
|
74
|
+
|
|
75
|
+
async def check_now(self) -> bool:
|
|
76
|
+
"""Runs an immediate active reachability probe against ``config.base_url`` (with fallback)."""
|
|
77
|
+
if self._disposed:
|
|
78
|
+
return self.is_connected
|
|
79
|
+
|
|
80
|
+
primary_url = self.config.base_url.strip() or self.FALLBACK_PROBE_URL
|
|
81
|
+
reachable = await self._probe_single_url(primary_url)
|
|
82
|
+
|
|
83
|
+
is_local = any(
|
|
84
|
+
marker in primary_url for marker in ("localhost", "127.0.0.1", "10.0.2.2")
|
|
85
|
+
)
|
|
86
|
+
if not reachable and primary_url != self.FALLBACK_PROBE_URL and not is_local:
|
|
87
|
+
reachable = await self._probe_single_url(self.FALLBACK_PROBE_URL)
|
|
88
|
+
|
|
89
|
+
self.update_status(reachable)
|
|
90
|
+
return reachable
|
|
91
|
+
|
|
92
|
+
async def _probe_single_url(self, url: str) -> bool:
|
|
93
|
+
client = self._ensure_probe_client()
|
|
94
|
+
headers = self.config.default_headers
|
|
95
|
+
try:
|
|
96
|
+
resp = await client.head(
|
|
97
|
+
url,
|
|
98
|
+
headers=headers,
|
|
99
|
+
timeout=self._probe_timeout,
|
|
100
|
+
follow_redirects=False,
|
|
101
|
+
)
|
|
102
|
+
return resp.status_code > 0
|
|
103
|
+
except httpx.HTTPError:
|
|
104
|
+
try:
|
|
105
|
+
resp = await client.get(
|
|
106
|
+
url,
|
|
107
|
+
headers=headers,
|
|
108
|
+
timeout=self._probe_timeout,
|
|
109
|
+
follow_redirects=False,
|
|
110
|
+
)
|
|
111
|
+
return resp.status_code > 0
|
|
112
|
+
except httpx.HTTPError:
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
def _ensure_probe_client(self) -> httpx.AsyncClient:
|
|
116
|
+
if self._probe_client is None:
|
|
117
|
+
self._probe_client = httpx.AsyncClient(timeout=self._probe_timeout)
|
|
118
|
+
return self._probe_client
|
|
119
|
+
|
|
120
|
+
async def _probe_loop(self) -> None:
|
|
121
|
+
try:
|
|
122
|
+
while not self._disposed:
|
|
123
|
+
await asyncio.sleep(self._check_interval)
|
|
124
|
+
if self._disposed:
|
|
125
|
+
break
|
|
126
|
+
await self.check_now()
|
|
127
|
+
except asyncio.CancelledError:
|
|
128
|
+
return
|
|
129
|
+
|
|
130
|
+
async def dispose(self) -> None:
|
|
131
|
+
"""Cancels periodic probing and releases the internal HTTP probe client."""
|
|
132
|
+
if self._disposed:
|
|
133
|
+
return
|
|
134
|
+
self._disposed = True
|
|
135
|
+
if self._probe_task is not None and not self._probe_task.done():
|
|
136
|
+
self._probe_task.cancel()
|
|
137
|
+
try:
|
|
138
|
+
await self._probe_task
|
|
139
|
+
except asyncio.CancelledError:
|
|
140
|
+
pass
|
|
141
|
+
self._probe_task = None
|
|
142
|
+
|
|
143
|
+
if self._owns_client and self._probe_client is not None:
|
|
144
|
+
await self._probe_client.aclose()
|
|
145
|
+
self._probe_client = None
|
|
146
|
+
|
|
147
|
+
await self._status.close()
|
hosteday/exceptions.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Unified exception hierarchy for the HosteDay Python SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class HostedayException(Exception):
|
|
10
|
+
"""Represents an error returned while communicating with HosteDay services."""
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
message: str,
|
|
15
|
+
*,
|
|
16
|
+
status_code: int | None = None,
|
|
17
|
+
validation_errors: Mapping[str, list[str]] | None = None,
|
|
18
|
+
response: Mapping[str, Any] | None = None,
|
|
19
|
+
error: BaseException | None = None,
|
|
20
|
+
) -> None:
|
|
21
|
+
super().__init__(message)
|
|
22
|
+
self.message: str = message
|
|
23
|
+
self.status_code: int | None = status_code
|
|
24
|
+
self.validation_errors: dict[str, list[str]] = (
|
|
25
|
+
{str(k): list(v) for k, v in validation_errors.items()}
|
|
26
|
+
if validation_errors
|
|
27
|
+
else {}
|
|
28
|
+
)
|
|
29
|
+
self.response: dict[str, Any] | None = dict(response) if response is not None else None
|
|
30
|
+
self.error: BaseException | None = error
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def from_response(
|
|
34
|
+
cls,
|
|
35
|
+
response: Mapping[str, Any],
|
|
36
|
+
*,
|
|
37
|
+
status_code: int | None = None,
|
|
38
|
+
error: BaseException | None = None,
|
|
39
|
+
) -> HostedayException:
|
|
40
|
+
"""Creates a ``HostedayException`` from a decoded API response mapping."""
|
|
41
|
+
message = cls._extract_message(response)
|
|
42
|
+
if message is None:
|
|
43
|
+
if status_code == 429:
|
|
44
|
+
message = "Too many requests (HTTP 429)."
|
|
45
|
+
else:
|
|
46
|
+
message = f"Hosteday request failed (HTTP {status_code})."
|
|
47
|
+
|
|
48
|
+
validation_errors = cls._extract_validation_errors(response)
|
|
49
|
+
return cls(
|
|
50
|
+
message,
|
|
51
|
+
status_code=status_code,
|
|
52
|
+
validation_errors=validation_errors,
|
|
53
|
+
response=response,
|
|
54
|
+
error=error,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def has_validation_errors(self) -> bool:
|
|
59
|
+
return bool(self.validation_errors)
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def is_validation_error(self) -> bool:
|
|
63
|
+
return self.status_code == 422
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def is_unauthenticated(self) -> bool:
|
|
67
|
+
return self.status_code == 401
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def is_forbidden(self) -> bool:
|
|
71
|
+
return self.status_code == 403
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def is_not_found(self) -> bool:
|
|
75
|
+
return self.status_code == 404
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def is_server_error(self) -> bool:
|
|
79
|
+
return self.status_code is not None and self.status_code >= 500
|
|
80
|
+
|
|
81
|
+
def first_error_for(self, field: str) -> str | None:
|
|
82
|
+
"""Returns the first validation error for ``field``, when available."""
|
|
83
|
+
errors = self.validation_errors.get(field)
|
|
84
|
+
if not errors:
|
|
85
|
+
return None
|
|
86
|
+
return errors[0]
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def first_validation_error(self) -> str | None:
|
|
90
|
+
"""Returns the first validation error from any field, when available."""
|
|
91
|
+
for errors in self.validation_errors.values():
|
|
92
|
+
if errors:
|
|
93
|
+
return errors[0]
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def display_message(self) -> str:
|
|
98
|
+
"""Returns the first validation error when present, otherwise ``message``."""
|
|
99
|
+
return self.first_validation_error or self.message
|
|
100
|
+
|
|
101
|
+
def __str__(self) -> str:
|
|
102
|
+
parts: list[str] = [f"message: {self.message}"]
|
|
103
|
+
if self.status_code is not None:
|
|
104
|
+
parts.append(f"status_code: {self.status_code}")
|
|
105
|
+
if self.validation_errors:
|
|
106
|
+
parts.append(f"validation_errors: {self.validation_errors}")
|
|
107
|
+
if self.error is not None:
|
|
108
|
+
parts.append(f"error: {self.error}")
|
|
109
|
+
return f"HostedayException({', '.join(parts)})"
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def _extract_message(response: Mapping[str, Any]) -> str | None:
|
|
113
|
+
raw_message = response.get("message")
|
|
114
|
+
if isinstance(raw_message, str) and raw_message.strip():
|
|
115
|
+
return raw_message.strip()
|
|
116
|
+
|
|
117
|
+
raw_error = response.get("error")
|
|
118
|
+
if isinstance(raw_error, str) and raw_error.strip():
|
|
119
|
+
return raw_error.strip()
|
|
120
|
+
|
|
121
|
+
if isinstance(raw_error, Mapping):
|
|
122
|
+
nested = raw_error.get("message")
|
|
123
|
+
if isinstance(nested, str) and nested.strip():
|
|
124
|
+
return nested.strip()
|
|
125
|
+
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def _extract_validation_errors(response: Mapping[str, Any]) -> dict[str, list[str]]:
|
|
130
|
+
raw_errors = response.get("errors")
|
|
131
|
+
if not isinstance(raw_errors, Mapping):
|
|
132
|
+
return {}
|
|
133
|
+
|
|
134
|
+
result: dict[str, list[str]] = {}
|
|
135
|
+
for key, value in raw_errors.items():
|
|
136
|
+
field = str(key)
|
|
137
|
+
if isinstance(value, list):
|
|
138
|
+
result[field] = [str(item) for item in value]
|
|
139
|
+
elif isinstance(value, str):
|
|
140
|
+
result[field] = [value]
|
|
141
|
+
else:
|
|
142
|
+
result[field] = [str(value)]
|
|
143
|
+
return result
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class HostedayAuthException(HostedayException):
|
|
147
|
+
"""Represents an authentication-specific HosteDay error with a machine-readable code."""
|
|
148
|
+
|
|
149
|
+
def __init__(
|
|
150
|
+
self,
|
|
151
|
+
message: str,
|
|
152
|
+
*,
|
|
153
|
+
code: str,
|
|
154
|
+
status_code: int | None = None,
|
|
155
|
+
validation_errors: Mapping[str, list[str]] | None = None,
|
|
156
|
+
response: Mapping[str, Any] | None = None,
|
|
157
|
+
error: BaseException | None = None,
|
|
158
|
+
) -> None:
|
|
159
|
+
super().__init__(
|
|
160
|
+
message,
|
|
161
|
+
status_code=status_code,
|
|
162
|
+
validation_errors=validation_errors,
|
|
163
|
+
response=response,
|
|
164
|
+
error=error,
|
|
165
|
+
)
|
|
166
|
+
self.code: str = code
|
|
167
|
+
|
|
168
|
+
@classmethod
|
|
169
|
+
def from_hosteday_exception(cls, exception: HostedayException) -> HostedayAuthException:
|
|
170
|
+
"""Converts a general ``HostedayException`` into a ``HostedayAuthException``."""
|
|
171
|
+
raw_error: Any = None
|
|
172
|
+
if exception.response is not None:
|
|
173
|
+
raw_error = exception.response.get("error", exception.response)
|
|
174
|
+
|
|
175
|
+
server_code: str | None = None
|
|
176
|
+
if isinstance(raw_error, Mapping):
|
|
177
|
+
raw_code = raw_error.get("code") or raw_error.get("error_code")
|
|
178
|
+
if raw_code is not None and str(raw_code).strip():
|
|
179
|
+
server_code = str(raw_code).strip()
|
|
180
|
+
|
|
181
|
+
return cls(
|
|
182
|
+
exception.message,
|
|
183
|
+
code=server_code or cls._code_from_status(exception.status_code),
|
|
184
|
+
status_code=exception.status_code,
|
|
185
|
+
validation_errors=exception.validation_errors,
|
|
186
|
+
response=exception.response,
|
|
187
|
+
error=exception.error,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def _code_from_status(status_code: int | None) -> str:
|
|
192
|
+
mapping: dict[int, str] = {
|
|
193
|
+
400: "invalid-argument",
|
|
194
|
+
401: "invalid-credentials",
|
|
195
|
+
403: "permission-denied",
|
|
196
|
+
409: "email-already-in-use",
|
|
197
|
+
422: "validation-failed",
|
|
198
|
+
}
|
|
199
|
+
if status_code is None:
|
|
200
|
+
return "auth-request-failed"
|
|
201
|
+
return mapping.get(status_code, "auth-request-failed")
|
|
202
|
+
|
|
203
|
+
def __str__(self) -> str:
|
|
204
|
+
return (
|
|
205
|
+
f"HostedayAuthException("
|
|
206
|
+
f"code: {self.code}, "
|
|
207
|
+
f"message: {self.message}, "
|
|
208
|
+
f"status_code: {self.status_code}, "
|
|
209
|
+
f"error: {self.error}"
|
|
210
|
+
f")"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class HostedayRealtimeAuthorizationException(HostedayException):
|
|
215
|
+
"""Exception thrown when broadcasting channel authorization fails."""
|
|
216
|
+
|
|
217
|
+
def __init__(
|
|
218
|
+
self,
|
|
219
|
+
message: str,
|
|
220
|
+
*,
|
|
221
|
+
status_code: int | None = 401,
|
|
222
|
+
response: Mapping[str, Any] | None = None,
|
|
223
|
+
error: BaseException | None = None,
|
|
224
|
+
) -> None:
|
|
225
|
+
super().__init__(
|
|
226
|
+
message,
|
|
227
|
+
status_code=status_code,
|
|
228
|
+
response=response,
|
|
229
|
+
error=error,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def __str__(self) -> str:
|
|
233
|
+
return f"HostedayRealtimeAuthorizationException: {self.message}"
|