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,258 @@
|
|
|
1
|
+
"""Tracked channel objects, presence member caching, whisper events, and NaCl decryption."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import inspect
|
|
8
|
+
import json
|
|
9
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from hosteday.realtime.hosteday_channel_type import HostedayChannelType
|
|
13
|
+
from hosteday.realtime.hosteday_realtime_event import HostedayRealtimeEvent
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from hosteday.realtime.hosteday_realtime_client import HostedayRealtimeClient
|
|
17
|
+
|
|
18
|
+
RealtimeEventHandler = Callable[[HostedayRealtimeEvent], Any]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ChannelSubscription:
|
|
22
|
+
"""Handle allowing callers to cancel a single event listener on a channel."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, cancel_fn: Callable[[], None]) -> None:
|
|
25
|
+
self._cancel_fn = cancel_fn
|
|
26
|
+
self._cancelled = False
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def is_cancelled(self) -> bool:
|
|
30
|
+
return self._cancelled
|
|
31
|
+
|
|
32
|
+
def cancel(self) -> None:
|
|
33
|
+
if not self._cancelled:
|
|
34
|
+
self._cancelled = True
|
|
35
|
+
self._cancel_fn()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class HostedayChannel:
|
|
39
|
+
"""Represents a tracked public, private, or private-encrypted channel."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
*,
|
|
44
|
+
name: str,
|
|
45
|
+
channel_type: HostedayChannelType,
|
|
46
|
+
client: HostedayRealtimeClient,
|
|
47
|
+
) -> None:
|
|
48
|
+
self.name: str = name
|
|
49
|
+
self.channel_type: HostedayChannelType = channel_type
|
|
50
|
+
self._client: HostedayRealtimeClient = client
|
|
51
|
+
self._listeners: dict[str, list[RealtimeEventHandler]] = {}
|
|
52
|
+
self.is_subscribed: bool = False
|
|
53
|
+
self.shared_secret: bytes | None = None
|
|
54
|
+
|
|
55
|
+
def bind(self, event_name: str, handler: RealtimeEventHandler) -> ChannelSubscription:
|
|
56
|
+
"""Registers an event listener for ``event_name`` and returns a cancellable handle."""
|
|
57
|
+
bucket = self._listeners.setdefault(event_name, [])
|
|
58
|
+
bucket.append(handler)
|
|
59
|
+
|
|
60
|
+
def _cancel() -> None:
|
|
61
|
+
handlers = self._listeners.get(event_name)
|
|
62
|
+
if handlers and handler in handlers:
|
|
63
|
+
handlers.remove(handler)
|
|
64
|
+
if not handlers:
|
|
65
|
+
self._listeners.pop(event_name, None)
|
|
66
|
+
|
|
67
|
+
return ChannelSubscription(_cancel)
|
|
68
|
+
|
|
69
|
+
async def whisper(self, event_name: str, data: Mapping[str, Any]) -> None:
|
|
70
|
+
"""Sends a client-to-client whisper event (auto-prefixing ``client-``) on a subscribed private/presence channel."""
|
|
71
|
+
if self.channel_type is HostedayChannelType.PUBLIC:
|
|
72
|
+
raise ValueError("Whisper (client-to-client) events require a private or presence channel.")
|
|
73
|
+
if not self.is_subscribed:
|
|
74
|
+
from hosteday.exceptions import HostedayException
|
|
75
|
+
|
|
76
|
+
raise HostedayException(
|
|
77
|
+
f'Cannot send whisper on "{self.name}" before subscription has succeeded.'
|
|
78
|
+
)
|
|
79
|
+
clean_event = event_name.strip()
|
|
80
|
+
if not clean_event:
|
|
81
|
+
raise ValueError("Whisper event name cannot be empty.")
|
|
82
|
+
prefixed = clean_event if clean_event.startswith("client-") else f"client-{clean_event}"
|
|
83
|
+
await self._client.send_client_event(
|
|
84
|
+
channel_name=self.name,
|
|
85
|
+
event_name=prefixed,
|
|
86
|
+
data=dict(data),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def dispatch_event(self, event_name: str, data: Any, *, raw: Any = None) -> None:
|
|
90
|
+
"""Handles an incoming Pusher/Reverb event on this channel."""
|
|
91
|
+
if event_name == "pusher:subscription_succeeded":
|
|
92
|
+
self.is_subscribed = True
|
|
93
|
+
|
|
94
|
+
effective_data = data
|
|
95
|
+
if (
|
|
96
|
+
self.channel_type is HostedayChannelType.PRIVATE_ENCRYPTED
|
|
97
|
+
and self.shared_secret is not None
|
|
98
|
+
and not event_name.startswith("pusher:")
|
|
99
|
+
):
|
|
100
|
+
effective_data = self._decrypt_payload(data, self.shared_secret)
|
|
101
|
+
|
|
102
|
+
event = HostedayRealtimeEvent.from_raw(
|
|
103
|
+
name=event_name,
|
|
104
|
+
channel_name=self.name,
|
|
105
|
+
data=effective_data,
|
|
106
|
+
raw=raw,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
handlers = list(self._listeners.get(event_name, ()))
|
|
110
|
+
if event_name.startswith("."):
|
|
111
|
+
stripped = event_name[1:]
|
|
112
|
+
for h in self._listeners.get(stripped, ()):
|
|
113
|
+
if h not in handlers:
|
|
114
|
+
handlers.append(h)
|
|
115
|
+
for handler in handlers:
|
|
116
|
+
result = handler(event)
|
|
117
|
+
if inspect.isawaitable(result):
|
|
118
|
+
asyncio.ensure_future(self._run_async_handler(result))
|
|
119
|
+
|
|
120
|
+
@staticmethod
|
|
121
|
+
async def _run_async_handler(awaitable: Awaitable[Any]) -> None:
|
|
122
|
+
await awaitable
|
|
123
|
+
|
|
124
|
+
@staticmethod
|
|
125
|
+
def _decrypt_payload(data: Any, shared_secret: bytes) -> Any:
|
|
126
|
+
payload_obj: Mapping[str, Any] | None = None
|
|
127
|
+
if isinstance(data, Mapping):
|
|
128
|
+
payload_obj = data
|
|
129
|
+
elif isinstance(data, str):
|
|
130
|
+
try:
|
|
131
|
+
parsed = json.loads(data)
|
|
132
|
+
if isinstance(parsed, Mapping):
|
|
133
|
+
payload_obj = parsed
|
|
134
|
+
except json.JSONDecodeError:
|
|
135
|
+
return data
|
|
136
|
+
|
|
137
|
+
if payload_obj is None:
|
|
138
|
+
return data
|
|
139
|
+
ciphertext_b64 = payload_obj.get("ciphertext")
|
|
140
|
+
nonce_b64 = payload_obj.get("nonce")
|
|
141
|
+
if not isinstance(ciphertext_b64, str) or not isinstance(nonce_b64, str):
|
|
142
|
+
return data
|
|
143
|
+
|
|
144
|
+
try:
|
|
145
|
+
from nacl.secret import SecretBox # type: ignore[import-not-found]
|
|
146
|
+
except ImportError as exc:
|
|
147
|
+
raise ImportError(
|
|
148
|
+
"Decrypting private-encrypted channels requires PyNaCl. "
|
|
149
|
+
"Install it with: pip install hosteday_python[crypto]"
|
|
150
|
+
) from exc
|
|
151
|
+
|
|
152
|
+
box = SecretBox(shared_secret)
|
|
153
|
+
decrypted = box.decrypt(
|
|
154
|
+
base64.b64decode(ciphertext_b64),
|
|
155
|
+
nonce=base64.b64decode(nonce_b64),
|
|
156
|
+
)
|
|
157
|
+
return decrypted.decode("utf-8")
|
|
158
|
+
|
|
159
|
+
def clear_listeners(self) -> None:
|
|
160
|
+
self._listeners.clear()
|
|
161
|
+
self.is_subscribed = False
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class PresenceChannel(HostedayChannel):
|
|
165
|
+
"""Presence channel tracking currently connected members."""
|
|
166
|
+
|
|
167
|
+
def __init__(self, *, name: str, client: HostedayRealtimeClient) -> None:
|
|
168
|
+
super().__init__(
|
|
169
|
+
name=name,
|
|
170
|
+
channel_type=HostedayChannelType.PRESENCE,
|
|
171
|
+
client=client,
|
|
172
|
+
)
|
|
173
|
+
self._members: dict[str, dict[str, Any]] = {}
|
|
174
|
+
|
|
175
|
+
@property
|
|
176
|
+
def members(self) -> dict[str, dict[str, Any]]:
|
|
177
|
+
"""Snapshot copy of currently connected presence members keyed by user ID."""
|
|
178
|
+
return dict(self._members)
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def members_count(self) -> int:
|
|
182
|
+
return len(self._members)
|
|
183
|
+
|
|
184
|
+
def build_presence_snapshot_payload(self) -> dict[str, Any]:
|
|
185
|
+
"""Builds the canonical Pusher ``subscription_succeeded`` presence snapshot."""
|
|
186
|
+
return {
|
|
187
|
+
"presence": {
|
|
188
|
+
"count": len(self._members),
|
|
189
|
+
"ids": list(self._members.keys()),
|
|
190
|
+
"hash": {k: dict(v) for k, v in self._members.items()},
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
def dispatch_event(self, event_name: str, data: Any, *, raw: Any = None) -> None:
|
|
195
|
+
normalized = HostedayRealtimeEvent.from_raw(
|
|
196
|
+
name=event_name,
|
|
197
|
+
channel_name=self.name,
|
|
198
|
+
data=data,
|
|
199
|
+
raw=raw,
|
|
200
|
+
).payload
|
|
201
|
+
|
|
202
|
+
if event_name == "pusher:subscription_succeeded":
|
|
203
|
+
presence_raw = normalized.get("presence")
|
|
204
|
+
if isinstance(presence_raw, str):
|
|
205
|
+
try:
|
|
206
|
+
presence_obj: Mapping[str, Any] = json.loads(presence_raw)
|
|
207
|
+
except json.JSONDecodeError:
|
|
208
|
+
presence_obj = normalized
|
|
209
|
+
elif isinstance(presence_raw, Mapping):
|
|
210
|
+
presence_obj = presence_raw
|
|
211
|
+
else:
|
|
212
|
+
presence_obj = normalized
|
|
213
|
+
|
|
214
|
+
hash_raw = presence_obj.get("hash")
|
|
215
|
+
if isinstance(hash_raw, str):
|
|
216
|
+
try:
|
|
217
|
+
parsed_hash = json.loads(hash_raw)
|
|
218
|
+
member_hash: Mapping[str, Any] | None = (
|
|
219
|
+
parsed_hash if isinstance(parsed_hash, Mapping) else None
|
|
220
|
+
)
|
|
221
|
+
except json.JSONDecodeError:
|
|
222
|
+
member_hash = None
|
|
223
|
+
elif isinstance(hash_raw, Mapping):
|
|
224
|
+
member_hash = hash_raw
|
|
225
|
+
else:
|
|
226
|
+
member_hash = None
|
|
227
|
+
|
|
228
|
+
self._members.clear()
|
|
229
|
+
if member_hash is not None:
|
|
230
|
+
for member_id, info in member_hash.items():
|
|
231
|
+
self._members[str(member_id)] = (
|
|
232
|
+
dict(info) if isinstance(info, Mapping) else {"id": str(member_id)}
|
|
233
|
+
)
|
|
234
|
+
elif isinstance(presence_obj.get("ids"), list):
|
|
235
|
+
for member_id in presence_obj["ids"]:
|
|
236
|
+
sid = str(member_id)
|
|
237
|
+
self._members[sid] = {"id": sid}
|
|
238
|
+
elif event_name == "pusher:member_added":
|
|
239
|
+
added_id = normalized.get("id")
|
|
240
|
+
if added_id is None:
|
|
241
|
+
added_id = normalized.get("user_id")
|
|
242
|
+
if added_id is not None:
|
|
243
|
+
info = normalized.get("info")
|
|
244
|
+
self._members[str(added_id)] = (
|
|
245
|
+
dict(info) if isinstance(info, Mapping) else {"id": str(added_id)}
|
|
246
|
+
)
|
|
247
|
+
elif event_name == "pusher:member_removed":
|
|
248
|
+
removed_id = normalized.get("id")
|
|
249
|
+
if removed_id is None:
|
|
250
|
+
removed_id = normalized.get("user_id")
|
|
251
|
+
if removed_id is not None:
|
|
252
|
+
self._members.pop(str(removed_id), None)
|
|
253
|
+
|
|
254
|
+
super().dispatch_event(event_name, data, raw=raw)
|
|
255
|
+
|
|
256
|
+
def clear_listeners(self) -> None:
|
|
257
|
+
super().clear_listeners()
|
|
258
|
+
self._members.clear()
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Dynamic broadcasting channel authorization delegate for private, presence, and encrypted channels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from hosteday.exceptions import HostedayRealtimeAuthorizationException
|
|
14
|
+
from hosteday.realtime.hosteday_channel_type import HostedayChannelType
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class ChannelAuthData:
|
|
19
|
+
"""Authorization credentials returned by ``/api/broadcasting/auth-manual``."""
|
|
20
|
+
|
|
21
|
+
auth: str
|
|
22
|
+
channel_data: str | None = None
|
|
23
|
+
shared_secret: bytes | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
HeadersBuilder = Callable[[], Awaitable[Mapping[str, str]]]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class HostedayChannelAuthorizationDelegate:
|
|
30
|
+
"""Executes dynamic header evaluation on every broadcasting authorization request."""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
*,
|
|
35
|
+
authorization_endpoint: str,
|
|
36
|
+
headers_builder: HeadersBuilder,
|
|
37
|
+
http_client: httpx.AsyncClient | None = None,
|
|
38
|
+
timeout: float = 15.0,
|
|
39
|
+
) -> None:
|
|
40
|
+
self.authorization_endpoint = authorization_endpoint
|
|
41
|
+
self.headers_builder = headers_builder
|
|
42
|
+
self._http_client = http_client
|
|
43
|
+
self._timeout = timeout
|
|
44
|
+
|
|
45
|
+
async def authorize(
|
|
46
|
+
self,
|
|
47
|
+
*,
|
|
48
|
+
socket_id: str,
|
|
49
|
+
channel_name: str,
|
|
50
|
+
channel_type: HostedayChannelType,
|
|
51
|
+
) -> ChannelAuthData:
|
|
52
|
+
"""Authorizes ``channel_name`` for ``socket_id`` using form URL-encoded POST."""
|
|
53
|
+
dynamic_headers = dict(await self.headers_builder())
|
|
54
|
+
auth_header = dynamic_headers.get("Authorization") or dynamic_headers.get("authorization")
|
|
55
|
+
if not auth_header or not auth_header.strip():
|
|
56
|
+
raise HostedayRealtimeAuthorizationException(
|
|
57
|
+
f'Missing dynamic Authorization bearer token when authorizing channel "{channel_name}".',
|
|
58
|
+
status_code=401,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
headers = {
|
|
62
|
+
**dynamic_headers,
|
|
63
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
64
|
+
}
|
|
65
|
+
form_body = {
|
|
66
|
+
"socket_id": socket_id,
|
|
67
|
+
"channel_name": channel_name,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if self._http_client is not None:
|
|
71
|
+
response = await self._http_client.post(
|
|
72
|
+
self.authorization_endpoint,
|
|
73
|
+
headers=headers,
|
|
74
|
+
data=form_body,
|
|
75
|
+
timeout=self._timeout,
|
|
76
|
+
)
|
|
77
|
+
else:
|
|
78
|
+
async with httpx.AsyncClient(timeout=self._timeout) as temp_client:
|
|
79
|
+
response = await temp_client.post(
|
|
80
|
+
self.authorization_endpoint,
|
|
81
|
+
headers=headers,
|
|
82
|
+
data=form_body,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if response.status_code != 200:
|
|
86
|
+
raise HostedayRealtimeAuthorizationException(
|
|
87
|
+
f'Broadcasting channel authorization failed with HTTP {response.status_code} '
|
|
88
|
+
f'for "{channel_name}": {response.text}',
|
|
89
|
+
status_code=response.status_code,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
return self.parse_response(response.text, channel_type=channel_type)
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def parse_response(
|
|
96
|
+
raw_body: str,
|
|
97
|
+
*,
|
|
98
|
+
channel_type: HostedayChannelType,
|
|
99
|
+
) -> ChannelAuthData:
|
|
100
|
+
"""Parses standard ``{auth, channel_data}`` and HosteDay ``{data: {auth, ...}}`` envelopes."""
|
|
101
|
+
try:
|
|
102
|
+
decoded: Any = json.loads(raw_body)
|
|
103
|
+
except json.JSONDecodeError as exc:
|
|
104
|
+
raise HostedayRealtimeAuthorizationException(
|
|
105
|
+
"Invalid JSON returned by broadcasting auth endpoint.",
|
|
106
|
+
status_code=200,
|
|
107
|
+
error=exc,
|
|
108
|
+
) from exc
|
|
109
|
+
|
|
110
|
+
payload: Mapping[str, Any] | None = None
|
|
111
|
+
if isinstance(decoded, Mapping):
|
|
112
|
+
if "auth" in decoded:
|
|
113
|
+
payload = decoded
|
|
114
|
+
elif isinstance(decoded.get("data"), Mapping) and "auth" in decoded["data"]:
|
|
115
|
+
payload = decoded["data"]
|
|
116
|
+
|
|
117
|
+
if payload is None:
|
|
118
|
+
raise HostedayRealtimeAuthorizationException(
|
|
119
|
+
f'Broadcasting auth endpoint returned payload without "auth" key: {raw_body}',
|
|
120
|
+
status_code=200,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
auth_raw = payload.get("auth")
|
|
124
|
+
auth = str(auth_raw).strip() if auth_raw is not None else ""
|
|
125
|
+
if not auth:
|
|
126
|
+
raise HostedayRealtimeAuthorizationException(
|
|
127
|
+
'Broadcasting auth endpoint returned empty "auth" key.',
|
|
128
|
+
status_code=200,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
channel_data: str | None = None
|
|
132
|
+
if channel_type is HostedayChannelType.PRESENCE:
|
|
133
|
+
raw_channel_data = payload.get("channel_data")
|
|
134
|
+
if isinstance(raw_channel_data, str):
|
|
135
|
+
cleaned_cd = raw_channel_data.strip()
|
|
136
|
+
channel_data = cleaned_cd if cleaned_cd else "{}"
|
|
137
|
+
elif raw_channel_data is not None:
|
|
138
|
+
channel_data = json.dumps(raw_channel_data, separators=(",", ":"))
|
|
139
|
+
else:
|
|
140
|
+
channel_data = "{}"
|
|
141
|
+
|
|
142
|
+
shared_secret: bytes | None = None
|
|
143
|
+
if channel_type is HostedayChannelType.PRIVATE_ENCRYPTED:
|
|
144
|
+
raw_secret = payload.get("shared_secret")
|
|
145
|
+
if not isinstance(raw_secret, str) or not raw_secret.strip():
|
|
146
|
+
raise HostedayRealtimeAuthorizationException(
|
|
147
|
+
'Private encrypted channel auth payload is missing "shared_secret".',
|
|
148
|
+
status_code=200,
|
|
149
|
+
)
|
|
150
|
+
try:
|
|
151
|
+
shared_secret = base64.b64decode(raw_secret)
|
|
152
|
+
except Exception as exc:
|
|
153
|
+
raise HostedayRealtimeAuthorizationException(
|
|
154
|
+
'Invalid base64 "shared_secret" returned by broadcasting auth endpoint.',
|
|
155
|
+
status_code=200,
|
|
156
|
+
error=exc,
|
|
157
|
+
) from exc
|
|
158
|
+
|
|
159
|
+
return ChannelAuthData(
|
|
160
|
+
auth=auth,
|
|
161
|
+
channel_data=channel_data,
|
|
162
|
+
shared_secret=shared_secret,
|
|
163
|
+
)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Realtime channel types and strict prefix normalization rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import Enum
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class HostedayChannelType(str, Enum):
|
|
9
|
+
"""Supported HosteDay / Pusher v7 channel types."""
|
|
10
|
+
|
|
11
|
+
PUBLIC = "public"
|
|
12
|
+
PRIVATE = "private"
|
|
13
|
+
PRESENCE = "presence"
|
|
14
|
+
PRIVATE_ENCRYPTED = "private_encrypted"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def normalize_channel_name(channel_name: str, channel_type: HostedayChannelType) -> str:
|
|
18
|
+
"""Normalizes and validates a channel name according to strict HosteDay prefix rules."""
|
|
19
|
+
cleaned = channel_name.strip()
|
|
20
|
+
if not cleaned:
|
|
21
|
+
raise ValueError("Channel name cannot be empty.")
|
|
22
|
+
|
|
23
|
+
if channel_type is HostedayChannelType.PUBLIC:
|
|
24
|
+
if cleaned.startswith(("private-", "presence-", "private-encrypted-")):
|
|
25
|
+
raise ValueError(
|
|
26
|
+
f"Public channel '{cleaned}' cannot start with 'private-', 'presence-', "
|
|
27
|
+
"or 'private-encrypted-'."
|
|
28
|
+
)
|
|
29
|
+
return cleaned
|
|
30
|
+
|
|
31
|
+
if channel_type is HostedayChannelType.PRIVATE:
|
|
32
|
+
if cleaned.startswith(("presence-", "private-encrypted-")):
|
|
33
|
+
raise ValueError(
|
|
34
|
+
f"Private channel '{cleaned}' cannot use 'presence-' or 'private-encrypted-'."
|
|
35
|
+
)
|
|
36
|
+
return cleaned if cleaned.startswith("private-") else f"private-{cleaned}"
|
|
37
|
+
|
|
38
|
+
if channel_type is HostedayChannelType.PRESENCE:
|
|
39
|
+
if cleaned.startswith(("private-", "private-encrypted-")):
|
|
40
|
+
raise ValueError(
|
|
41
|
+
f"Presence channel '{cleaned}' cannot use 'private-' or 'private-encrypted-'."
|
|
42
|
+
)
|
|
43
|
+
return cleaned if cleaned.startswith("presence-") else f"presence-{cleaned}"
|
|
44
|
+
|
|
45
|
+
if channel_type is HostedayChannelType.PRIVATE_ENCRYPTED:
|
|
46
|
+
if cleaned.startswith("presence-"):
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"Private encrypted channel '{cleaned}' cannot use 'presence-'."
|
|
49
|
+
)
|
|
50
|
+
if cleaned.startswith("private-encrypted-"):
|
|
51
|
+
return cleaned
|
|
52
|
+
if cleaned.startswith("private-"):
|
|
53
|
+
return f"private-encrypted-{cleaned[len('private-'):]}"
|
|
54
|
+
return f"private-encrypted-{cleaned}"
|
|
55
|
+
|
|
56
|
+
raise ValueError(f"Unsupported channel type: {channel_type}")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def infer_channel_type(channel_name: str) -> HostedayChannelType:
|
|
60
|
+
"""Infers the ``HostedayChannelType`` from a channel name prefix."""
|
|
61
|
+
cleaned = channel_name.strip()
|
|
62
|
+
if cleaned.startswith("presence-"):
|
|
63
|
+
return HostedayChannelType.PRESENCE
|
|
64
|
+
if cleaned.startswith("private-encrypted-"):
|
|
65
|
+
return HostedayChannelType.PRIVATE_ENCRYPTED
|
|
66
|
+
if cleaned.startswith("private-"):
|
|
67
|
+
return HostedayChannelType.PRIVATE
|
|
68
|
+
return HostedayChannelType.PUBLIC
|