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.
Files changed (50) hide show
  1. hosteday/__init__.py +111 -0
  2. hosteday/_version.py +3 -0
  3. hosteday/auth/__init__.py +34 -0
  4. hosteday/auth/hosteday_auth.py +444 -0
  5. hosteday/auth/hosteday_auth_storage.py +130 -0
  6. hosteday/auth/hosteday_session.py +184 -0
  7. hosteday/auth/hosteday_token_provider.py +82 -0
  8. hosteday/auth/hosteday_user.py +223 -0
  9. hosteday/cli/__init__.py +5 -0
  10. hosteday/cli/setup.py +163 -0
  11. hosteday/config/__init__.py +15 -0
  12. hosteday/config/hosteday_config.py +576 -0
  13. hosteday/config/hosteday_option_keys.py +60 -0
  14. hosteday/config/hosteday_url_resolver.py +255 -0
  15. hosteday/connectivity/__init__.py +5 -0
  16. hosteday/connectivity/hosteday_connectivity.py +147 -0
  17. hosteday/exceptions.py +233 -0
  18. hosteday/features/__init__.py +5 -0
  19. hosteday/features/hosteday_features.py +78 -0
  20. hosteday/hosteday.py +346 -0
  21. hosteday/hosteday_client.py +579 -0
  22. hosteday/http/__init__.py +18 -0
  23. hosteday/http/hosteday_http_client.py +340 -0
  24. hosteday/http/hosteday_response_reader.py +171 -0
  25. hosteday/http/query_builder.py +204 -0
  26. hosteday/jobs/__init__.py +9 -0
  27. hosteday/jobs/hosteday_job_response.py +76 -0
  28. hosteday/jobs/hosteday_jobs_client.py +109 -0
  29. hosteday/notifications/__init__.py +13 -0
  30. hosteday/notifications/hosteday_notification_client.py +290 -0
  31. hosteday/notifications/hosteday_notification_response.py +79 -0
  32. hosteday/py.typed +1 -0
  33. hosteday/reactive/__init__.py +5 -0
  34. hosteday/reactive/observable_state.py +67 -0
  35. hosteday/realtime/__init__.py +31 -0
  36. hosteday/realtime/connection_state.py +14 -0
  37. hosteday/realtime/hosteday_channel.py +258 -0
  38. hosteday/realtime/hosteday_channel_auth.py +163 -0
  39. hosteday/realtime/hosteday_channel_type.py +68 -0
  40. hosteday/realtime/hosteday_realtime_client.py +790 -0
  41. hosteday/realtime/hosteday_realtime_event.py +130 -0
  42. hosteday/web/__init__.py +5 -0
  43. hosteday/web/server.py +637 -0
  44. hosteday_python/__init__.py +6 -0
  45. hosteday_python/py.typed +1 -0
  46. hosteday_python-0.1.0.dist-info/METADATA +205 -0
  47. hosteday_python-0.1.0.dist-info/RECORD +50 -0
  48. hosteday_python-0.1.0.dist-info/WHEEL +4 -0
  49. hosteday_python-0.1.0.dist-info/entry_points.txt +2 -0
  50. hosteday_python-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,290 @@
