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
hosteday/web/server.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
"""Embedded ``HostedayWebApp`` hiding FastAPI/Uvicorn behind a clean HosteDay BFF & SPA interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Callable, Mapping
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, TypeVar
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
import uvicorn
|
|
12
|
+
from fastapi import FastAPI, Request, UploadFile
|
|
13
|
+
from fastapi.responses import FileResponse, JSONResponse
|
|
14
|
+
from fastapi.staticfiles import StaticFiles
|
|
15
|
+
|
|
16
|
+
from hosteday.auth.hosteday_auth_storage import (
|
|
17
|
+
HostedayAuthStorage,
|
|
18
|
+
JsonFileHostedayAuthStorage,
|
|
19
|
+
)
|
|
20
|
+
from hosteday.auth.hosteday_user import HostedayUser
|
|
21
|
+
from hosteday.config.hosteday_config import HostedayConfig
|
|
22
|
+
from hosteday.exceptions import HostedayAuthException, HostedayException
|
|
23
|
+
from hosteday.realtime.hosteday_channel_auth import HostedayChannelAuthorizationDelegate
|
|
24
|
+
from hosteday.realtime.hosteday_channel_type import infer_channel_type
|
|
25
|
+
|
|
26
|
+
_HandlerT = TypeVar("_HandlerT", bound=Callable[..., Any])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class HostedayWebError(Exception):
|
|
30
|
+
"""High-level HTTP error raised by custom ``HostedayWebApp`` route handlers."""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
status_code: int = 400,
|
|
35
|
+
message: str = "Bad Request",
|
|
36
|
+
*,
|
|
37
|
+
details: Any = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.status_code = status_code
|
|
41
|
+
self.message = message
|
|
42
|
+
self.details = details
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _serialize_user(user: HostedayUser | None) -> dict[str, Any] | None:
|
|
46
|
+
if user is None:
|
|
47
|
+
return None
|
|
48
|
+
return {
|
|
49
|
+
"id": user.id,
|
|
50
|
+
"name": user.display_name or user.email or "HosteDay",
|
|
51
|
+
"email": user.email or "",
|
|
52
|
+
"is_email_verified": bool(user.is_email_verified),
|
|
53
|
+
"avatar_url": _resolve_avatar_url(user),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _resolve_avatar_url(user: HostedayUser) -> str | None:
|
|
58
|
+
from hosteday.hosteday import Hosteday
|
|
59
|
+
|
|
60
|
+
candidates: list[str] = []
|
|
61
|
+
if user.photo_url:
|
|
62
|
+
candidates.append(str(user.photo_url).strip())
|
|
63
|
+
raw = getattr(user, "raw_data", None)
|
|
64
|
+
if isinstance(raw, Mapping):
|
|
65
|
+
for field in ("avatar_url", "photo_url", "avatar", "photo", "profile_photo_url"):
|
|
66
|
+
val = raw.get(field)
|
|
67
|
+
if isinstance(val, str) and val.strip():
|
|
68
|
+
candidates.append(val.strip())
|
|
69
|
+
for candidate in candidates:
|
|
70
|
+
if candidate.startswith(("http://", "https://")):
|
|
71
|
+
return candidate
|
|
72
|
+
if Hosteday.is_initialized:
|
|
73
|
+
try:
|
|
74
|
+
return Hosteday.client.storage_url(candidate)
|
|
75
|
+
except Exception:
|
|
76
|
+
return candidate
|
|
77
|
+
return candidate
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _build_public_browser_config(config: HostedayConfig) -> dict[str, Any]:
|
|
82
|
+
"""Builds browser-safe public configuration (never exposes ``project_api_key``)."""
|
|
83
|
+
firebase: dict[str, str] = {}
|
|
84
|
+
if config.firebase_api_key:
|
|
85
|
+
firebase["apiKey"] = config.firebase_api_key
|
|
86
|
+
if config.firebase_auth_domain:
|
|
87
|
+
firebase["authDomain"] = config.firebase_auth_domain
|
|
88
|
+
if config.firebase_project_id:
|
|
89
|
+
firebase["projectId"] = config.firebase_project_id
|
|
90
|
+
if config.firebase_storage_bucket:
|
|
91
|
+
firebase["storageBucket"] = config.firebase_storage_bucket
|
|
92
|
+
if config.firebase_messaging_sender_id:
|
|
93
|
+
firebase["messagingSenderId"] = config.firebase_messaging_sender_id
|
|
94
|
+
if config.firebase_app_id:
|
|
95
|
+
firebase["appId"] = config.firebase_app_id
|
|
96
|
+
if config.firebase_measurement_id:
|
|
97
|
+
firebase["measurementId"] = config.firebase_measurement_id
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
"appName": config.app_name or "HosteDay App",
|
|
101
|
+
"realtime": {
|
|
102
|
+
"enabled": bool(config.has_realtime and config.features.is_realtime_enabled),
|
|
103
|
+
"wsUrl": config.realtime_url if config.has_realtime else "",
|
|
104
|
+
"key": config.pusher_key,
|
|
105
|
+
"host": config.urls.normalize_realtime_host(config.realtime_host)
|
|
106
|
+
if config.realtime_host
|
|
107
|
+
else "",
|
|
108
|
+
"port": config.urls.resolve_realtime_port(
|
|
109
|
+
scheme=config.realtime_scheme,
|
|
110
|
+
host=config.realtime_host,
|
|
111
|
+
port=config.realtime_port,
|
|
112
|
+
)
|
|
113
|
+
if config.realtime_host
|
|
114
|
+
else 443,
|
|
115
|
+
"scheme": config.realtime_scheme,
|
|
116
|
+
},
|
|
117
|
+
"firebase": firebase,
|
|
118
|
+
"vapidKey": config.firebase_vapid_key or "",
|
|
119
|
+
"hasFirebaseConfig": config.has_firebase_config,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
async def _read_json_body(request: Request) -> dict[str, Any]:
|
|
124
|
+
try:
|
|
125
|
+
parsed = await request.json()
|
|
126
|
+
except Exception as exc:
|
|
127
|
+
raise HostedayWebError(400, "Invalid JSON request body.") from exc
|
|
128
|
+
if not isinstance(parsed, Mapping):
|
|
129
|
+
raise HostedayWebError(400, "Request body must be a JSON object.")
|
|
130
|
+
return dict(parsed)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class HostedayWebApp:
|
|
134
|
+
"""High-level embedded web server & BFF powered by ``hosteday_python``."""
|
|
135
|
+
|
|
136
|
+
def __init__(
|
|
137
|
+
self,
|
|
138
|
+
*,
|
|
139
|
+
title: str = "HosteDay Web App",
|
|
140
|
+
config: HostedayConfig | None = None,
|
|
141
|
+
options: Mapping[str, Any] | None = None,
|
|
142
|
+
config_path: str | Path | None = None,
|
|
143
|
+
firebase_config_path: str | Path | None = None,
|
|
144
|
+
auth_storage: HostedayAuthStorage | None = None,
|
|
145
|
+
session_path: str | Path | None = None,
|
|
146
|
+
static_dir: str | Path | None = None,
|
|
147
|
+
connect_realtime: bool = False,
|
|
148
|
+
enable_active_probe: bool = True,
|
|
149
|
+
http_client: httpx.AsyncClient | None = None,
|
|
150
|
+
auto_initialize: bool = True,
|
|
151
|
+
) -> None:
|
|
152
|
+
self._title = title
|
|
153
|
+
self._config = config
|
|
154
|
+
self._options = options
|
|
155
|
+
self._config_path = Path(config_path) if config_path is not None else None
|
|
156
|
+
self._firebase_config_path = (
|
|
157
|
+
Path(firebase_config_path) if firebase_config_path is not None else None
|
|
158
|
+
)
|
|
159
|
+
self._auth_storage = auth_storage or (
|
|
160
|
+
JsonFileHostedayAuthStorage(Path(session_path)) if session_path is not None else None
|
|
161
|
+
)
|
|
162
|
+
self._static_dir = Path(static_dir) if static_dir is not None else None
|
|
163
|
+
self._connect_realtime = connect_realtime
|
|
164
|
+
self._enable_active_probe = enable_active_probe
|
|
165
|
+
self._http_client = http_client
|
|
166
|
+
self._auto_initialize = auto_initialize
|
|
167
|
+
self._owned_sdk_lifecycle = False
|
|
168
|
+
|
|
169
|
+
self._app = FastAPI(title=title, lifespan=self._lifespan)
|
|
170
|
+
self._register_error_handlers()
|
|
171
|
+
self._register_builtin_routes()
|
|
172
|
+
self._mount_static_assets()
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def asgi_app(self) -> Any:
|
|
176
|
+
"""Exposes the underlying ASGI callable for testing or custom ASGI runners."""
|
|
177
|
+
return self._app
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def app(self) -> Any:
|
|
181
|
+
"""Alias for :attr:`asgi_app`."""
|
|
182
|
+
return self._app
|
|
183
|
+
|
|
184
|
+
@asynccontextmanager
|
|
185
|
+
async def _lifespan(self, _app: FastAPI) -> AsyncIterator[None]:
|
|
186
|
+
from hosteday.hosteday import Hosteday
|
|
187
|
+
|
|
188
|
+
if self._auto_initialize and not Hosteday.is_initialized:
|
|
189
|
+
await Hosteday.initialize_app(
|
|
190
|
+
config=self._config,
|
|
191
|
+
options=self._options,
|
|
192
|
+
config_path=self._config_path,
|
|
193
|
+
firebase_config_path=self._firebase_config_path,
|
|
194
|
+
auth_storage=self._auth_storage,
|
|
195
|
+
connect_realtime=self._connect_realtime,
|
|
196
|
+
enable_active_probe=self._enable_active_probe,
|
|
197
|
+
http_client=self._http_client,
|
|
198
|
+
)
|
|
199
|
+
self._owned_sdk_lifecycle = True
|
|
200
|
+
try:
|
|
201
|
+
yield
|
|
202
|
+
finally:
|
|
203
|
+
if self._owned_sdk_lifecycle and Hosteday.is_initialized:
|
|
204
|
+
self._owned_sdk_lifecycle = False
|
|
205
|
+
await Hosteday.dispose()
|
|
206
|
+
|
|
207
|
+
def _register_error_handlers(self) -> None:
|
|
208
|
+
@self._app.exception_handler(HostedayWebError)
|
|
209
|
+
async def _handle_web_error(_request: Request, exc: HostedayWebError) -> JSONResponse:
|
|
210
|
+
payload: dict[str, Any] = {"detail": exc.message}
|
|
211
|
+
if exc.details is not None:
|
|
212
|
+
payload["details"] = exc.details
|
|
213
|
+
return JSONResponse(status_code=exc.status_code, content=payload)
|
|
214
|
+
|
|
215
|
+
@self._app.exception_handler(HostedayException)
|
|
216
|
+
async def _handle_sdk_error(_request: Request, exc: HostedayException) -> JSONResponse:
|
|
217
|
+
status = (
|
|
218
|
+
exc.status_code
|
|
219
|
+
if isinstance(exc.status_code, int) and 400 <= exc.status_code < 600
|
|
220
|
+
else 400
|
|
221
|
+
)
|
|
222
|
+
return JSONResponse(status_code=status, content={"detail": exc.display_message})
|
|
223
|
+
|
|
224
|
+
def _register_builtin_routes(self) -> None:
|
|
225
|
+
from hosteday.hosteday import Hosteday
|
|
226
|
+
|
|
227
|
+
async def _public_config() -> dict[str, Any]:
|
|
228
|
+
if not Hosteday.is_initialized:
|
|
229
|
+
raise HostedayWebError(503, "Service is initializing.")
|
|
230
|
+
return {
|
|
231
|
+
"config": _build_public_browser_config(Hosteday.config),
|
|
232
|
+
"online": Hosteday.is_online,
|
|
233
|
+
"user": _serialize_user(Hosteday.auth.current_user),
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
self._app.add_api_route("/bff/config/public", _public_config, methods=["GET"])
|
|
237
|
+
self._app.add_api_route("/bff/public-config", _public_config, methods=["GET"])
|
|
238
|
+
|
|
239
|
+
@self._app.get("/bff/connectivity")
|
|
240
|
+
async def _connectivity() -> dict[str, Any]:
|
|
241
|
+
if not Hosteday.is_initialized:
|
|
242
|
+
return {"online": False}
|
|
243
|
+
return {"online": await Hosteday.connectivity.check_now()}
|
|
244
|
+
|
|
245
|
+
@self._app.get("/bff/auth/me")
|
|
246
|
+
async def _auth_me() -> dict[str, Any]:
|
|
247
|
+
if not Hosteday.is_initialized:
|
|
248
|
+
return {"user": None}
|
|
249
|
+
return {"user": _serialize_user(Hosteday.auth.current_user)}
|
|
250
|
+
|
|
251
|
+
@self._app.post("/bff/auth/login")
|
|
252
|
+
async def _auth_login(request: Request) -> dict[str, Any]:
|
|
253
|
+
body = await _read_json_body(request)
|
|
254
|
+
email = str(body.get("email") or "").strip()
|
|
255
|
+
password = str(body.get("password") or "")
|
|
256
|
+
if not email or not password:
|
|
257
|
+
raise HostedayWebError(422, "Email and password are required.")
|
|
258
|
+
cred = await Hosteday.auth.sign_in_with_email_and_password(
|
|
259
|
+
email=email,
|
|
260
|
+
password=password,
|
|
261
|
+
)
|
|
262
|
+
return {"user": _serialize_user(cred.user)}
|
|
263
|
+
|
|
264
|
+
@self._app.post("/bff/auth/register")
|
|
265
|
+
async def _auth_register(request: Request) -> dict[str, Any]:
|
|
266
|
+
body = await _read_json_body(request)
|
|
267
|
+
email = str(body.get("email") or "").strip()
|
|
268
|
+
password = str(body.get("password") or "")
|
|
269
|
+
name = str(body.get("name") or "").strip()
|
|
270
|
+
if not email or not password:
|
|
271
|
+
raise HostedayWebError(422, "Email and password are required.")
|
|
272
|
+
extra = {"name": name} if name else None
|
|
273
|
+
cred = await Hosteday.auth.create_user_with_email_and_password(
|
|
274
|
+
email=email,
|
|
275
|
+
password=password,
|
|
276
|
+
additional_data=extra,
|
|
277
|
+
)
|
|
278
|
+
return {"user": _serialize_user(cred.user)}
|
|
279
|
+
|
|
280
|
+
@self._app.post("/bff/auth/logout")
|
|
281
|
+
async def _auth_logout() -> dict[str, Any]:
|
|
282
|
+
try:
|
|
283
|
+
await Hosteday.auth.sign_out()
|
|
284
|
+
except (HostedayAuthException, HostedayException):
|
|
285
|
+
pass
|
|
286
|
+
return {"ok": True}
|
|
287
|
+
|
|
288
|
+
@self._app.post("/bff/auth/reload")
|
|
289
|
+
async def _auth_reload() -> dict[str, Any]:
|
|
290
|
+
await Hosteday.auth.reload()
|
|
291
|
+
return {"user": _serialize_user(Hosteday.auth.current_user)}
|
|
292
|
+
|
|
293
|
+
async def _update_profile(request: Request) -> dict[str, Any]:
|
|
294
|
+
body = await _read_json_body(request)
|
|
295
|
+
name = str(body.get("name") or "").strip()
|
|
296
|
+
if not name:
|
|
297
|
+
raise HostedayWebError(422, "Display name is required.")
|
|
298
|
+
user = await Hosteday.auth.update_profile(name=name)
|
|
299
|
+
return {"user": _serialize_user(user)}
|
|
300
|
+
|
|
301
|
+
self._app.add_api_route("/bff/auth/profile", _update_profile, methods=["PATCH", "PUT"])
|
|
302
|
+
|
|
303
|
+
@self._app.post("/bff/auth/avatar")
|
|
304
|
+
async def _auth_avatar(request: Request) -> dict[str, Any]:
|
|
305
|
+
form = await request.form()
|
|
306
|
+
upload = form.get("file")
|
|
307
|
+
if not isinstance(upload, UploadFile):
|
|
308
|
+
raise HostedayWebError(422, "Avatar image file is required.")
|
|
309
|
+
raw_bytes = await upload.read()
|
|
310
|
+
filename = upload.filename or "avatar.png"
|
|
311
|
+
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "png"
|
|
312
|
+
await Hosteday.auth.update_avatar(data=raw_bytes, extension=ext)
|
|
313
|
+
await Hosteday.auth.reload()
|
|
314
|
+
return {"user": _serialize_user(Hosteday.auth.current_user)}
|
|
315
|
+
|
|
316
|
+
@self._app.post("/bff/auth/verify-email")
|
|
317
|
+
async def _auth_verify_email() -> dict[str, Any]:
|
|
318
|
+
await Hosteday.auth.send_email_verification()
|
|
319
|
+
return {"ok": True}
|
|
320
|
+
|
|
321
|
+
@self._app.post("/bff/auth/forgot-password")
|
|
322
|
+
async def _auth_forgot_password(request: Request) -> dict[str, Any]:
|
|
323
|
+
body = await _read_json_body(request)
|
|
324
|
+
email = str(body.get("email") or "").strip()
|
|
325
|
+
if not email:
|
|
326
|
+
raise HostedayWebError(422, "Email is required.")
|
|
327
|
+
await Hosteday.auth.send_password_reset_email(email=email)
|
|
328
|
+
return {"ok": True}
|
|
329
|
+
|
|
330
|
+
async def _auth_password_reset() -> dict[str, Any]:
|
|
331
|
+
await Hosteday.auth.send_current_user_password_reset_email()
|
|
332
|
+
return {"ok": True}
|
|
333
|
+
|
|
334
|
+
self._app.add_api_route("/bff/auth/password-reset", _auth_password_reset, methods=["POST"])
|
|
335
|
+
self._app.add_api_route("/bff/auth/change-password", _auth_password_reset, methods=["POST"])
|
|
336
|
+
|
|
337
|
+
async def _auth_delete() -> dict[str, Any]:
|
|
338
|
+
await Hosteday.auth.delete_user()
|
|
339
|
+
return {"ok": True}
|
|
340
|
+
|
|
341
|
+
self._app.add_api_route("/bff/auth/delete", _auth_delete, methods=["DELETE"])
|
|
342
|
+
self._app.add_api_route("/bff/auth/account", _auth_delete, methods=["DELETE"])
|
|
343
|
+
|
|
344
|
+
@self._app.post("/bff/realtime/auth")
|
|
345
|
+
async def _realtime_auth(request: Request) -> dict[str, Any]:
|
|
346
|
+
if not Hosteday.is_initialized:
|
|
347
|
+
raise HostedayWebError(503, "Service unavailable.")
|
|
348
|
+
body = await _read_json_body(request)
|
|
349
|
+
socket_id = str(body.get("socket_id") or "").strip()
|
|
350
|
+
channel_name = str(body.get("channel_name") or "").strip()
|
|
351
|
+
if not socket_id or not channel_name:
|
|
352
|
+
raise HostedayWebError(422, "socket_id and channel_name are required.")
|
|
353
|
+
delegate = HostedayChannelAuthorizationDelegate(
|
|
354
|
+
authorization_endpoint=Hosteday.config.uri(Hosteday.config.broadcasting_auth_path),
|
|
355
|
+
headers_builder=Hosteday.realtime.build_authorization_headers,
|
|
356
|
+
http_client=self._http_client,
|
|
357
|
+
)
|
|
358
|
+
auth_res = await delegate.authorize(
|
|
359
|
+
socket_id=socket_id,
|
|
360
|
+
channel_name=channel_name,
|
|
361
|
+
channel_type=infer_channel_type(channel_name),
|
|
362
|
+
)
|
|
363
|
+
response: dict[str, Any] = {"auth": auth_res.auth}
|
|
364
|
+
if auth_res.channel_data is not None:
|
|
365
|
+
response["channel_data"] = auth_res.channel_data
|
|
366
|
+
return response
|
|
367
|
+
|
|
368
|
+
@self._app.post("/bff/notifications/register-device")
|
|
369
|
+
async def _register_device(request: Request) -> dict[str, Any]:
|
|
370
|
+
body = await _read_json_body(request)
|
|
371
|
+
token = str(body.get("token") or "").strip()
|
|
372
|
+
if not token:
|
|
373
|
+
raise HostedayWebError(422, "Device token is required.")
|
|
374
|
+
access_token = await Hosteday.auth.get_access_token()
|
|
375
|
+
await Hosteday.notifications.sync_device_token(
|
|
376
|
+
token=token,
|
|
377
|
+
access_token=access_token,
|
|
378
|
+
device_type=str(body.get("device_type") or "web"),
|
|
379
|
+
device_id=str(body["device_id"]) if body.get("device_id") else None,
|
|
380
|
+
device_name=str(body.get("device_name") or "Web Browser"),
|
|
381
|
+
)
|
|
382
|
+
return {"ok": True}
|
|
383
|
+
|
|
384
|
+
@self._app.post("/bff/notifications/unregister-device")
|
|
385
|
+
async def _unregister_device(request: Request) -> dict[str, Any]:
|
|
386
|
+
body = await _read_json_body(request)
|
|
387
|
+
token = str(body.get("token") or "").strip()
|
|
388
|
+
if not token:
|
|
389
|
+
raise HostedayWebError(422, "Device token is required.")
|
|
390
|
+
await Hosteday.notifications.unregister_device_token(
|
|
391
|
+
token=token,
|
|
392
|
+
device_id=str(body["device_id"]) if body.get("device_id") else None,
|
|
393
|
+
action="unlink",
|
|
394
|
+
)
|
|
395
|
+
return {"ok": True}
|
|
396
|
+
|
|
397
|
+
def _mount_static_assets(self) -> None:
|
|
398
|
+
if self._static_dir is None or not self._static_dir.is_dir():
|
|
399
|
+
return
|
|
400
|
+
|
|
401
|
+
static_root = self._static_dir
|
|
402
|
+
sw_path = static_root / "firebase-messaging-sw.js"
|
|
403
|
+
index_path = static_root / "index.html"
|
|
404
|
+
|
|
405
|
+
if sw_path.is_file():
|
|
406
|
+
|
|
407
|
+
@self._app.get("/firebase-messaging-sw.js", include_in_schema=False)
|
|
408
|
+
async def _service_worker() -> FileResponse:
|
|
409
|
+
return FileResponse(
|
|
410
|
+
sw_path,
|
|
411
|
+
media_type="application/javascript",
|
|
412
|
+
headers={"Service-Worker-Allowed": "/"},
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
if index_path.is_file():
|
|
416
|
+
|
|
417
|
+
@self._app.get("/", include_in_schema=False)
|
|
418
|
+
async def _spa_index() -> FileResponse:
|
|
419
|
+
return FileResponse(index_path)
|
|
420
|
+
|
|
421
|
+
self._app.mount("/static", StaticFiles(directory=str(static_root)), name="static")
|
|
422
|
+
|
|
423
|
+
# ------------------------------------------------------------------
|
|
424
|
+
# Clean Route Registration Helpers (Zero FastAPI Imports for Users)
|
|
425
|
+
# ------------------------------------------------------------------
|
|
426
|
+
|
|
427
|
+
@staticmethod
|
|
428
|
+
def _normalize_route_path(path: str) -> str:
|
|
429
|
+
"""Normalizes clean relative paths (e.g. ``'notes'`` -> ``'/bff/notes'``) while preserving explicit leading ``/``."""
|
|
430
|
+
cleaned = path.strip()
|
|
431
|
+
if not cleaned:
|
|
432
|
+
return "/bff"
|
|
433
|
+
if cleaned.startswith("/"):
|
|
434
|
+
return cleaned
|
|
435
|
+
return f"/bff/{cleaned}"
|
|
436
|
+
|
|
437
|
+
def group(self, prefix: str) -> _RouteGroup:
|
|
438
|
+
"""Creates a prefixed route group (e.g. ``bff = web.group('/bff')``)."""
|
|
439
|
+
return _RouteGroup(self, prefix=prefix)
|
|
440
|
+
|
|
441
|
+
def get(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
442
|
+
"""Registers a custom HTTP GET endpoint on this HosteDay web app."""
|
|
443
|
+
normalized = self._normalize_route_path(path)
|
|
444
|
+
|
|
445
|
+
def _decorator(fn: _HandlerT) -> _HandlerT:
|
|
446
|
+
self._app.add_api_route(normalized, fn, methods=["GET"])
|
|
447
|
+
return fn
|
|
448
|
+
|
|
449
|
+
return _decorator
|
|
450
|
+
|
|
451
|
+
def post(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
452
|
+
"""Registers a custom HTTP POST endpoint on this HosteDay web app."""
|
|
453
|
+
normalized = self._normalize_route_path(path)
|
|
454
|
+
|
|
455
|
+
def _decorator(fn: _HandlerT) -> _HandlerT:
|
|
456
|
+
self._app.add_api_route(normalized, fn, methods=["POST"])
|
|
457
|
+
return fn
|
|
458
|
+
|
|
459
|
+
return _decorator
|
|
460
|
+
|
|
461
|
+
def put(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
462
|
+
"""Registers a custom HTTP PUT endpoint on this HosteDay web app."""
|
|
463
|
+
normalized = self._normalize_route_path(path)
|
|
464
|
+
|
|
465
|
+
def _decorator(fn: _HandlerT) -> _HandlerT:
|
|
466
|
+
self._app.add_api_route(normalized, fn, methods=["PUT"])
|
|
467
|
+
return fn
|
|
468
|
+
|
|
469
|
+
return _decorator
|
|
470
|
+
|
|
471
|
+
def patch(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
472
|
+
"""Registers a custom HTTP PATCH endpoint on this HosteDay web app."""
|
|
473
|
+
normalized = self._normalize_route_path(path)
|
|
474
|
+
|
|
475
|
+
def _decorator(fn: _HandlerT) -> _HandlerT:
|
|
476
|
+
self._app.add_api_route(normalized, fn, methods=["PATCH"])
|
|
477
|
+
return fn
|
|
478
|
+
|
|
479
|
+
return _decorator
|
|
480
|
+
|
|
481
|
+
def delete(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
482
|
+
"""Registers a custom HTTP DELETE endpoint on this HosteDay web app."""
|
|
483
|
+
normalized = self._normalize_route_path(path)
|
|
484
|
+
|
|
485
|
+
def _decorator(fn: _HandlerT) -> _HandlerT:
|
|
486
|
+
self._app.add_api_route(normalized, fn, methods=["DELETE"])
|
|
487
|
+
return fn
|
|
488
|
+
|
|
489
|
+
return _decorator
|
|
490
|
+
|
|
491
|
+
def crud(
|
|
492
|
+
self,
|
|
493
|
+
resource: str,
|
|
494
|
+
*,
|
|
495
|
+
require_auth_write: bool = True,
|
|
496
|
+
owner_field: str | None = None,
|
|
497
|
+
) -> None:
|
|
498
|
+
"""Registers standard ``GET``, ``POST``, ``PUT``, and ``DELETE`` BFF routes for ``resource`` in one call."""
|
|
499
|
+
from hosteday.hosteday import Hosteday
|
|
500
|
+
|
|
501
|
+
clean = resource.strip().strip("/")
|
|
502
|
+
if not clean:
|
|
503
|
+
raise ValueError("resource name cannot be empty.")
|
|
504
|
+
|
|
505
|
+
base_path = self._normalize_route_path(clean)
|
|
506
|
+
item_path = f"{base_path}/{{item_id}}"
|
|
507
|
+
|
|
508
|
+
async def _list_items(
|
|
509
|
+
page: int = 1,
|
|
510
|
+
per_page: int = 15,
|
|
511
|
+
search: str | None = None,
|
|
512
|
+
) -> dict[str, Any]:
|
|
513
|
+
with_auth = Hosteday.auth.current_user is not None
|
|
514
|
+
clean_search = search.strip() if search and search.strip() else None
|
|
515
|
+
safe_page = max(1, page)
|
|
516
|
+
safe_per_page = max(1, min(100, per_page))
|
|
517
|
+
try:
|
|
518
|
+
result = await Hosteday.client.index(
|
|
519
|
+
clean,
|
|
520
|
+
page=safe_page,
|
|
521
|
+
per_page=safe_per_page,
|
|
522
|
+
search=clean_search,
|
|
523
|
+
with_auth=with_auth,
|
|
524
|
+
)
|
|
525
|
+
except HostedayException:
|
|
526
|
+
result = await Hosteday.client.index(
|
|
527
|
+
clean,
|
|
528
|
+
page=safe_page,
|
|
529
|
+
per_page=safe_per_page,
|
|
530
|
+
search=clean_search,
|
|
531
|
+
with_auth=not with_auth,
|
|
532
|
+
)
|
|
533
|
+
return {
|
|
534
|
+
"items": list(result.items),
|
|
535
|
+
"current_page": max(1, result.current_page),
|
|
536
|
+
"last_page": max(1, result.last_page or 1),
|
|
537
|
+
"total": result.total,
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
async def _create_item(request: Request) -> dict[str, Any]:
|
|
541
|
+
user = Hosteday.auth.current_user
|
|
542
|
+
if require_auth_write and user is None:
|
|
543
|
+
raise HostedayWebError(401, "Authentication required.")
|
|
544
|
+
body = await _read_json_body(request)
|
|
545
|
+
if owner_field and user is not None and owner_field not in body:
|
|
546
|
+
body[owner_field] = user.id
|
|
547
|
+
created = await Hosteday.client.create(
|
|
548
|
+
clean,
|
|
549
|
+
body=body,
|
|
550
|
+
with_auth=require_auth_write or user is not None,
|
|
551
|
+
)
|
|
552
|
+
return {"ok": True, "item": created}
|
|
553
|
+
|
|
554
|
+
async def _update_item(item_id: str, request: Request) -> dict[str, Any]:
|
|
555
|
+
user = Hosteday.auth.current_user
|
|
556
|
+
if require_auth_write and user is None:
|
|
557
|
+
raise HostedayWebError(401, "Authentication required.")
|
|
558
|
+
body = await _read_json_body(request)
|
|
559
|
+
if owner_field and user is not None and owner_field not in body:
|
|
560
|
+
body[owner_field] = user.id
|
|
561
|
+
updated = await Hosteday.client.update(
|
|
562
|
+
clean,
|
|
563
|
+
id=item_id,
|
|
564
|
+
body=body,
|
|
565
|
+
with_auth=require_auth_write or user is not None,
|
|
566
|
+
)
|
|
567
|
+
return {"ok": True, "item": updated}
|
|
568
|
+
|
|
569
|
+
async def _delete_item(item_id: str) -> dict[str, Any]:
|
|
570
|
+
user = Hosteday.auth.current_user
|
|
571
|
+
if require_auth_write and user is None:
|
|
572
|
+
raise HostedayWebError(401, "Authentication required.")
|
|
573
|
+
deleted = await Hosteday.client.delete(
|
|
574
|
+
clean,
|
|
575
|
+
id=item_id,
|
|
576
|
+
with_auth=require_auth_write or user is not None,
|
|
577
|
+
)
|
|
578
|
+
return {"ok": True, **deleted}
|
|
579
|
+
|
|
580
|
+
self._app.add_api_route(base_path, _list_items, methods=["GET"])
|
|
581
|
+
self._app.add_api_route(base_path, _create_item, methods=["POST"])
|
|
582
|
+
self._app.add_api_route(item_path, _update_item, methods=["PUT", "PATCH"])
|
|
583
|
+
self._app.add_api_route(item_path, _delete_item, methods=["DELETE"])
|
|
584
|
+
|
|
585
|
+
def serve(
|
|
586
|
+
self,
|
|
587
|
+
*,
|
|
588
|
+
host: str = "127.0.0.1",
|
|
589
|
+
port: int = 8000,
|
|
590
|
+
log_level: str = "info",
|
|
591
|
+
) -> None:
|
|
592
|
+
"""Starts the embedded web server."""
|
|
593
|
+
uvicorn.run(self._app, host=host, port=port, log_level=log_level)
|
|
594
|
+
|
|
595
|
+
def run(
|
|
596
|
+
self,
|
|
597
|
+
*,
|
|
598
|
+
host: str = "127.0.0.1",
|
|
599
|
+
port: int = 8000,
|
|
600
|
+
log_level: str = "info",
|
|
601
|
+
) -> None:
|
|
602
|
+
"""Alias for :meth:`serve`."""
|
|
603
|
+
self.serve(host=host, port=port, log_level=log_level)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
class _RouteGroup:
|
|
607
|
+
"""Prefixed route registration helper returned by ``HostedayWebApp.group(prefix)``."""
|
|
608
|
+
|
|
609
|
+
def __init__(self, web: HostedayWebApp, *, prefix: str) -> None:
|
|
610
|
+
self._web = web
|
|
611
|
+
cleaned = prefix.strip().rstrip("/")
|
|
612
|
+
self._prefix = cleaned if cleaned.startswith("/") or not cleaned else f"/{cleaned}"
|
|
613
|
+
|
|
614
|
+
def _join(self, path: str) -> str:
|
|
615
|
+
sub = path.strip()
|
|
616
|
+
if not sub:
|
|
617
|
+
return self._prefix or "/"
|
|
618
|
+
if not sub.startswith("/"):
|
|
619
|
+
sub = f"/{sub}"
|
|
620
|
+
if self._prefix and (sub == self._prefix or sub.startswith(f"{self._prefix}/")):
|
|
621
|
+
return sub
|
|
622
|
+
return f"{self._prefix}{sub}"
|
|
623
|
+
|
|
624
|
+
def get(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
625
|
+
return self._web.get(self._join(path))
|
|
626
|
+
|
|
627
|
+
def post(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
628
|
+
return self._web.post(self._join(path))
|
|
629
|
+
|
|
630
|
+
def put(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
631
|
+
return self._web.put(self._join(path))
|
|
632
|
+
|
|
633
|
+
def patch(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
634
|
+
return self._web.patch(self._join(path))
|
|
635
|
+
|
|
636
|
+
def delete(self, path: str) -> Callable[[_HandlerT], _HandlerT]:
|
|
637
|
+
return self._web.delete(self._join(path))
|
hosteday_python/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|