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,130 @@
|
|
|
1
|
+
"""Auth storage protocol, canonical keys, and Memory/File/Keyring implementations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import importlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Protocol, runtime_checkable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class HostedayAuthStorageKeys:
|
|
14
|
+
"""Canonical storage keys shared across all HosteDay SDKs."""
|
|
15
|
+
|
|
16
|
+
SESSION: str = "hosteday.auth.session"
|
|
17
|
+
ACCESS_TOKEN: str = "hosteday.auth.access_token"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@runtime_checkable
|
|
21
|
+
class HostedayAuthStorage(Protocol):
|
|
22
|
+
"""Async key-value storage contract for persisting authentication sessions."""
|
|
23
|
+
|
|
24
|
+
async def read(self, key: str) -> str | None:
|
|
25
|
+
"""Reads a stored value by key, returning ``None`` when absent."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
async def write(self, key: str, value: str) -> None:
|
|
29
|
+
"""Persists ``value`` under ``key``."""
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
async def delete(self, key: str) -> None:
|
|
33
|
+
"""Removes ``key`` if present."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MemoryHostedayAuthStorage:
|
|
38
|
+
"""In-memory ``HostedayAuthStorage`` implementation (default for tests & serverless)."""
|
|
39
|
+
|
|
40
|
+
def __init__(self) -> None:
|
|
41
|
+
self._store: dict[str, str] = {}
|
|
42
|
+
|
|
43
|
+
async def read(self, key: str) -> str | None:
|
|
44
|
+
return self._store.get(key)
|
|
45
|
+
|
|
46
|
+
async def write(self, key: str, value: str) -> None:
|
|
47
|
+
self._store[key] = value
|
|
48
|
+
|
|
49
|
+
async def delete(self, key: str) -> None:
|
|
50
|
+
self._store.pop(key, None)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class JsonFileHostedayAuthStorage:
|
|
54
|
+
"""File-backed JSON storage with restrictive POSIX permissions (``0o600``)."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, path: str | Path) -> None:
|
|
57
|
+
self._path: Path = Path(path)
|
|
58
|
+
self._lock: asyncio.Lock = asyncio.Lock()
|
|
59
|
+
|
|
60
|
+
def _load_sync(self) -> dict[str, str]:
|
|
61
|
+
if not self._path.exists():
|
|
62
|
+
return {}
|
|
63
|
+
try:
|
|
64
|
+
raw = json.loads(self._path.read_text(encoding="utf-8"))
|
|
65
|
+
except (OSError, json.JSONDecodeError):
|
|
66
|
+
return {}
|
|
67
|
+
if not isinstance(raw, dict):
|
|
68
|
+
return {}
|
|
69
|
+
return {str(k): str(v) for k, v in raw.items() if v is not None}
|
|
70
|
+
|
|
71
|
+
def _save_sync(self, data: dict[str, str]) -> None:
|
|
72
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
self._path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
|
74
|
+
try:
|
|
75
|
+
os.chmod(self._path, 0o600)
|
|
76
|
+
except OSError:
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
async def read(self, key: str) -> str | None:
|
|
80
|
+
async with self._lock:
|
|
81
|
+
data = await asyncio.to_thread(self._load_sync)
|
|
82
|
+
return data.get(key)
|
|
83
|
+
|
|
84
|
+
async def write(self, key: str, value: str) -> None:
|
|
85
|
+
async with self._lock:
|
|
86
|
+
data = await asyncio.to_thread(self._load_sync)
|
|
87
|
+
data[key] = value
|
|
88
|
+
await asyncio.to_thread(self._save_sync, data)
|
|
89
|
+
|
|
90
|
+
async def delete(self, key: str) -> None:
|
|
91
|
+
async with self._lock:
|
|
92
|
+
data = await asyncio.to_thread(self._load_sync)
|
|
93
|
+
if key in data:
|
|
94
|
+
del data[key]
|
|
95
|
+
await asyncio.to_thread(self._save_sync, data)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class KeyringHostedayAuthStorage:
|
|
99
|
+
"""OS-keyring backed storage (requires ``pip install hosteday_python[encrypted]``)."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, service_name: str = "hosteday_python") -> None:
|
|
102
|
+
try:
|
|
103
|
+
keyring: Any = importlib.import_module("keyring")
|
|
104
|
+
except ImportError as exc:
|
|
105
|
+
raise ImportError(
|
|
106
|
+
"KeyringHostedayAuthStorage requires the 'encrypted' extra. "
|
|
107
|
+
"Install it with: pip install hosteday_python[encrypted]"
|
|
108
|
+
) from exc
|
|
109
|
+
self._keyring: Any = keyring
|
|
110
|
+
self._service_name = service_name
|
|
111
|
+
|
|
112
|
+
async def read(self, key: str) -> str | None:
|
|
113
|
+
result = await asyncio.to_thread(
|
|
114
|
+
self._keyring.get_password, self._service_name, key
|
|
115
|
+
)
|
|
116
|
+
return str(result) if result is not None else None
|
|
117
|
+
|
|
118
|
+
async def write(self, key: str, value: str) -> None:
|
|
119
|
+
await asyncio.to_thread(
|
|
120
|
+
self._keyring.set_password, self._service_name, key, value
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
async def delete(self, key: str) -> None:
|
|
124
|
+
def _delete() -> None:
|
|
125
|
+
try:
|
|
126
|
+
self._keyring.delete_password(self._service_name, key)
|
|
127
|
+
except Exception:
|
|
128
|
+
pass
|
|
129
|
+
|
|
130
|
+
await asyncio.to_thread(_delete)
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Represents an authenticated HosteDay user session and parses Laravel auth responses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timedelta, timezone
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from hosteday.auth.hosteday_user import HostedayUser
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class HostedaySession:
|
|
15
|
+
"""Authenticated user session with bearer access token and optional expiry."""
|
|
16
|
+
|
|
17
|
+
user: HostedayUser
|
|
18
|
+
access_token: str
|
|
19
|
+
refresh_token: str | None = None
|
|
20
|
+
token_type: str = "Bearer"
|
|
21
|
+
expires_at: datetime | None = None
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def is_expired(self) -> bool:
|
|
25
|
+
"""Returns whether the session token has expired."""
|
|
26
|
+
if self.expires_at is None:
|
|
27
|
+
return False
|
|
28
|
+
expiry = (
|
|
29
|
+
self.expires_at
|
|
30
|
+
if self.expires_at.tzinfo is not None
|
|
31
|
+
else self.expires_at.replace(tzinfo=timezone.utc)
|
|
32
|
+
)
|
|
33
|
+
return expiry < datetime.now(timezone.utc)
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def from_json(cls, payload: Mapping[str, Any]) -> HostedaySession:
|
|
37
|
+
"""Restores a session from persisted storage JSON."""
|
|
38
|
+
user_data = _as_dict(payload.get("user"))
|
|
39
|
+
if user_data is None:
|
|
40
|
+
raise ValueError("Stored Hosteday session does not include user data.")
|
|
41
|
+
|
|
42
|
+
access_token = _first_text([payload], ("access_token", "accessToken", "token"))
|
|
43
|
+
if access_token is None:
|
|
44
|
+
raise ValueError("Stored Hosteday session does not include an access token.")
|
|
45
|
+
|
|
46
|
+
return cls(
|
|
47
|
+
user=HostedayUser.from_json(user_data),
|
|
48
|
+
access_token=access_token,
|
|
49
|
+
refresh_token=_first_text([payload], ("refresh_token", "refreshToken")),
|
|
50
|
+
token_type=_first_text([payload], ("token_type", "tokenType")) or "Bearer",
|
|
51
|
+
expires_at=_parse_date(payload.get("expires_at") or payload.get("expiresAt")),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_auth_response(cls, response: Mapping[str, Any]) -> HostedaySession:
|
|
56
|
+
"""Parses common Laravel auth shapes: ``{token, user}``, ``{access_token, user}``, or ``{data: {...}}``."""
|
|
57
|
+
root = dict(response)
|
|
58
|
+
data = _as_dict(root.get("data"))
|
|
59
|
+
sources: list[Mapping[str, Any]] = [data, root] if data is not None else [root]
|
|
60
|
+
|
|
61
|
+
user_data = (
|
|
62
|
+
(_as_dict(data.get("user")) if data is not None else None)
|
|
63
|
+
or _as_dict(root.get("user"))
|
|
64
|
+
or (data if _looks_like_user(data) else None)
|
|
65
|
+
or (root if _looks_like_user(root) else None)
|
|
66
|
+
)
|
|
67
|
+
if user_data is None:
|
|
68
|
+
raise ValueError("Authentication response does not include user data.")
|
|
69
|
+
|
|
70
|
+
access_token = _first_text(sources, ("access_token", "accessToken", "token"))
|
|
71
|
+
if access_token is None:
|
|
72
|
+
raise ValueError("Authentication response does not include an access token.")
|
|
73
|
+
|
|
74
|
+
expires_at = _parse_date(
|
|
75
|
+
_first_value(sources, ("expires_at", "expiresAt"))
|
|
76
|
+
) or _expires_at_from_seconds(_first_value(sources, ("expires_in", "expiresIn")))
|
|
77
|
+
|
|
78
|
+
return cls(
|
|
79
|
+
user=HostedayUser.from_json(user_data),
|
|
80
|
+
access_token=access_token,
|
|
81
|
+
refresh_token=_first_text(sources, ("refresh_token", "refreshToken")),
|
|
82
|
+
token_type=_first_text(sources, ("token_type", "tokenType")) or "Bearer",
|
|
83
|
+
expires_at=expires_at,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def to_json(self) -> dict[str, Any]:
|
|
87
|
+
expires_iso: str | None = None
|
|
88
|
+
if self.expires_at is not None:
|
|
89
|
+
dt = (
|
|
90
|
+
self.expires_at.astimezone(timezone.utc)
|
|
91
|
+
if self.expires_at.tzinfo is not None
|
|
92
|
+
else self.expires_at.replace(tzinfo=timezone.utc)
|
|
93
|
+
)
|
|
94
|
+
expires_iso = dt.isoformat()
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
"user": self.user.to_json(),
|
|
98
|
+
"access_token": self.access_token,
|
|
99
|
+
"refresh_token": self.refresh_token,
|
|
100
|
+
"token_type": self.token_type,
|
|
101
|
+
"expires_at": expires_iso,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def copy_with(
|
|
105
|
+
self,
|
|
106
|
+
*,
|
|
107
|
+
user: HostedayUser | None = None,
|
|
108
|
+
access_token: str | None = None,
|
|
109
|
+
refresh_token: str | None = None,
|
|
110
|
+
token_type: str | None = None,
|
|
111
|
+
expires_at: datetime | None = None,
|
|
112
|
+
) -> HostedaySession:
|
|
113
|
+
return HostedaySession(
|
|
114
|
+
user=user if user is not None else self.user,
|
|
115
|
+
access_token=access_token if access_token is not None else self.access_token,
|
|
116
|
+
refresh_token=refresh_token if refresh_token is not None else self.refresh_token,
|
|
117
|
+
token_type=token_type if token_type is not None else self.token_type,
|
|
118
|
+
expires_at=expires_at if expires_at is not None else self.expires_at,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _as_dict(value: Any) -> dict[str, Any] | None:
|
|
123
|
+
if isinstance(value, Mapping):
|
|
124
|
+
return dict(value)
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _looks_like_user(value: Mapping[str, Any] | None) -> bool:
|
|
129
|
+
if value is None:
|
|
130
|
+
return False
|
|
131
|
+
return "id" in value or "user_id" in value or "uuid" in value
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _first_value(sources: Sequence[Mapping[str, Any]], keys: Sequence[str]) -> Any:
|
|
135
|
+
for source in sources:
|
|
136
|
+
for key in keys:
|
|
137
|
+
if key in source and source[key] is not None:
|
|
138
|
+
return source[key]
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _first_text(sources: Sequence[Mapping[str, Any]], keys: Sequence[str]) -> str | None:
|
|
143
|
+
value = _first_value(sources, keys)
|
|
144
|
+
if value is None:
|
|
145
|
+
return None
|
|
146
|
+
text = str(value).strip()
|
|
147
|
+
return text if text else None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _parse_date(value: Any) -> datetime | None:
|
|
151
|
+
if value is None:
|
|
152
|
+
return None
|
|
153
|
+
if isinstance(value, datetime):
|
|
154
|
+
return (
|
|
155
|
+
value.astimezone(timezone.utc)
|
|
156
|
+
if value.tzinfo is not None
|
|
157
|
+
else value.replace(tzinfo=timezone.utc)
|
|
158
|
+
)
|
|
159
|
+
text = str(value).strip()
|
|
160
|
+
if not text:
|
|
161
|
+
return None
|
|
162
|
+
if text.endswith("Z"):
|
|
163
|
+
text = f"{text[:-1]}+00:00"
|
|
164
|
+
try:
|
|
165
|
+
parsed = datetime.fromisoformat(text)
|
|
166
|
+
except ValueError:
|
|
167
|
+
return None
|
|
168
|
+
return (
|
|
169
|
+
parsed.astimezone(timezone.utc)
|
|
170
|
+
if parsed.tzinfo is not None
|
|
171
|
+
else parsed.replace(tzinfo=timezone.utc)
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _expires_at_from_seconds(value: Any) -> datetime | None:
|
|
176
|
+
if value is None or isinstance(value, bool):
|
|
177
|
+
return None
|
|
178
|
+
try:
|
|
179
|
+
seconds = int(value)
|
|
180
|
+
except (TypeError, ValueError):
|
|
181
|
+
return None
|
|
182
|
+
if seconds <= 0:
|
|
183
|
+
return None
|
|
184
|
+
return datetime.now(timezone.utc) + timedelta(seconds=seconds)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Token provider protocol and Static / Storage-backed / Combined implementations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Protocol, runtime_checkable
|
|
7
|
+
|
|
8
|
+
from hosteday.auth.hosteday_auth_storage import (
|
|
9
|
+
HostedayAuthStorage,
|
|
10
|
+
HostedayAuthStorageKeys,
|
|
11
|
+
)
|
|
12
|
+
from hosteday.auth.hosteday_session import HostedaySession
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@runtime_checkable
|
|
16
|
+
class HostedayTokenProvider(Protocol):
|
|
17
|
+
"""Async provider returning the active bearer access token, or ``None``."""
|
|
18
|
+
|
|
19
|
+
async def get_token(self) -> str | None:
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class StaticHostedayTokenProvider:
|
|
24
|
+
"""Returns a fixed bearer token supplied by the caller."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, token: str | None) -> None:
|
|
27
|
+
self._token = token
|
|
28
|
+
|
|
29
|
+
async def get_token(self) -> str | None:
|
|
30
|
+
return self._token
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class HostedayAuthTokenProvider:
|
|
34
|
+
"""Reads the active bearer token from ``HostedayAuthStorage``."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, storage: HostedayAuthStorage) -> None:
|
|
37
|
+
self._storage = storage
|
|
38
|
+
|
|
39
|
+
async def get_token(self) -> str | None:
|
|
40
|
+
direct = await self._storage.read(HostedayAuthStorageKeys.ACCESS_TOKEN)
|
|
41
|
+
if direct and direct.strip():
|
|
42
|
+
return direct.strip()
|
|
43
|
+
|
|
44
|
+
serialized = await self._storage.read(HostedayAuthStorageKeys.SESSION)
|
|
45
|
+
if not serialized or not serialized.strip():
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
decoded = json.loads(serialized)
|
|
50
|
+
if not isinstance(decoded, dict):
|
|
51
|
+
return None
|
|
52
|
+
session = HostedaySession.from_json(decoded)
|
|
53
|
+
if session.is_expired:
|
|
54
|
+
return None
|
|
55
|
+
return session.access_token.strip() or None
|
|
56
|
+
except (ValueError, json.JSONDecodeError):
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class HostedayCombinedTokenProvider:
|
|
61
|
+
"""Reads from ``primary`` (auth storage) first, falling back to an external provider."""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
*,
|
|
66
|
+
primary: HostedayTokenProvider,
|
|
67
|
+
fallback: HostedayTokenProvider | None = None,
|
|
68
|
+
) -> None:
|
|
69
|
+
self._primary = primary
|
|
70
|
+
self._fallback = fallback
|
|
71
|
+
|
|
72
|
+
async def get_token(self) -> str | None:
|
|
73
|
+
primary_token = await self._primary.get_token()
|
|
74
|
+
if primary_token and primary_token.strip():
|
|
75
|
+
return primary_token.strip()
|
|
76
|
+
|
|
77
|
+
if self._fallback is not None:
|
|
78
|
+
fallback_token = await self._fallback.get_token()
|
|
79
|
+
if fallback_token and fallback_token.strip():
|
|
80
|
+
return fallback_token.strip()
|
|
81
|
+
|
|
82
|
+
return None
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Represents the currently authenticated HosteDay user with alias normalization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from types import MappingProxyType
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
_UNSET = object()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class HostedayUser:
|
|
14
|
+
"""Immutable authenticated user model preserving raw API attributes."""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
*,
|
|
19
|
+
id: str,
|
|
20
|
+
email: str | None = None,
|
|
21
|
+
display_name: str | None = None,
|
|
22
|
+
email_verified: bool = False,
|
|
23
|
+
photo_url: str | None = None,
|
|
24
|
+
created_at: datetime | None = None,
|
|
25
|
+
updated_at: datetime | None = None,
|
|
26
|
+
data: Mapping[str, Any] | None = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
self.id: str = id
|
|
29
|
+
self.email: str | None = email
|
|
30
|
+
self.display_name: str | None = display_name
|
|
31
|
+
self.email_verified: bool = email_verified
|
|
32
|
+
self.photo_url: str | None = photo_url
|
|
33
|
+
self.created_at: datetime | None = created_at
|
|
34
|
+
self.updated_at: datetime | None = updated_at
|
|
35
|
+
self.data: Mapping[str, Any] = MappingProxyType(dict(data) if data else {})
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def name(self) -> str | None:
|
|
39
|
+
return self.display_name
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def avatar_url(self) -> str | None:
|
|
43
|
+
return self.photo_url
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def is_email_verified(self) -> bool:
|
|
47
|
+
return self.email_verified
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def has_email(self) -> bool:
|
|
51
|
+
return bool(self.email and self.email.strip())
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def has_display_name(self) -> bool:
|
|
55
|
+
return bool(self.display_name and self.display_name.strip())
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def has_photo_url(self) -> bool:
|
|
59
|
+
return bool(self.photo_url and self.photo_url.strip())
|
|
60
|
+
|
|
61
|
+
def __getitem__(self, key: str) -> Any:
|
|
62
|
+
return self.data[key]
|
|
63
|
+
|
|
64
|
+
def __contains__(self, key: object) -> bool:
|
|
65
|
+
return key in self.data
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_json(cls, payload: Mapping[str, Any]) -> HostedayUser:
|
|
69
|
+
normalized = dict(payload)
|
|
70
|
+
user_id = _first_text(normalized, ("id", "user_id", "uuid"))
|
|
71
|
+
if user_id is None:
|
|
72
|
+
raise ValueError("Hosteday user response does not include an id.")
|
|
73
|
+
|
|
74
|
+
return cls(
|
|
75
|
+
id=user_id,
|
|
76
|
+
email=_first_text(normalized, ("email",)),
|
|
77
|
+
display_name=_first_text(
|
|
78
|
+
normalized,
|
|
79
|
+
("name", "display_name", "displayName", "full_name", "fullName"),
|
|
80
|
+
),
|
|
81
|
+
email_verified=_parse_email_verified(normalized),
|
|
82
|
+
photo_url=_first_text(
|
|
83
|
+
normalized,
|
|
84
|
+
(
|
|
85
|
+
"avatar_url",
|
|
86
|
+
"avatarUrl",
|
|
87
|
+
"avatar",
|
|
88
|
+
"photo_url",
|
|
89
|
+
"photoUrl",
|
|
90
|
+
"image",
|
|
91
|
+
"image_url",
|
|
92
|
+
"imageUrl",
|
|
93
|
+
),
|
|
94
|
+
),
|
|
95
|
+
created_at=_first_datetime(normalized, ("created_at", "createdAt")),
|
|
96
|
+
updated_at=_first_datetime(normalized, ("updated_at", "updatedAt")),
|
|
97
|
+
data=normalized,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def to_json(self) -> dict[str, Any]:
|
|
101
|
+
result: dict[str, Any] = dict(self.data)
|
|
102
|
+
result["id"] = self.id
|
|
103
|
+
if self.email is not None:
|
|
104
|
+
result["email"] = self.email
|
|
105
|
+
if self.display_name is not None:
|
|
106
|
+
result["name"] = self.display_name
|
|
107
|
+
result["email_verified"] = self.email_verified
|
|
108
|
+
if self.photo_url is not None:
|
|
109
|
+
result["avatar_url"] = self.photo_url
|
|
110
|
+
if self.created_at is not None:
|
|
111
|
+
result["created_at"] = self.created_at.isoformat()
|
|
112
|
+
if self.updated_at is not None:
|
|
113
|
+
result["updated_at"] = self.updated_at.isoformat()
|
|
114
|
+
return result
|
|
115
|
+
|
|
116
|
+
def copy_with(
|
|
117
|
+
self,
|
|
118
|
+
*,
|
|
119
|
+
id: str | None = None,
|
|
120
|
+
email: Any = _UNSET,
|
|
121
|
+
display_name: Any = _UNSET,
|
|
122
|
+
email_verified: bool | None = None,
|
|
123
|
+
photo_url: Any = _UNSET,
|
|
124
|
+
created_at: Any = _UNSET,
|
|
125
|
+
updated_at: Any = _UNSET,
|
|
126
|
+
data: Mapping[str, Any] | None = None,
|
|
127
|
+
) -> HostedayUser:
|
|
128
|
+
return HostedayUser(
|
|
129
|
+
id=id if id is not None else self.id,
|
|
130
|
+
email=self.email if email is _UNSET else email,
|
|
131
|
+
display_name=self.display_name if display_name is _UNSET else display_name,
|
|
132
|
+
email_verified=(
|
|
133
|
+
email_verified if email_verified is not None else self.email_verified
|
|
134
|
+
),
|
|
135
|
+
photo_url=self.photo_url if photo_url is _UNSET else photo_url,
|
|
136
|
+
created_at=self.created_at if created_at is _UNSET else created_at,
|
|
137
|
+
updated_at=self.updated_at if updated_at is _UNSET else updated_at,
|
|
138
|
+
data=data if data is not None else self.data,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def __repr__(self) -> str:
|
|
142
|
+
return (
|
|
143
|
+
f"HostedayUser(id={self.id!r}, email={self.email!r}, "
|
|
144
|
+
f"display_name={self.display_name!r}, email_verified={self.email_verified!r}, "
|
|
145
|
+
f"photo_url={self.photo_url!r})"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def __eq__(self, other: object) -> bool:
|
|
149
|
+
if not isinstance(other, HostedayUser):
|
|
150
|
+
return NotImplemented
|
|
151
|
+
return (
|
|
152
|
+
self.id == other.id
|
|
153
|
+
and self.email == other.email
|
|
154
|
+
and self.display_name == other.display_name
|
|
155
|
+
and self.email_verified == other.email_verified
|
|
156
|
+
and self.photo_url == other.photo_url
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _first_text(values: Mapping[str, Any], keys: Sequence[str]) -> str | None:
|
|
161
|
+
for key in keys:
|
|
162
|
+
value = values.get(key)
|
|
163
|
+
if value is None:
|
|
164
|
+
continue
|
|
165
|
+
text = str(value).strip()
|
|
166
|
+
if text:
|
|
167
|
+
return text
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _first_datetime(values: Mapping[str, Any], keys: Sequence[str]) -> datetime | None:
|
|
172
|
+
for key in keys:
|
|
173
|
+
parsed = _to_datetime(values.get(key))
|
|
174
|
+
if parsed is not None:
|
|
175
|
+
return parsed
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _parse_email_verified(values: Mapping[str, Any]) -> bool:
|
|
180
|
+
direct = values.get("email_verified")
|
|
181
|
+
if direct is None:
|
|
182
|
+
direct = values.get("emailVerified")
|
|
183
|
+
if _to_bool(direct):
|
|
184
|
+
return True
|
|
185
|
+
|
|
186
|
+
verified_at = values.get("email_verified_at")
|
|
187
|
+
if verified_at is None:
|
|
188
|
+
verified_at = values.get("emailVerifiedAt")
|
|
189
|
+
if verified_at is None:
|
|
190
|
+
return False
|
|
191
|
+
if isinstance(verified_at, str):
|
|
192
|
+
return bool(verified_at.strip())
|
|
193
|
+
return True
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _to_bool(value: Any) -> bool:
|
|
197
|
+
if isinstance(value, bool):
|
|
198
|
+
return value
|
|
199
|
+
if isinstance(value, (int, float)):
|
|
200
|
+
return value != 0
|
|
201
|
+
if value is None:
|
|
202
|
+
return False
|
|
203
|
+
return str(value).strip().lower() in {"true", "1", "yes"}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _to_datetime(value: Any) -> datetime | None:
|
|
207
|
+
if value is None:
|
|
208
|
+
return None
|
|
209
|
+
if isinstance(value, datetime):
|
|
210
|
+
return value
|
|
211
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
212
|
+
return datetime.fromtimestamp(value / 1000.0, tz=timezone.utc)
|
|
213
|
+
if isinstance(value, str):
|
|
214
|
+
text = value.strip()
|
|
215
|
+
if not text:
|
|
216
|
+
return None
|
|
217
|
+
if text.endswith("Z"):
|
|
218
|
+
text = f"{text[:-1]}+00:00"
|
|
219
|
+
try:
|
|
220
|
+
return datetime.fromisoformat(text)
|
|
221
|
+
except ValueError:
|
|
222
|
+
return None
|
|
223
|
+
return None
|