1
+ """Push notification client managing device tokens, 404 fallbacks, topics, and dispatching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator, Mapping
6
+ from typing import Any
7
+
8
+ from hosteday.auth.hosteday_token_provider import HostedayTokenProvider
9
+ from hosteday.config.hosteday_config import HostedayConfig
10
+ from hosteday.exceptions import HostedayException
11
+ from hosteday.http.hosteday_http_client import HostedayHttpClient
12
+ from hosteday.notifications.hosteday_notification_response import (
13
+ HostedayNotificationResponse,
14
+ )
15
+ from hosteday.reactive.observable_state import ObservableState
16
+
17
+
18
+ class HostedayNotificationClient:
19
+ """Manages HosteDay push notifications, device token sync/unlink, topics, and server push."""
20
+
21
+ def __init__(
22
+ self,
23
+ *,
24
+ config: HostedayConfig,
25
+ http: HostedayHttpClient,
26
+ token_provider: HostedayTokenProvider | None = None,
27
+ ) -> None:
28
+ self.config = config
29
+ self.http = http
30
+ self.token_provider = token_provider
31
+
32
+ self._token_state: ObservableState[str | None] = ObservableState(None)
33
+ self._subscribed_topics: set[str] = set()
34
+ if config.default_notification_topic and config.default_notification_topic.strip():
35
+ self._subscribed_topics.add(config.default_notification_topic.strip())
36
+
37
+ self.current_device_id: str | None = None
38
+ self.current_device_type: str | None = None
39
+ self.current_device_name: str | None = None
40
+ self._disposed: bool = False
41
+
42
+ @property
43
+ def is_enabled(self) -> bool:
44
+ return self.config.notifications_enabled
45
+
46
+ @property
47
+ def current_token(self) -> str | None:
48
+ return self._token_state.value
49
+
50
+ def on_token_changed(self) -> AsyncIterator[str | None]:
51
+ return self._token_state.stream(replay_current=True)
52
+
53
+ @property
54
+ def subscribed_topics(self) -> frozenset[str]:
55
+ return frozenset(self._subscribed_topics)
56
+
57
+ async def sync_device_token(
58
+ self,
59
+ *,
60
+ token: str,
61
+ access_token: str | None = None,
62
+ device_type: str | None = None,
63
+ device_id: str | None = None,
64
+ device_name: str | None = None,
65
+ endpoint: str | None = None,
66
+ ) -> dict[str, Any]:
67
+ """Synchronizes or registers a device token with the HosteDay server."""
68
+ return await self.register_device_token(
69
+ token=token,
70
+ access_token=access_token,
71
+ device_type=device_type,
72
+ device_id=device_id,
73
+ device_name=device_name,
74
+ endpoint=endpoint,
75
+ )
76
+
77
+ async def register_device_token(
78
+ self,
79
+ *,
80
+ token: str,
81
+ access_token: str | None = None,
82
+ device_type: str | None = None,
83
+ device_id: str | None = None,
84
+ device_name: str | None = None,
85
+ endpoint: str | None = None,
86
+ ) -> dict[str, Any]:
87
+ """Registers a device token (for authenticated users or guests) with automatic 404 fallback."""
88
+ self._ensure_not_disposed()
89
+ clean_token = token.strip()
90
+ if not clean_token:
91
+ raise HostedayException("A valid device token is required.")
92
+
93
+ clean_access = access_token.strip() if access_token else ""
94
+ has_explicit_auth = bool(clean_access)
95
+ has_auth = has_explicit_auth or await self._has_authenticated_user()
96
+
97
+ body: dict[str, Any] = {
98
+ "device_token": clean_token,
99
+ "token": clean_token,
100
+ }
101
+ if device_type:
102
+ body["device_type"] = device_type
103
+ if device_id:
104
+ body["device_id"] = device_id
105
+ if device_name:
106
+ body["device_name"] = device_name
107
+
108
+ headers = {"Authorization": f"Bearer {clean_access}"} if has_explicit_auth else None
109
+ target_path = endpoint or self.config.register_device_token_path
110
+
111
+ try:
112
+ response = await self.http.post(
113
+ target_path,
114
+ body=body,
115
+ headers=headers,
116
+ with_auth=(not has_explicit_auth) and has_auth,
117
+ )
118
+ except HostedayException as exc:
119
+ if exc.status_code == 404:
120
+ alternative = (
121
+ "/api/notifications/devices/register"
122
+ if target_path == "/api/device-tokens"
123
+ else "/api/device-tokens"
124
+ )
125
+ response = await self.http.post(
126
+ alternative,
127
+ body=body,
128
+ headers=headers,
129
+ with_auth=(not has_explicit_auth) and has_auth,
130
+ )
131
+ else:
132
+ raise
133
+
134
+ self.current_device_id = device_id
135
+ self.current_device_type = device_type
136
+ self.current_device_name = device_name
137
+ self._token_state.emit(clean_token)
138
+ return response
139
+
140
+ async def unregister_device_token(
141
+ self,
142
+ *,
143
+ token: str,
144
+ device_id: str | None = None,
145
+ action: str | None = "unlink",
146
+ logout_only: bool | None = None,
147
+ access_token: str | None = None,
148
+ endpoint: str | None = None,
149
+ ) -> dict[str, Any]:
150
+ """Unregisters or unlinks a device token with automatic 404 fallback."""
151
+ self._ensure_not_disposed()
152
+ clean_token = token.strip()
153
+ if not clean_token:
154
+ return {}
155
+
156
+ clean_access = access_token.strip() if access_token else ""
157
+ has_explicit_auth = bool(clean_access)
158
+ has_auth = has_explicit_auth or await self._has_authenticated_user()
159
+
160
+ body: dict[str, Any] = {
161
+ "device_token": clean_token,
162
+ "token": clean_token,
163
+ }
164
+ if device_id:
165
+ body["device_id"] = device_id
166
+ if action:
167
+ body["action"] = action
168
+ if logout_only is not None:
169
+ body["logout_only"] = logout_only
170
+
171
+ headers = {"Authorization": f"Bearer {clean_access}"} if has_explicit_auth else None
172
+ target_path = endpoint or self.config.unregister_device_token_path
173
+
174
+ try:
175
+ response = await self.http.post(
176
+ target_path,
177
+ body=body,
178
+ headers=headers,
179
+ with_auth=(not has_explicit_auth) and has_auth,
180
+ )
181
+ except HostedayException as exc:
182
+ if exc.status_code == 404:
183
+ alternative = (
184
+ "/api/notifications/devices/unregister"
185
+ if target_path == "/api/device-tokens"
186
+ else "/api/device-tokens"
187
+ )
188
+ response = await self.http.post(
189
+ alternative,
190
+ body=body,
191
+ headers=headers,
192
+ with_auth=(not has_explicit_auth) and has_auth,
193
+ )
194
+ else:
195
+ raise
196
+
197
+ if self._token_state.value == clean_token:
198
+ self._token_state.emit(None)
199
+ return response
200
+
201
+ async def get_registered_devices(self) -> list[dict[str, Any]]:
202
+ """Retrieves devices registered for the authenticated user."""
203
+ self._ensure_not_disposed()
204
+ has_auth = await self._has_authenticated_user()
205
+ response = await self.http.get(
206
+ self.config.registered_devices_path,
207
+ with_auth=has_auth,
208
+ )
209
+
210
+ raw_list: Any = None
211
+ for key in ("data", "devices", "records", "items"):
212
+ if key in response and response[key] is not None:
213
+ raw_list = response[key]
214
+ break
215
+
216
+ if isinstance(raw_list, list):
217
+ return [dict(item) for item in raw_list if isinstance(item, Mapping)]
218
+ return []
219
+
220
+ async def send_notification(
221
+ self,
222
+ *,
223
+ title: str,
224
+ body: str,
225
+ recipient_user_id: str | None = None,
226
+ recipient_token: str | None = None,
227
+ topic: str | None = None,
228
+ data: Mapping[str, Any] | None = None,
229
+ provider: str | None = None,
230
+ ) -> HostedayNotificationResponse:
231
+ """Dispatches an immediate push notification through the HosteDay server gateway."""
232
+ self._ensure_not_disposed()
233
+ clean_title = title.strip()
234
+ clean_body = body.strip()
235
+ if not clean_title:
236
+ raise HostedayException("A notification title is required.")
237
+ if not clean_body:
238
+ raise HostedayException("A notification body is required.")
239
+
240
+ target_topic = topic or self.config.default_notification_topic
241
+ has_auth = await self._has_authenticated_user()
242
+
243
+ payload: dict[str, Any] = {
244
+ "title": clean_title,
245
+ "body": clean_body,
246
+ }
247
+ if recipient_user_id:
248
+ payload["recipient_user_id"] = recipient_user_id
249
+ if recipient_token:
250
+ payload["recipient_token"] = recipient_token
251
+ if target_topic:
252
+ payload["topic"] = target_topic
253
+ if data:
254
+ payload["data"] = dict(data)
255
+ if provider:
256
+ payload["provider"] = provider
257
+
258
+ response = await self.http.post(
259
+ self.config.send_notification_path,
260
+ body=payload,
261
+ with_auth=has_auth,
262
+ )
263
+ return HostedayNotificationResponse.from_json(response)
264
+
265
+ async def subscribe_to_topic(self, topic: str) -> None:
266
+ self._ensure_not_disposed()
267
+ cleaned = topic.strip()
268
+ if cleaned:
269
+ self._subscribed_topics.add(cleaned)
270
+
271
+ async def unsubscribe_from_topic(self, topic: str) -> None:
272
+ self._ensure_not_disposed()
273
+ cleaned = topic.strip()
274
+ self._subscribed_topics.discard(cleaned)
275
+
276
+ async def dispose(self) -> None:
277
+ if self._disposed:
278
+ return
279
+ self._disposed = True
280
+ await self._token_state.close()
281
+
282
+ async def _has_authenticated_user(self) -> bool:
283
+ if self.token_provider is None:
284
+ return False
285
+ token = await self.token_provider.get_token()
286
+ return bool(token and token.strip())
287
+
288
+ def _ensure_not_disposed(self) -> None:
289
+ if self._disposed:
290
+ raise HostedayException("Notification client has been disposed.")
@@ -0,0 +1,79 @@
1
+ """Typed + Mapping-compatible response model for HosteDay push notifications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Mapping
6
+ from types import MappingProxyType
7
+ from typing import Any
8
+
9
+
10
+ class HostedayNotificationResponse(Mapping[str, Any]):
11
+ """Represents a HosteDay notification dispatch response with read-only Mapping compatibility."""
12
+
13
+ def __init__(
14
+ self,
15
+ *,
16
+ success: bool,
17
+ message_id: str | None = None,
18
+ error: str | None = None,
19
+ data: Mapping[str, Any] | None = None,
20
+ raw: Mapping[str, Any] | None = None,
21
+ ) -> None:
22
+ self.success: bool = success
23
+ self.message_id: str | None = message_id
24
+ self.error: str | None = error
25
+ self.data: dict[str, Any] | None = dict(data) if data is not None else None
26
+
27
+ if raw is not None:
28
+ raw_dict = dict(raw)
29
+ else:
30
+ raw_dict = {"success": success}
31
+ if message_id is not None:
32
+ raw_dict["message_id"] = message_id
33
+ if error is not None:
34
+ raw_dict["error"] = error
35
+ if data is not None:
36
+ raw_dict["data"] = dict(data)
37
+ self._raw: Mapping[str, Any] = MappingProxyType(raw_dict)
38
+
39
+ @classmethod
40
+ def from_json(cls, payload: Mapping[str, Any]) -> HostedayNotificationResponse:
41
+ success = payload.get("success") is True
42
+ raw_data = payload.get("data")
43
+ data_dict = dict(raw_data) if isinstance(raw_data, Mapping) else None
44
+
45
+ raw_msg_id = (
46
+ payload.get("message_id")
47
+ or payload.get("messageId")
48
+ or (data_dict.get("message_id") if data_dict else None)
49
+ or (data_dict.get("messageId") if data_dict else None)
50
+ )
51
+ raw_error = payload.get("error")
52
+ if raw_error is None and not success:
53
+ raw_error = payload.get("message") or "Notification dispatch failed."
54
+
55
+ return cls(
56
+ success=success,
57
+ message_id=str(raw_msg_id) if raw_msg_id is not None else None,
58
+ error=str(raw_error) if raw_error is not None else None,
59
+ data=data_dict,
60
+ raw=payload,
61
+ )
62
+
63
+ def __getitem__(self, key: str) -> Any:
64
+ return self._raw[key]
65
+
66
+ def __iter__(self) -> Iterator[str]:
67
+ return iter(self._raw)
68
+
69
+ def __len__(self) -> int:
70
+ return len(self._raw)
71
+
72
+ def to_json(self) -> dict[str, Any]:
73
+ return dict(self._raw)
74
+
75
+ def __repr__(self) -> str:
76
+ return (
77
+ f"HostedayNotificationResponse(success={self.success!r}, "
78
+ f"message_id={self.message_id!r}, error={self.error!r}, data={self.data!r})"
79
+ )
hosteday/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,5 @@
1
+ """Reactive primitives for HosteDay state streams."""
2
+
3
+ from hosteday.reactive.observable_state import ObservableState
4
+
5
+ __all__ = ["ObservableState"]
@@ -0,0 +1,67 @@
1
+ """Reactive state container with immediate replay on subscribe."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import AsyncIterator
7
+ from typing import Generic, TypeVar
8
+
9
+ T = TypeVar("T")
10
+ _CLOSE_SENTINEL = object()
11
+
12
+
13
+ class ObservableState(Generic[T]):
14
+ """Async state holder equivalent to Kotlin ``StateFlow`` and Dart replay streams."""
15
+
16
+ def __init__(self, initial: T, *, distinct_until_changed: bool = False) -> None:
17
+ self._value: T = initial
18
+ self._distinct: bool = distinct_until_changed
19
+ self._subscribers: set[asyncio.Queue[T | object]] = set()
20
+ self._closed: bool = False
21
+
22
+ @property
23
+ def value(self) -> T:
24
+ return self._value
25
+
26
+ @property
27
+ def is_closed(self) -> bool:
28
+ return self._closed
29
+
30
+ def emit(self, value: T) -> None:
31
+ """Updates the current value and notifies all active subscribers."""
32
+ if self._closed:
33
+ return
34
+ if self._distinct and value == self._value:
35
+ return
36
+ self._value = value
37
+ for queue in list(self._subscribers):
38
+ queue.put_nowait(value)
39
+
40
+ async def stream(self, *, replay_current: bool = True) -> AsyncIterator[T]:
41
+ """Yields the current value immediately (when ``replay_current`` is True), then live updates."""
42
+ queue: asyncio.Queue[T | object] = asyncio.Queue()
43
+ if replay_current:
44
+ queue.put_nowait(self._value)
45
+ if self._closed:
46
+ if replay_current:
47
+ yield self._value
48
+ return
49
+
50
+ self._subscribers.add(queue)
51
+ try:
52
+ while True:
53
+ item = await queue.get()
54
+ if item is _CLOSE_SENTINEL:
55
+ break
56
+ yield item # type: ignore[misc]
57
+ finally:
58
+ self._subscribers.discard(queue)
59
+
60
+ async def close(self) -> None:
61
+ """Closes the state stream and completes all active subscriber iterators."""
62
+ if self._closed:
63
+ return
64
+ self._closed = True
65
+ for queue in list(self._subscribers):
66
+ queue.put_nowait(_CLOSE_SENTINEL)
67
+ self._subscribers.clear()
@@ -0,0 +1,31 @@
1
+ """Pusher v7 / Laravel Reverb realtime WebSocket engine for HosteDay."""
2
+
3
+ from hosteday.realtime.connection_state import RealtimeConnectionState
4
+ from hosteday.realtime.hosteday_channel import (
5
+ ChannelSubscription,
6
+ HostedayChannel,
7
+ PresenceChannel,
8
+ )
9
+ from hosteday.realtime.hosteday_channel_auth import (
10
+ ChannelAuthData,
11
+ HostedayChannelAuthorizationDelegate,
12
+ )
13
+ from hosteday.realtime.hosteday_channel_type import HostedayChannelType
14
+ from hosteday.realtime.hosteday_realtime_client import (
15
+ HostedayRealtimeCallback,
16
+ HostedayRealtimeClient,
17
+ )
18
+ from hosteday.realtime.hosteday_realtime_event import HostedayRealtimeEvent
19
+
20
+ __all__ = [
21
+ "ChannelAuthData",
22
+ "ChannelSubscription",
23
+ "HostedayChannel",
24
+ "HostedayChannelAuthorizationDelegate",
25
+ "HostedayChannelType",
26
+ "HostedayRealtimeCallback",
27
+ "HostedayRealtimeClient",
28
+ "HostedayRealtimeEvent",
29
+ "PresenceChannel",
30
+ "RealtimeConnectionState",
31
+ ]
@@ -0,0 +1,14 @@
1
+ """WebSocket connection lifecycle states for ``HostedayRealtimeClient``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum
6
+
7
+
8
+ class RealtimeConnectionState(str, Enum):
9
+ """Lifecycle states of the Pusher v7 / Laravel Reverb WebSocket client."""
10
+
11
+ DISCONNECTED = "disconnected"
12
+ CONNECTING = "connecting"
13
+ CONNECTED = "connected"
14
+ RECONNECTING = "reconnecting"