From f378d0fd7096702093fb02ce99d46f1f89ffa7f5 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 14:33:21 +0100 Subject: [PATCH 1/9] feat: async client, SignalR user hub, live control and typed errors Bring the SDK up to the C# SDK's feature set and beyond. - Add AsyncOpenShockClient / AsyncOpenShockHubClient. The sync client is now generated from the async code by scripts/unasync.py (checked in CI). - Add openshock.realtime (optional 'realtime' extra, asyncio only): UserHubClient for the SignalR user hub and LiveControlClient for the live control gateway, sharing a reconnecting WebSocket transport. - Parse problem details into typed exceptions (ShockerPaused, HubOffline, TokenPermissionMissing, ...). OpenShockAuthError and OpenShockNotFound are now subclasses of OpenShockApiError. - Replace string aliases with real enums that still compare equal to their wire strings and tolerate unknown backend values. - Send a descriptive User-Agent including app_name / app_version. - Add devices.gateway() for GET /2/devices/{id}/lcg. - Fix devices.create(), devices.pair_code() and account.create_token(), which parsed responses the backend does not send. - Return typed models from shockers.list_own/list_shared/get/all_logs and UUIDs from methods that create things. Remove the PairCode model. - Add tests for every REST method, the hub and live control (against in-process fake servers), four standalone examples, and a rewritten README. - Bump version to 0.2.0b1. --- .github/workflows/ci.yml | 2 + README.md | 244 +++++++--- examples/README.md | 21 + examples/async_control/README.md | 11 + examples/async_control/main.py | 56 +++ examples/async_control/requirements.txt | 1 + examples/live_control/README.md | 11 + examples/live_control/main.py | 60 +++ examples/live_control/requirements.txt | 1 + examples/realtime_events/README.md | 11 + examples/realtime_events/main.py | 54 +++ examples/realtime_events/requirements.txt | 1 + examples/rest_quickstart/README.md | 11 + examples/rest_quickstart/main.py | 32 ++ examples/rest_quickstart/requirements.txt | 1 + openshock/__init__.py | 31 +- openshock/_async/__init__.py | 0 openshock/_async/client.py | 191 ++++++++ openshock/_async/resources/__init__.py | 0 openshock/_async/resources/account.py | 77 ++++ openshock/_async/resources/devices.py | 80 ++++ openshock/_async/resources/hub.py | 34 ++ openshock/_async/resources/meta.py | 24 + openshock/_async/resources/sessions.py | 32 ++ openshock/_async/resources/shares.py | 119 +++++ openshock/_async/resources/shockers.py | 225 ++++++++++ openshock/_async/resources/user_shares.py | 123 ++++++ openshock/_core.py | 117 +++++ openshock/_sync/__init__.py | 0 openshock/_sync/client.py | 192 ++++++++ openshock/_sync/resources/__init__.py | 0 openshock/{ => _sync}/resources/account.py | 40 +- openshock/_sync/resources/devices.py | 81 ++++ openshock/{ => _sync}/resources/hub.py | 16 +- openshock/{ => _sync}/resources/meta.py | 8 +- openshock/{ => _sync}/resources/sessions.py | 16 +- openshock/{ => _sync}/resources/shares.py | 41 +- openshock/{ => _sync}/resources/shockers.py | 116 ++--- .../{ => _sync}/resources/user_shares.py | 38 +- openshock/_version.py | 8 + openshock/client.py | 196 +-------- openshock/exceptions.py | 189 +++++++- openshock/models/__init__.py | 13 +- openshock/models/account.py | 40 +- openshock/models/common.py | 163 ++++++- openshock/models/device.py | 75 +++- openshock/models/session.py | 8 + openshock/models/share.py | 37 +- openshock/models/shocker.py | 127 +++++- openshock/realtime/__init__.py | 31 ++ openshock/realtime/_events.py | 66 +++ openshock/realtime/_signalr.py | 192 ++++++++ openshock/realtime/_transport.py | 416 ++++++++++++++++++ openshock/realtime/live_control.py | 350 +++++++++++++++ openshock/realtime/models.py | 159 +++++++ openshock/realtime/user_hub.py | 206 +++++++++ openshock/resources/__init__.py | 18 + openshock/resources/devices.py | 65 --- pyproject.toml | 17 +- scripts/unasync.py | 81 ++++ tests/fakes.py | 184 ++++++++ tests/test_client.py | 12 + tests/test_endpoints.py | 228 ++++++++++ tests/test_enums.py | 63 +++ tests/test_live_control.py | 251 +++++++++++ tests/test_rest.py | 323 ++++++++++++++ tests/test_user_hub.py | 290 ++++++++++++ 67 files changed, 5430 insertions(+), 496 deletions(-) create mode 100644 examples/README.md create mode 100644 examples/async_control/README.md create mode 100644 examples/async_control/main.py create mode 100644 examples/async_control/requirements.txt create mode 100644 examples/live_control/README.md create mode 100644 examples/live_control/main.py create mode 100644 examples/live_control/requirements.txt create mode 100644 examples/realtime_events/README.md create mode 100644 examples/realtime_events/main.py create mode 100644 examples/realtime_events/requirements.txt create mode 100644 examples/rest_quickstart/README.md create mode 100644 examples/rest_quickstart/main.py create mode 100644 examples/rest_quickstart/requirements.txt create mode 100644 openshock/_async/__init__.py create mode 100644 openshock/_async/client.py create mode 100644 openshock/_async/resources/__init__.py create mode 100644 openshock/_async/resources/account.py create mode 100644 openshock/_async/resources/devices.py create mode 100644 openshock/_async/resources/hub.py create mode 100644 openshock/_async/resources/meta.py create mode 100644 openshock/_async/resources/sessions.py create mode 100644 openshock/_async/resources/shares.py create mode 100644 openshock/_async/resources/shockers.py create mode 100644 openshock/_async/resources/user_shares.py create mode 100644 openshock/_core.py create mode 100644 openshock/_sync/__init__.py create mode 100644 openshock/_sync/client.py create mode 100644 openshock/_sync/resources/__init__.py rename openshock/{ => _sync}/resources/account.py (57%) create mode 100644 openshock/_sync/resources/devices.py rename openshock/{ => _sync}/resources/hub.py (65%) rename openshock/{ => _sync}/resources/meta.py (68%) rename openshock/{ => _sync}/resources/sessions.py (52%) rename openshock/{ => _sync}/resources/shares.py (69%) rename openshock/{ => _sync}/resources/shockers.py (59%) rename openshock/{ => _sync}/resources/user_shares.py (77%) create mode 100644 openshock/_version.py create mode 100644 openshock/realtime/__init__.py create mode 100644 openshock/realtime/_events.py create mode 100644 openshock/realtime/_signalr.py create mode 100644 openshock/realtime/_transport.py create mode 100644 openshock/realtime/live_control.py create mode 100644 openshock/realtime/models.py create mode 100644 openshock/realtime/user_hub.py delete mode 100644 openshock/resources/devices.py create mode 100644 scripts/unasync.py create mode 100644 tests/fakes.py create mode 100644 tests/test_endpoints.py create mode 100644 tests/test_enums.py create mode 100644 tests/test_live_control.py create mode 100644 tests/test_rest.py create mode 100644 tests/test_user_hub.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 112dd8a..152bd86 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,8 @@ jobs: - run: pip install ruff - run: ruff format --check . - run: ruff check . + - name: Check that the generated sync client is up to date + run: python scripts/unasync.py --check typecheck: runs-on: ubuntu-latest diff --git a/README.md b/README.md index d899aad..605062a 100644 --- a/README.md +++ b/README.md @@ -5,44 +5,59 @@ [![Python](https://img.shields.io/pypi/pyversions/openshock)](https://pypi.org/project/openshock/) [![License](https://img.shields.io/github/license/OpenShock/SDK.Python)](LICENSE) -The official OpenShock Python SDK to integrate with an OpenShock backend easily. Provides a typed REST API client with planned support for live WebSocket connections. +The official OpenShock Python SDK to integrate with an OpenShock backend easily. + +- **REST API** — typed client for the whole user API, sync and async +- **Realtime events** — SignalR user hub: hub online state, executed commands, firmware updates +- **Live control** — stream intensity to shockers in real time +- Typed models and enums, typed errors, automatic reconnects, Python 3.10+ ## Install ```bash -pip install openshock +pip install openshock # REST client only +pip install "openshock[realtime]" # + SignalR user hub and live control ``` ## Quick start ```python -from openshock import OpenShockClient +from openshock import Control, ControlType, OpenShockClient + +with OpenShockClient(api_token="your-api-token", app_name="MyApp", app_version="1.0.0") as client: + # Your hubs and their shockers + for hub in client.shockers.list_own(): + for shocker in hub.shockers: + print(hub.name, shocker.name, shocker.id) + + # Vibrate at 50% for one second + client.shockers.control( + [Control(id="shocker-uuid", type=ControlType.VIBRATE, intensity=50, duration=1000)], + custom_name="MyApp", + ) +``` -client = OpenShockClient(api_token="your-api-token") +Create API tokens at [openshock.app](https://openshock.app) under Settings > API Tokens. -# Get backend info -info = client.meta.backend_info() -print(f"OpenShock {info.version}") +Please set `app_name` / `app_version`: they end up in the `User-Agent` header and let the +OpenShock team tell integrations apart. -# List your shockers -shockers = client.shockers.list_own() +### Async -# Send a vibrate command -from openshock import Control +Every client has an async twin with the same resources and methods: -client.shockers.control([ - Control(id="shocker-uuid", type="Vibrate", intensity=50, duration=1000) -]) +```python +import asyncio +from openshock import AsyncOpenShockClient -client.close() -``` -Or use as a context manager: +async def main(): + async with AsyncOpenShockClient(api_token="your-api-token") as client: + stats = await client.meta.online_stats() + print(f"Devices online: {stats.devices_online}") -```python -with OpenShockClient(api_token="your-api-token") as client: - stats = client.meta.online_stats() - print(f"Devices online: {stats.devices_online}") + +asyncio.run(main()) ``` ## Resources @@ -57,48 +72,170 @@ with OpenShockClient(api_token="your-api-token") as client: | `client.user_shares` | User-to-user shares (V2) | `client.user_shares.get()` | | `client.sessions` | Login session management | `client.sessions.list()` | -For hub/device endpoints, use `OpenShockHubClient`: +## Errors + +Every non-2xx response raises a subclass of `OpenShockApiError`, which carries +`status_code` and, when the backend sent one, the parsed `problem` document. ```python -from openshock import OpenShockHubClient +from openshock import OpenShockApiError, ShockerNoPermission, ShockerNotFoundOrNoAccess, ShockerPaused + +try: + client.shockers.control([...]) +except ShockerPaused as e: + print("paused:", e.shocker_id) +except (ShockerNotFoundOrNoAccess, ShockerNoPermission) as e: + print("not allowed:", e.shocker_id) +except OpenShockApiError as e: + print(e.status_code, e.problem_type, e) +``` + +| Exception | Raised when | +|-----------|-------------| +| `OpenShockAuthError` | 401 / 403 | +| `TokenPermissionMissing` | the API token lacks a permission (`.required_permission`) | +| `ApiTokenPaused` | the API token is paused | +| `OpenShockNotFound` | 404 | +| `HubNotFound`, `HubOffline` | hub lookups, e.g. `client.devices.gateway()` | +| `ShockerNotFoundOrNoAccess`, `ShockerPaused`, `ShockerNoPermission` | a control request was rejected (`.shocker_id`) | +| `OpenShockRateLimited` | 429 (`.retry_after`) | +| `OpenShockConnectionError` | a realtime connection failed for good | + +## Realtime: user hub + +`UserHubClient` connects to the SignalR user hub. It needs `openshock[realtime]` and asyncio. -hub = OpenShockHubClient(hub_token="device-token") -lcg = hub.hub.assign_lcg() -print(f"Connect to {lcg.host}:{lcg.port}") +```python +import asyncio +from openshock.realtime import UserHubClient + + +async def main(): + async with UserHubClient("your-api-token", app_name="MyApp", app_version="1.0.0") as hub: + + @hub.on_hub_status + def on_status(states): + for state in states: + print(state.device, "online" if state.online else "offline", state.firmware_version) + + @hub.on_log + async def on_log(sender, logs): + for log in logs: + print(f"{sender.custom_name or sender.name}: {log.type} {log.intensity}% on {log.shocker.name}") + + await hub.wait_closed() + + +asyncio.run(main()) ``` -## Authentication +| Event | Arguments | +|-------|-----------| +| `on_welcome` | `connection_id` | +| `on_hub_status` | `list[HubOnlineState]` | +| `on_log` | `sender, list[ControlLog]` | +| `on_hub_update` | `hub_id, HubUpdateType` | +| `on_ota_install_started` | `hub_id, update_id, version` | +| `on_ota_install_progress` | `hub_id, update_id, OtaUpdateProgressTask, progress` | +| `on_ota_install_failed` | `hub_id, update_id, fatal, message` | +| `on_ota_rollback`, `on_ota_install_succeeded` | `hub_id, update_id` | +| `on_connected`, `on_reconnected` | — | +| `on_reconnecting`, `on_closed` | `error` | -Two client types for two auth schemes: +Handlers can be plain functions or coroutines. Subscribe with the decorator form shown +above or with `hub.on_log.subscribe(handler)`, which returns an unsubscribe function. +`hub.on("MethodName", handler)` subscribes to hub methods the SDK has no typed event for. -- **`OpenShockClient(api_token=...)`** — User API token (`OpenShockToken` header) -- **`OpenShockHubClient(hub_token=...)`** — Device token (`DeviceToken` header) +Commands can be sent over the same connection: `await hub.control([...], custom_name="MyApp")`. +`set_captive_portal`, `emergency_stop`, `ota_install` and `reboot` exist too, but the +backend only honours them for user-session connections, not API tokens. -Create API tokens at [openshock.app](https://openshock.app) under Settings > API Tokens. +The connection reconnects on its own (immediately, then after 2s, 10s, and every 30s). +Pass `retry_policy=` to change that. If the token is rejected or revoked the session ends: +`on_closed` receives the error and `wait_closed()` raises it. + +> **Naming:** `UserHubClient` is the realtime connection for a *user*. `OpenShockHubClient` +> (below) is the REST client a hub *device* uses. The C# SDK calls the former `OpenShockHubClient`. -## Typed models +## Realtime: live control -All responses are parsed into typed dataclasses: +Live control is a stream: you keep telling the hub what a shocker should be doing right now, +and it stops shortly after you stop. `LiveControlClient` handles the gateway lookup, the tick +rate the gateway asks for, pings and reconnects. ```python -from openshock import ( - BackendInfo, Stats, User, Token, Device, Shocker, - ShockerPermissions, ShockerLimits, ShockerLog, Control, - Session, PublicShare, UserShares, ShareInvite, PauseReason, -) +import asyncio +from openshock import ControlType +from openshock.realtime import LiveControlClient + + +async def main(): + async with LiveControlClient("hub-uuid", api_token="your-api-token") as live: + await live.wait_connected() + + # Ramp vibration from 0 to 50 over five seconds + for intensity in range(0, 51): + live.intake_frame("shocker-uuid", ControlType.VIBRATE, intensity) + await asyncio.sleep(0.1) + + +asyncio.run(main()) ``` -## Self-hosting +- `intake_frame()` never blocks. The latest value per shocker is sent on every tick and + dropped after a short hold window (2.5 ticks, or `hold_for=` seconds), so call it again to keep going. +- `release()` stops sending immediately; `send_frame()` sends a single frame right away. +- `live.tps`, `live.latency_ms`, `live.hub_connected` expose the current state. +- Events: `on_hub_connected`, `on_hub_not_connected`, `on_tps`, `on_latency`, `on_rejected` + (e.g. `SHOCKER_PAUSED`, `SHOCKER_MISSING_LIVE_PERMISSION`), plus the connection events above. +- While the hub is offline the client keeps retrying in the background (0s, 5s, 10s, then every 30s). +- Pass `client=` to reuse an `AsyncOpenShockClient`, or `gateway=` to skip the lookup. + +The shockers need the *live* permission for your account. -To connect to a self-hosted instance: +## Hub (device) endpoints + +For the endpoints a hub itself calls, use `OpenShockHubClient` with a device token: ```python -client = OpenShockClient( - api_token="your-token", - base_url="https://api.your-instance.com", -) +from openshock import OpenShockHubClient + +with OpenShockHubClient(hub_token="device-token") as hub: + lcg = hub.hub.assign_lcg() + print(f"Connect to {lcg.host}:{lcg.port}") ``` +## Models and enums + +Responses are parsed into typed dataclasses (`Shocker`, `Device`, `Token`, `ShockerLog`, …). +Enums such as `ControlType`, `ShockerModelType` and `PermissionType` are string enums: + +```python +ControlType.SHOCK == "Shock" # True, plain strings keep working everywhere +ControlType("vibrate") # case-insensitive lookup +PermissionType("some.new.permission").is_known # False, unknown values never raise +``` + +## Self-hosting + +```python +client = OpenShockClient(api_token="your-token", base_url="https://api.your-instance.com") +hub = UserHubClient("your-token", base_url="https://api.your-instance.com") +``` + +## Examples + +Standalone example programs live in [`examples/`](examples), one folder each: + +| Folder | Shows | +|--------|-------| +| [`rest_quickstart`](examples/rest_quickstart) | Sync REST client: list hubs, shockers and shares | +| [`async_control`](examples/async_control) | Async REST client: send a command, handle typed errors | +| [`realtime_events`](examples/realtime_events) | SignalR user hub: print live events for your account | +| [`live_control`](examples/live_control) | Live control: stream intensity to a shocker | + +They read `OPENSHOCK_API_TOKEN` (and `OPENSHOCK_API_URL` for self-hosted instances) from the environment. + ## Development ```bash @@ -106,19 +243,16 @@ git clone https://github.com/OpenShock/SDK.Python.git cd SDK.Python pip install -e ".[dev]" -# Format -ruff format . - -# Lint -ruff check . - -# Type check -mypy openshock/ - -# Test -pytest +ruff format . # format +ruff check . # lint +mypy openshock/ # type check +pytest # test ``` +The sync client is generated from the async one. Edit code under `openshock/_async/`, +then run `python scripts/unasync.py` to regenerate `openshock/_sync/`. CI fails if the +two are out of step. + ## License [MIT](LICENSE) diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..bf28aec --- /dev/null +++ b/examples/README.md @@ -0,0 +1,21 @@ +# Examples + +Each folder is a small standalone program with its own `requirements.txt` and README. + +| Folder | Shows | Needs | +|--------|-------|-------| +| [`rest_quickstart`](rest_quickstart) | Sync REST client: list hubs, shockers and shares | `openshock` | +| [`async_control`](async_control) | Async REST client: send a command, handle typed errors | `openshock` | +| [`realtime_events`](realtime_events) | SignalR user hub: print live events for your account | `openshock[realtime]` | +| [`live_control`](live_control) | Live control: stream intensity to a shocker | `openshock[realtime]` | + +All of them read an API token from `OPENSHOCK_API_TOKEN` (create one at +[openshock.app](https://openshock.app) under Settings > API Tokens) and, optionally, the API +URL of a self-hosted instance from `OPENSHOCK_API_URL`. + +```bash +cd examples/rest_quickstart +pip install -r requirements.txt +export OPENSHOCK_API_TOKEN=your-api-token +python main.py +``` diff --git a/examples/async_control/README.md b/examples/async_control/README.md new file mode 100644 index 0000000..4171a1d --- /dev/null +++ b/examples/async_control/README.md @@ -0,0 +1,11 @@ +# Async control + +Async client. Sends a single command to a shocker and handles each way the backend can refuse it (paused, no access, no permission). + +```bash +pip install -r requirements.txt +export OPENSHOCK_API_TOKEN=your-api-token +python main.py [vibrate|sound|shock] [intensity] [duration-ms] +``` + +Set `OPENSHOCK_API_URL` as well to use a self-hosted instance. diff --git a/examples/async_control/main.py b/examples/async_control/main.py new file mode 100644 index 0000000..5d6a34e --- /dev/null +++ b/examples/async_control/main.py @@ -0,0 +1,56 @@ +""" +Send one command to a shocker and handle the ways the backend can refuse it. + + python main.py [vibrate|sound|shock] [intensity] [duration-ms] +""" + +import asyncio +import os +import sys + +from openshock import ( + AsyncOpenShockClient, + Control, + ControlType, + OpenShockApiError, + ShockerNoPermission, + ShockerNotFoundOrNoAccess, + ShockerPaused, +) + +APP_NAME = "OpenShock.SDK.Python.Examples" +APP_VERSION = "1.0.0" +BASE_URL = os.environ.get("OPENSHOCK_API_URL", "https://api.openshock.app") +API_TOKEN = os.environ.get("OPENSHOCK_API_TOKEN") or sys.exit( + "Set OPENSHOCK_API_TOKEN to an API token from https://openshock.app (Settings > API Tokens)." +) + + +async def main() -> None: + if len(sys.argv) < 2: + sys.exit(__doc__) + shocker_id = sys.argv[1] + control_type = ControlType(sys.argv[2] if len(sys.argv) > 2 else "vibrate") + intensity = int(sys.argv[3]) if len(sys.argv) > 3 else 25 + duration = int(sys.argv[4]) if len(sys.argv) > 4 else 1000 + + async with AsyncOpenShockClient( + api_token=API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION + ) as client: + try: + await client.shockers.control( + [Control(id=shocker_id, type=control_type, intensity=intensity, duration=duration)], + custom_name="SDK example", + ) + except ShockerPaused: + sys.exit("That shocker is paused.") + except ShockerNotFoundOrNoAccess: + sys.exit("That shocker does not exist or is not shared with you.") + except ShockerNoPermission: + sys.exit(f"You are not allowed to use {control_type} on that shocker.") + except OpenShockApiError as exc: + sys.exit(f"Request failed: {exc}") + print(f"Sent {control_type} at {intensity}% for {duration} ms") + + +asyncio.run(main()) diff --git a/examples/async_control/requirements.txt b/examples/async_control/requirements.txt new file mode 100644 index 0000000..3512a09 --- /dev/null +++ b/examples/async_control/requirements.txt @@ -0,0 +1 @@ +openshock diff --git a/examples/live_control/README.md b/examples/live_control/README.md new file mode 100644 index 0000000..d13f329 --- /dev/null +++ b/examples/live_control/README.md @@ -0,0 +1,11 @@ +# Live control + +Live control stream. Looks up the shocker's hub, connects to its gateway and ramps vibration up and down for a few seconds. The shocker needs the *live* permission and its hub must be online. + +```bash +pip install -r requirements.txt +export OPENSHOCK_API_TOKEN=your-api-token +python main.py +``` + +Set `OPENSHOCK_API_URL` as well to use a self-hosted instance. diff --git a/examples/live_control/main.py b/examples/live_control/main.py new file mode 100644 index 0000000..a4a2a44 --- /dev/null +++ b/examples/live_control/main.py @@ -0,0 +1,60 @@ +""" +Ramp a shocker's vibration up and down through live control. + + python main.py + +The shocker needs the "live" permission for your account, and its hub must be online. +""" + +import asyncio +import math +import os +import sys + +from openshock import AsyncOpenShockClient, ControlType +from openshock.realtime import LiveControlClient, LiveResponseType + +APP_NAME = "OpenShock.SDK.Python.Examples" +APP_VERSION = "1.0.0" +BASE_URL = os.environ.get("OPENSHOCK_API_URL", "https://api.openshock.app") +API_TOKEN = os.environ.get("OPENSHOCK_API_TOKEN") or sys.exit( + "Set OPENSHOCK_API_TOKEN to an API token from https://openshock.app (Settings > API Tokens)." +) + +PEAK = 30 # percent +SECONDS = 6 + + +async def main() -> None: + if len(sys.argv) < 2: + sys.exit(__doc__) + shocker_id = sys.argv[1] + + async with AsyncOpenShockClient( + api_token=API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION + ) as client: + # Live control connects per hub, so find the hub this shocker belongs to. + shocker = await client.shockers.get(shocker_id) + assert shocker.device is not None + + live = LiveControlClient(shocker.device, client=client, app_name=APP_NAME, app_version=APP_VERSION) + live.on_latency(lambda own, hub: print(f"latency {own} ms")) + live.on_hub_not_connected(lambda: print("The hub went offline")) + + @live.on_rejected + def on_rejected(reason: LiveResponseType, data: object) -> None: + print(f"Frame rejected: {reason.name}") + + async with live: + print("Waiting for the hub's gateway...") + await live.wait_connected() + print(f"Connected to {live.gateway}, sending at {live.tps} ticks per second") + + steps = SECONDS * 20 + for step in range(steps): + intensity = round(PEAK * math.sin(math.pi * step / steps)) + live.intake_frame(shocker_id, ControlType.VIBRATE, intensity) + await asyncio.sleep(0.05) + + +asyncio.run(main()) diff --git a/examples/live_control/requirements.txt b/examples/live_control/requirements.txt new file mode 100644 index 0000000..8fa2d32 --- /dev/null +++ b/examples/live_control/requirements.txt @@ -0,0 +1 @@ +openshock[realtime] diff --git a/examples/realtime_events/README.md b/examples/realtime_events/README.md new file mode 100644 index 0000000..f2853e8 --- /dev/null +++ b/examples/realtime_events/README.md @@ -0,0 +1,11 @@ +# Realtime events + +SignalR user hub. Prints hub online/offline changes, hub updates and every command executed on your shockers, until you press Ctrl+C. Reconnects on its own. + +```bash +pip install -r requirements.txt +export OPENSHOCK_API_TOKEN=your-api-token +python main.py +``` + +Set `OPENSHOCK_API_URL` as well to use a self-hosted instance. diff --git a/examples/realtime_events/main.py b/examples/realtime_events/main.py new file mode 100644 index 0000000..48633e3 --- /dev/null +++ b/examples/realtime_events/main.py @@ -0,0 +1,54 @@ +"""Print realtime events for your account until interrupted (Ctrl+C).""" + +import asyncio +import contextlib +import logging +import os +import sys +from uuid import UUID + +from openshock.realtime import ControlLog, HubControlLogSender, HubOnlineState, HubUpdateType, UserHubClient + +APP_NAME = "OpenShock.SDK.Python.Examples" +APP_VERSION = "1.0.0" +BASE_URL = os.environ.get("OPENSHOCK_API_URL", "https://api.openshock.app") +API_TOKEN = os.environ.get("OPENSHOCK_API_TOKEN") or sys.exit( + "Set OPENSHOCK_API_TOKEN to an API token from https://openshock.app (Settings > API Tokens)." +) + + +async def main() -> None: + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s: %(message)s") + hub = UserHubClient(API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION) + + @hub.on_welcome + def on_welcome(connection_id: str) -> None: + print(f"Connected, connection id {connection_id}") + + @hub.on_hub_status + def on_hub_status(states: list[HubOnlineState]) -> None: + for state in states: + status = f"online (firmware {state.firmware_version})" if state.online else "offline" + print(f"Hub {state.device} is {status}") + + @hub.on_hub_update + def on_hub_update(hub_id: UUID, update: HubUpdateType) -> None: + print(f"Hub {hub_id}: {update}") + + @hub.on_log + async def on_log(sender: HubControlLogSender, logs: list[ControlLog]) -> None: + who = sender.custom_name or sender.name + mine = " (this connection)" if sender.connection_id == hub.connection_id else "" + for log in logs: + live = " [live]" if log.live_control else "" + print(f"{who}{mine}: {log.type} {log.intensity}% for {log.duration} ms on {log.shocker.name}{live}") + + hub.on_reconnecting(lambda error: print(f"Connection lost ({error}), reconnecting...")) + hub.on_reconnected(lambda: print("Reconnected")) + + async with hub: + await hub.wait_closed() + + +with contextlib.suppress(KeyboardInterrupt): + asyncio.run(main()) diff --git a/examples/realtime_events/requirements.txt b/examples/realtime_events/requirements.txt new file mode 100644 index 0000000..8fa2d32 --- /dev/null +++ b/examples/realtime_events/requirements.txt @@ -0,0 +1 @@ +openshock[realtime] diff --git a/examples/rest_quickstart/README.md b/examples/rest_quickstart/README.md new file mode 100644 index 0000000..16d8d42 --- /dev/null +++ b/examples/rest_quickstart/README.md @@ -0,0 +1,11 @@ +# REST quickstart + +Synchronous client. Prints the backend version, who you are, your hubs and shockers, and the shockers shared with you. + +```bash +pip install -r requirements.txt +export OPENSHOCK_API_TOKEN=your-api-token +python main.py +``` + +Set `OPENSHOCK_API_URL` as well to use a self-hosted instance. diff --git a/examples/rest_quickstart/main.py b/examples/rest_quickstart/main.py new file mode 100644 index 0000000..49649ba --- /dev/null +++ b/examples/rest_quickstart/main.py @@ -0,0 +1,32 @@ +"""List your hubs and shockers, and the shockers other people shared with you.""" + +import os +import sys + +from openshock import OpenShockClient + +APP_NAME = "OpenShock.SDK.Python.Examples" +APP_VERSION = "1.0.0" +BASE_URL = os.environ.get("OPENSHOCK_API_URL", "https://api.openshock.app") +API_TOKEN = os.environ.get("OPENSHOCK_API_TOKEN") or sys.exit( + "Set OPENSHOCK_API_TOKEN to an API token from https://openshock.app (Settings > API Tokens)." +) + +with OpenShockClient(api_token=API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION) as client: + info = client.meta.backend_info() + me = client.account.user_self() + print(f"OpenShock {info.version}, signed in as {me.name}\n") + + print("Own:") + for hub in client.shockers.list_own(): + print(f" {hub.name} ({hub.id})") + for shocker in hub.shockers: + paused = " [paused]" if shocker.is_paused else "" + print(f" {shocker.name} {shocker.model} ({shocker.id}){paused}") + + print("\nShared with me:") + for owner in client.shockers.list_shared(): + for shared_hub in owner.devices: + for shared in shared_hub.shockers: + limit = shared.limits.intensity if shared.limits.intensity is not None else 100 + print(f" {owner.name} / {shared_hub.name} / {shared.name} max {limit}% ({shared.id})") diff --git a/examples/rest_quickstart/requirements.txt b/examples/rest_quickstart/requirements.txt new file mode 100644 index 0000000..3512a09 --- /dev/null +++ b/examples/rest_quickstart/requirements.txt @@ -0,0 +1 @@ +openshock diff --git a/openshock/__init__.py b/openshock/__init__.py index a803286..d8a5922 100644 --- a/openshock/__init__.py +++ b/openshock/__init__.py @@ -1,24 +1,48 @@ +"""Official OpenShock Python SDK. See https://github.com/OpenShock/SDK.Python""" + +from ._version import __version__ as __version__ +from .auth import ApiTokenAuth as ApiTokenAuth +from .auth import Auth as Auth +from .auth import HubTokenAuth as HubTokenAuth +from .client import AsyncOpenShockClient as AsyncOpenShockClient +from .client import AsyncOpenShockHubClient as AsyncOpenShockHubClient from .client import OpenShockClient as OpenShockClient from .client import OpenShockHubClient as OpenShockHubClient +from .exceptions import ApiTokenPaused as ApiTokenPaused +from .exceptions import HubInvocationError as HubInvocationError +from .exceptions import HubNotFound as HubNotFound +from .exceptions import HubOffline as HubOffline from .exceptions import OpenShockApiError as OpenShockApiError from .exceptions import OpenShockAuthError as OpenShockAuthError +from .exceptions import OpenShockConnectionError as OpenShockConnectionError from .exceptions import OpenShockError as OpenShockError from .exceptions import OpenShockNotFound as OpenShockNotFound +from .exceptions import OpenShockRateLimited as OpenShockRateLimited +from .exceptions import ProblemDetails as ProblemDetails +from .exceptions import ShockerControlError as ShockerControlError +from .exceptions import ShockerNoPermission as ShockerNoPermission +from .exceptions import ShockerNotFoundOrNoAccess as ShockerNotFoundOrNoAccess +from .exceptions import ShockerPaused as ShockerPaused +from .exceptions import TokenPermissionMissing as TokenPermissionMissing from .models import BackendInfo as BackendInfo from .models import BasicUserInfo as BasicUserInfo +from .models import BulkPauseResult as BulkPauseResult from .models import Control as Control from .models import ControlLogSender as ControlLogSender from .models import ControlType as ControlType +from .models import CreatedToken as CreatedToken from .models import Device as Device from .models import DeviceSelf as DeviceSelf +from .models import DeviceWithShockers as DeviceWithShockers from .models import DeviceWithToken as DeviceWithToken +from .models import HubGateway as HubGateway from .models import LcgInfo as LcgInfo from .models import LcgNode as LcgNode from .models import LcgNodeV2 as LcgNodeV2 from .models import MinimalShocker as MinimalShocker from .models import OtaUpdate as OtaUpdate +from .models import OtaUpdateStatus as OtaUpdateStatus from .models import OwnPublicShare as OwnPublicShare -from .models import PairCode as PairCode from .models import PauseReason as PauseReason from .models import PermissionType as PermissionType from .models import PublicShare as PublicShare @@ -27,13 +51,17 @@ from .models import RoleType as RoleType from .models import Session as Session from .models import ShareCode as ShareCode +from .models import SharedDevice as SharedDevice +from .models import SharedShocker as SharedShocker from .models import ShareInfo as ShareInfo from .models import ShareInvite as ShareInvite from .models import ShareInviteShocker as ShareInviteShocker from .models import Shocker as Shocker from .models import ShockerLimits as ShockerLimits from .models import ShockerLog as ShockerLog +from .models import ShockerLogWithHub as ShockerLogWithHub from .models import ShockerModelType as ShockerModelType +from .models import ShockerOwner as ShockerOwner from .models import ShockerPermissions as ShockerPermissions from .models import Stats as Stats from .models import Token as Token @@ -41,5 +69,6 @@ from .models import UserShare as UserShare from .models import UserShareInfo as UserShareInfo from .models import UserShares as UserShares +from .models import WireEnum as WireEnum from .models import parse_dt as parse_dt from .models import parse_uuid as parse_uuid diff --git a/openshock/_async/__init__.py b/openshock/_async/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/openshock/_async/client.py b/openshock/_async/client.py new file mode 100644 index 0000000..3f5d5b5 --- /dev/null +++ b/openshock/_async/client.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from types import TracebackType +from typing import Any, TypeVar + +import httpx + +from .._core import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, handle_response, http_user_agent +from ..auth import ApiTokenAuth, Auth, HubTokenAuth +from .resources.account import AsyncAccountResource +from .resources.devices import AsyncDevicesResource +from .resources.hub import AsyncHubResource +from .resources.meta import AsyncMetaResource +from .resources.sessions import AsyncSessionsResource +from .resources.shares import AsyncSharesResource +from .resources.shockers import AsyncShockersResource +from .resources.user_shares import AsyncUserSharesResource + +T = TypeVar("T") +_SelfT = TypeVar("_SelfT", bound="_AsyncBaseClient") + + +class _AsyncBaseClient: + """ + Internal base client that handles HTTP, auth and error mapping. + Concrete clients subclass this and attach resources. + """ + + def __init__( + self, + *, + auth: Auth, + base_url: str = DEFAULT_BASE_URL, + timeout: float = DEFAULT_TIMEOUT, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self._auth = auth + self._base_url = base_url.rstrip("/") + self._app_name = app_name + self._app_version = app_version + self._client = httpx.AsyncClient( + base_url=self._base_url, + timeout=timeout, + transport=transport, + headers={**(headers or {}), "User-Agent": http_user_agent(app_name, app_version)}, + ) + + # --- introspection ----------------------------------------------------- + + @property + def auth(self) -> Auth: + return self._auth + + @property + def base_url(self) -> str: + return self._base_url + + # --- lifecycle --------------------------------------------------------- + + async def aclose(self) -> None: + await self._client.aclose() + + async def __aenter__(self: _SelfT) -> _SelfT: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + await self.aclose() + + # --- internal helpers -------------------------------------------------- + + async def _request( + self, + method: str, + path: str, + *, + params: dict[str, Any] | None = None, + json: Any = None, + transform: Callable[[Any], T] | None = None, + ) -> T | Any: + """ + Perform an HTTP request and return the parsed payload for 2xx responses + (JSON-decoded when possible, otherwise text, ``None`` for an empty body). + + On non-2xx an :class:`~openshock.exceptions.OpenShockApiError` subclass is raised; + see :func:`openshock.exceptions.error_from_response` for the mapping. + """ + resp = await self._client.request( + method, + path, + params=params, + json=json, + headers=dict(self._auth.headers()), + ) + return handle_response(resp, transform) + + +class AsyncOpenShockClient(_AsyncBaseClient): + """ + High-level client for the *user* OpenShock REST API (ApiToken-based). + + ``app_name`` / ``app_version`` identify your program in the User-Agent header. + """ + + def __init__( + self, + *, + auth: ApiTokenAuth | None = None, + api_token: str | None = None, + base_url: str = DEFAULT_BASE_URL, + timeout: float = DEFAULT_TIMEOUT, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + if auth is not None and api_token is not None: + raise ValueError("Provide either `auth` or `api_token`, not both.") + + if auth is None: + if api_token is None: + raise ValueError("You must provide either `auth` or `api_token`.") + auth = ApiTokenAuth(api_token) + + super().__init__( + auth=auth, + base_url=base_url, + timeout=timeout, + app_name=app_name, + app_version=app_version, + headers=headers, + transport=transport, + ) + + self.meta = AsyncMetaResource(self) + self.account = AsyncAccountResource(self) + self.devices = AsyncDevicesResource(self) + self.shockers = AsyncShockersResource(self) + self.shares = AsyncSharesResource(self) + self.sessions = AsyncSessionsResource(self) + self.user_shares = AsyncUserSharesResource(self) + + +class AsyncOpenShockHubClient(_AsyncBaseClient): + """ + High-level client for the *hub/device* OpenShock REST API (DeviceToken-based). + + This is what a hub (the ESP32 device) itself talks to. To receive realtime user + events use :class:`openshock.realtime.UserHubClient` instead. + """ + + def __init__( + self, + *, + auth: HubTokenAuth | None = None, + hub_token: str | None = None, + base_url: str = DEFAULT_BASE_URL, + timeout: float = DEFAULT_TIMEOUT, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + if auth is not None and hub_token is not None: + raise ValueError("Provide either `auth` or `hub_token`, not both.") + + if auth is None: + if hub_token is None: + raise ValueError("You must provide either `auth` or `hub_token`.") + auth = HubTokenAuth(hub_token) + + super().__init__( + auth=auth, + base_url=base_url, + timeout=timeout, + app_name=app_name, + app_version=app_version, + headers=headers, + transport=transport, + ) + + self.hub = AsyncHubResource(self) + self.meta = AsyncMetaResource(self) diff --git a/openshock/_async/resources/__init__.py b/openshock/_async/resources/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/openshock/_async/resources/account.py b/openshock/_async/resources/account.py new file mode 100644 index 0000000..2665d48 --- /dev/null +++ b/openshock/_async/resources/account.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +from collections.abc import Sequence +from datetime import datetime +from typing import TYPE_CHECKING, Any +from uuid import UUID + +from ..._core import unwrap, unwrap_list +from ...models import CreatedToken, PermissionType, Token, User + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +def _permissions(permissions: Sequence[PermissionType | str]) -> list[str]: + return [PermissionType(p).value for p in permissions] + + +class AsyncAccountResource: + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + async def user_self(self) -> User: + """GET /1/users/self — Get the authenticated user's info.""" + resp = await self._client._request("GET", "/1/users/self") + return User.from_dict(unwrap(resp)) + + async def token_self(self) -> Token: + """GET /1/tokens/self — Get info about the API token being used.""" + resp = await self._client._request("GET", "/1/tokens/self") + return Token.from_dict(unwrap(resp)) + + async def list_tokens(self) -> list[Token]: + """GET /1/tokens — List all API tokens for the authenticated user.""" + resp = await self._client._request("GET", "/1/tokens") + return [Token.from_dict(t) for t in unwrap_list(resp)] + + async def create_token( + self, + name: str, + permissions: Sequence[PermissionType | str], + valid_until: datetime | str | None = None, + ) -> CreatedToken: + """ + POST /1/tokens — Create a new API token. + + The returned object carries the token secret; it cannot be retrieved again later. + """ + body: dict[str, Any] = {"name": name, "permissions": _permissions(permissions)} + if valid_until is not None: + body["validUntil"] = valid_until.isoformat() if isinstance(valid_until, datetime) else valid_until + resp = await self._client._request("POST", "/1/tokens", json=body) + return CreatedToken.from_dict(unwrap(resp)) + + async def get_token(self, token_id: str | UUID) -> Token: + """GET /1/tokens/{tokenId} — Get a token by ID.""" + resp = await self._client._request("GET", f"/1/tokens/{token_id}") + return Token.from_dict(unwrap(resp)) + + async def edit_token( + self, + token_id: str | UUID, + *, + name: str | None = None, + permissions: Sequence[PermissionType | str] | None = None, + ) -> None: + """PATCH /1/tokens/{tokenId} — Edit a token's name or permissions.""" + body: dict[str, Any] = {} + if name is not None: + body["name"] = name + if permissions is not None: + body["permissions"] = _permissions(permissions) + await self._client._request("PATCH", f"/1/tokens/{token_id}", json=body) + + async def revoke_token(self, token_id: str | UUID) -> None: + """DELETE /1/tokens/{tokenId} — Permanently revoke a token.""" + await self._client._request("DELETE", f"/1/tokens/{token_id}") diff --git a/openshock/_async/resources/devices.py b/openshock/_async/resources/devices.py new file mode 100644 index 0000000..9cfd4c1 --- /dev/null +++ b/openshock/_async/resources/devices.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import builtins +from typing import TYPE_CHECKING +from uuid import UUID + +from ..._core import unwrap, unwrap_list +from ...models import Device, DeviceWithToken, HubGateway, LcgInfo, OtaUpdate, Shocker + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +class AsyncDevicesResource: + """Hub (device) management.""" + + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + async def list(self) -> builtins.list[Device]: + """GET /1/devices — List all hubs owned by the authenticated user.""" + resp = await self._client._request("GET", "/1/devices") + return [Device.from_dict(d) for d in unwrap_list(resp)] + + async def create(self, name: str) -> UUID: + """POST /2/devices — Create a new hub. Returns the new hub's ID.""" + resp = await self._client._request("POST", "/2/devices", json={"name": name}) + return UUID(str(unwrap(resp)).strip().strip('"')) + + async def get(self, device_id: str | UUID) -> DeviceWithToken: + """ + GET /1/devices/{deviceId} — Get a hub. + + The hub's device token is included when you are allowed to see it. + """ + resp = await self._client._request("GET", f"/1/devices/{device_id}") + return DeviceWithToken.from_dict(unwrap(resp)) + + async def edit(self, device_id: str | UUID, *, name: str) -> None: + """PATCH /1/devices/{deviceId} — Rename a hub.""" + await self._client._request("PATCH", f"/1/devices/{device_id}", json={"name": name}) + + async def delete(self, device_id: str | UUID) -> None: + """DELETE /1/devices/{deviceId} — Delete a hub.""" + await self._client._request("DELETE", f"/1/devices/{device_id}") + + async def regenerate_token(self, device_id: str | UUID) -> str: + """PUT /1/devices/{deviceId} — Regenerate the hub's device token. Returns the new token.""" + resp = await self._client._request("PUT", f"/1/devices/{device_id}") + return str(unwrap(resp)) + + async def shockers(self, device_id: str | UUID) -> builtins.list[Shocker]: + """GET /1/devices/{deviceId}/shockers — List the shockers of a hub.""" + resp = await self._client._request("GET", f"/1/devices/{device_id}/shockers") + return [Shocker.from_dict(s) for s in unwrap_list(resp)] + + async def pair_code(self, device_id: str | UUID) -> str: + """GET /1/devices/{deviceId}/pair — Generate a pair code for a hub (valid 15 minutes).""" + resp = await self._client._request("GET", f"/1/devices/{device_id}/pair") + return str(unwrap(resp)) + + async def gateway(self, device_id: str | UUID) -> HubGateway: + """ + GET /2/devices/{deviceId}/lcg — Get the live control gateway a hub is connected to. + + Raises :class:`~openshock.exceptions.HubOffline` when the hub is not online and + :class:`~openshock.exceptions.HubNotFound` when it does not exist or is not yours. + """ + resp = await self._client._request("GET", f"/2/devices/{device_id}/lcg") + return HubGateway.from_dict(unwrap(resp)) + + async def lcg_info(self, device_id: str | UUID) -> LcgInfo: + """GET /1/devices/{deviceId}/lcg — Legacy gateway lookup. Prefer :meth:`gateway`.""" + resp = await self._client._request("GET", f"/1/devices/{device_id}/lcg") + return LcgInfo.from_dict(unwrap(resp)) + + async def ota_history(self, device_id: str | UUID) -> builtins.list[OtaUpdate]: + """GET /1/devices/{deviceId}/ota — Get the firmware update history of a hub.""" + resp = await self._client._request("GET", f"/1/devices/{device_id}/ota") + return [OtaUpdate.from_dict(o) for o in unwrap_list(resp)] diff --git a/openshock/_async/resources/hub.py b/openshock/_async/resources/hub.py new file mode 100644 index 0000000..aa0d1d5 --- /dev/null +++ b/openshock/_async/resources/hub.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ..._core import unwrap +from ...models import DeviceSelf, LcgNodeV2 + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +class AsyncHubResource: + """Endpoints called by ESP32 hubs using DeviceToken auth.""" + + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + async def self_info(self) -> DeviceSelf: + """GET /1/device/self — Get info about the authenticated hub.""" + resp = await self._client._request("GET", "/1/device/self") + return DeviceSelf.from_dict(unwrap(resp)) + + async def assign_lcg(self, *, version: int | None = None) -> LcgNodeV2: + """GET /2/device/assignLCG — Get the best LCG node for this hub (V2).""" + params: dict[str, Any] = {} + if version is not None: + params["version"] = version + resp = await self._client._request("GET", "/2/device/assignLCG", params=params or None) + return LcgNodeV2.from_dict(unwrap(resp)) + + async def pair(self, pair_code: str) -> str: + """GET /1/device/pair/{pairCode} — Exchange a pair code for the hub's device token.""" + resp = await self._client._request("GET", f"/1/device/pair/{pair_code}") + return str(unwrap(resp)) diff --git a/openshock/_async/resources/meta.py b/openshock/_async/resources/meta.py new file mode 100644 index 0000000..76376f5 --- /dev/null +++ b/openshock/_async/resources/meta.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..._core import unwrap +from ...models import BackendInfo, Stats + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +class AsyncMetaResource: + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + async def backend_info(self) -> BackendInfo: + """GET /1 — Returns backend version and metadata.""" + resp = await self._client._request("GET", "/1") + return BackendInfo.from_any(unwrap(resp)) + + async def online_stats(self) -> Stats: + """GET /1/public/stats — Returns online device/shocker counts.""" + resp = await self._client._request("GET", "/1/public/stats") + return Stats.from_any(unwrap(resp)) diff --git a/openshock/_async/resources/sessions.py b/openshock/_async/resources/sessions.py new file mode 100644 index 0000000..6fd921f --- /dev/null +++ b/openshock/_async/resources/sessions.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import builtins +from typing import TYPE_CHECKING +from uuid import UUID + +from ..._core import unwrap, unwrap_list +from ...models import Session + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +class AsyncSessionsResource: + """Login session management. These endpoints require user-session auth.""" + + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + async def list(self) -> builtins.list[Session]: + """GET /1/sessions — List all login sessions.""" + resp = await self._client._request("GET", "/1/sessions") + return [Session.from_dict(s) for s in unwrap_list(resp)] + + async def get_current(self) -> Session: + """GET /1/sessions/self — Get the current session.""" + resp = await self._client._request("GET", "/1/sessions/self") + return Session.from_dict(unwrap(resp)) + + async def delete(self, session_id: str | UUID) -> None: + """DELETE /1/sessions/{sessionId} — Invalidate a session.""" + await self._client._request("DELETE", f"/1/sessions/{session_id}") diff --git a/openshock/_async/resources/shares.py b/openshock/_async/resources/shares.py new file mode 100644 index 0000000..1cec38e --- /dev/null +++ b/openshock/_async/resources/shares.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any +from uuid import UUID + +from ..._core import unwrap, unwrap_list +from ...models import ( + OwnPublicShare, + PauseReason, + PublicShare, + ShockerLimits, + ShockerPermissions, +) +from ...models.common import parse_pause_reason + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +class AsyncSharesResource: + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + # --- public share links --- + + async def list_public(self) -> list[OwnPublicShare]: + """GET /1/shares/links — List all public shares owned by the user.""" + resp = await self._client._request("GET", "/1/shares/links") + return [OwnPublicShare.from_dict(s) for s in unwrap_list(resp)] + + async def create_public( + self, + name: str, + *, + expires_on: datetime | str | None = None, + ) -> UUID: + """POST /1/shares/links — Create a new public share. Returns the share ID.""" + body: dict[str, Any] = {"name": name} + if expires_on is not None: + body["expiresOn"] = expires_on.isoformat() if isinstance(expires_on, datetime) else expires_on + resp = await self._client._request("POST", "/1/shares/links", json=body) + return UUID(str(unwrap(resp)).strip().strip('"')) + + async def delete_public(self, public_share_id: str | UUID) -> None: + """DELETE /1/shares/links/{publicShareId} — Delete a public share.""" + await self._client._request("DELETE", f"/1/shares/links/{public_share_id}") + + async def public_get(self, public_share_id: str | UUID) -> PublicShare: + """GET /1/public/shares/links/{publicShareId} — Get public share info (unauthenticated).""" + resp = await self._client._request("GET", f"/1/public/shares/links/{public_share_id}") + return PublicShare.from_dict(unwrap(resp)) + + # --- shockers within public shares --- + + async def add_shocker( + self, + public_share_id: str | UUID, + shocker_id: str | UUID, + ) -> None: + """POST /1/shares/links/{publicShareId}/{shockerId} — Add a shocker to a public share.""" + await self._client._request("POST", f"/1/shares/links/{public_share_id}/{shocker_id}") + + async def edit_shocker( + self, + public_share_id: str | UUID, + shocker_id: str | UUID, + *, + permissions: ShockerPermissions, + limits: ShockerLimits, + cooldown: int | None = None, + ) -> None: + """PATCH /1/shares/links/{publicShareId}/{shockerId} — Edit a shocker within a public share.""" + body: dict[str, Any] = { + "permissions": permissions.to_dict(), + "limits": limits.to_dict(), + } + if cooldown is not None: + body["cooldown"] = cooldown + await self._client._request( + "PATCH", + f"/1/shares/links/{public_share_id}/{shocker_id}", + json=body, + ) + + async def remove_shocker( + self, + public_share_id: str | UUID, + shocker_id: str | UUID, + ) -> None: + """DELETE /1/shares/links/{publicShareId}/{shockerId} — Remove a shocker from a public share.""" + await self._client._request("DELETE", f"/1/shares/links/{public_share_id}/{shocker_id}") + + async def pause_shocker( + self, + public_share_id: str | UUID, + shocker_id: str | UUID, + pause: bool, + ) -> PauseReason: + """ + POST /1/shares/links/{publicShareId}/{shockerId}/pause — Pause or unpause a shocker + within a public share. Returns the resulting pause reasons. + """ + resp = await self._client._request( + "POST", + f"/1/shares/links/{public_share_id}/{shocker_id}/pause", + json={"pause": pause}, + ) + return parse_pause_reason(unwrap(resp)) + + # --- share codes --- + + async def link_code(self, share_code_id: str | UUID) -> None: + """POST /1/shares/code/{shareCodeId} — Redeem a share code.""" + await self._client._request("POST", f"/1/shares/code/{share_code_id}") + + async def delete_code(self, share_code_id: str | UUID) -> None: + """DELETE /1/shares/code/{shareCodeId} — Delete a share code.""" + await self._client._request("DELETE", f"/1/shares/code/{share_code_id}") diff --git a/openshock/_async/resources/shockers.py b/openshock/_async/resources/shockers.py new file mode 100644 index 0000000..2f75995 --- /dev/null +++ b/openshock/_async/resources/shockers.py @@ -0,0 +1,225 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any +from uuid import UUID + +from ..._core import unwrap, unwrap_list +from ...models import ( + Control, + DeviceWithShockers, + ShareCode, + ShareInfo, + Shocker, + ShockerLimits, + ShockerLog, + ShockerLogWithHub, + ShockerModelType, + ShockerOwner, + ShockerPermissions, +) + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +class AsyncShockersResource: + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + # --- lists & info --- + + async def list_own(self) -> list[DeviceWithShockers]: + """GET /1/shockers/own — List your hubs, each with its shockers.""" + resp = await self._client._request("GET", "/1/shockers/own") + return [DeviceWithShockers.from_dict(d) for d in unwrap_list(resp)] + + async def list_shared(self) -> list[ShockerOwner]: + """GET /1/shockers/shared — List shockers shared with you, grouped by owner and hub.""" + resp = await self._client._request("GET", "/1/shockers/shared") + return [ShockerOwner.from_dict(o) for o in unwrap_list(resp)] + + async def get(self, shocker_id: str | UUID) -> Shocker: + """GET /1/shockers/{shockerId} — Get a shocker, including the ID of its hub (``.device``).""" + resp = await self._client._request("GET", f"/1/shockers/{shocker_id}") + return Shocker.from_dict(unwrap(resp)) + + # --- CRUD --- + + async def register( + self, + *, + name: str, + rf_id: int, + device: str | UUID, + model: ShockerModelType | str, + ) -> UUID: + """POST /1/shockers — Register a new shocker. Returns the new shocker ID.""" + body = { + "name": name, + "rfId": rf_id, + "device": str(device), + "model": ShockerModelType(model).value, + } + resp = await self._client._request("POST", "/1/shockers", json=body) + return UUID(str(unwrap(resp)).strip().strip('"')) + + async def edit( + self, + shocker_id: str | UUID, + *, + name: str | None = None, + rf_id: int | None = None, + device: str | UUID | None = None, + model: ShockerModelType | str | None = None, + ) -> None: + """PATCH /1/shockers/{shockerId} — Update a shocker.""" + body: dict[str, Any] = {} + if name is not None: + body["name"] = name + if rf_id is not None: + body["rfId"] = rf_id + if device is not None: + body["device"] = str(device) + if model is not None: + body["model"] = ShockerModelType(model).value + await self._client._request("PATCH", f"/1/shockers/{shocker_id}", json=body) + + async def delete(self, shocker_id: str | UUID) -> None: + """DELETE /1/shockers/{shockerId} — Delete a shocker.""" + await self._client._request("DELETE", f"/1/shockers/{shocker_id}") + + # --- control & pause --- + + async def control( + self, + controls: Sequence[Control | dict[str, Any]] | Control, + *, + custom_name: str | None = None, + ) -> None: + """ + POST /2/shockers/control — Send control commands to shockers. + + ``custom_name`` is shown in the control logs as the sender name. + + Raises :class:`~openshock.exceptions.ShockerNotFoundOrNoAccess`, + :class:`~openshock.exceptions.ShockerPaused` or + :class:`~openshock.exceptions.ShockerNoPermission` (each with ``.shocker_id``) + when the backend rejects a command. + """ + if isinstance(controls, Control): + controls = [controls] + if not controls: + raise ValueError("controls must be a non-empty sequence") + + body: dict[str, Any] = {"shocks": [c.to_dict() if isinstance(c, Control) else c for c in controls]} + if custom_name is not None: + body["customName"] = custom_name + + await self._client._request("POST", "/2/shockers/control", json=body) + + async def pause(self, shocker_id: str | UUID, pause: bool) -> bool: + """POST /1/shockers/{shockerId}/pause — Pause or unpause a shocker. Returns the new pause state.""" + resp = await self._client._request("POST", f"/1/shockers/{shocker_id}/pause", json={"pause": pause}) + data = unwrap(resp) + return bool(data) if data is not None else pause + + # --- logs --- + + async def logs( + self, + shocker_id: str | UUID, + *, + offset: int = 0, + limit: int = 100, + ) -> list[ShockerLog]: + """GET /1/shockers/{shockerId}/logs — Get control log history.""" + params = {"offset": offset, "limit": limit} + resp = await self._client._request("GET", f"/1/shockers/{shocker_id}/logs", params=params) + return [ShockerLog.from_dict(e) for e in unwrap_list(resp)] + + async def all_logs( + self, + *, + offset: int = 0, + limit: int = 100, + ) -> list[ShockerLogWithHub]: + """GET /1/shockers/logs — Get logs across all owned shockers.""" + params = {"offset": offset, "limit": limit} + resp = await self._client._request("GET", "/1/shockers/logs", params=params) + return [ShockerLogWithHub.from_dict(e) for e in unwrap_list(resp)] + + # --- shares --- + + async def get_shares(self, shocker_id: str | UUID) -> list[ShareInfo]: + """GET /1/shockers/{shockerId}/shares — Get all user shares for a shocker.""" + resp = await self._client._request("GET", f"/1/shockers/{shocker_id}/shares") + return [ShareInfo.from_dict(s) for s in unwrap_list(resp)] + + async def create_share_code( + self, + shocker_id: str | UUID, + *, + permissions: ShockerPermissions, + limits: ShockerLimits, + ) -> UUID: + """POST /1/shockers/{shockerId}/shares — Create a share code. Returns the code ID.""" + body = { + "permissions": permissions.to_dict(), + "limits": limits.to_dict(), + } + resp = await self._client._request("POST", f"/1/shockers/{shocker_id}/shares", json=body) + return UUID(str(unwrap(resp)).strip().strip('"')) + + async def list_share_codes(self, shocker_id: str | UUID) -> list[ShareCode]: + """GET /1/shockers/{shockerId}/shareCodes — List all share codes.""" + resp = await self._client._request("GET", f"/1/shockers/{shocker_id}/shareCodes") + return [ShareCode.from_dict(c) for c in unwrap_list(resp)] + + async def update_share( + self, + shocker_id: str | UUID, + shared_with_user_id: str | UUID, + *, + permissions: ShockerPermissions, + limits: ShockerLimits, + ) -> None: + """PATCH /1/shockers/{shockerId}/shares/{sharedWithUserId} — Update a share's permissions and limits.""" + body = { + "permissions": permissions.to_dict(), + "limits": limits.to_dict(), + } + await self._client._request( + "PATCH", + f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}", + json=body, + ) + + async def remove_share( + self, + shocker_id: str | UUID, + shared_with_user_id: str | UUID, + ) -> None: + """DELETE /1/shockers/{shockerId}/shares/{sharedWithUserId} — Stop sharing a shocker with a user.""" + await self._client._request( + "DELETE", + f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}", + ) + + async def pause_share( + self, + shocker_id: str | UUID, + shared_with_user_id: str | UUID, + pause: bool, + ) -> bool: + """ + POST /1/shockers/{shockerId}/shares/{sharedWithUserId}/pause — Pause or unpause a share. + Returns the new pause state. + """ + resp = await self._client._request( + "POST", + f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}/pause", + json={"pause": pause}, + ) + data = unwrap(resp) + return bool(data) if data is not None else pause diff --git a/openshock/_async/resources/user_shares.py b/openshock/_async/resources/user_shares.py new file mode 100644 index 0000000..a304487 --- /dev/null +++ b/openshock/_async/resources/user_shares.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any +from uuid import UUID + +from ..._core import unwrap, unwrap_list +from ...models import ( + BulkPauseResult, + ShareInvite, + ShareInviteShocker, + ShockerLimits, + ShockerPermissions, + UserShare, + UserShares, +) + +if TYPE_CHECKING: + from ..client import _AsyncBaseClient + + +class AsyncUserSharesResource: + """V2 user-to-user share management.""" + + def __init__(self, client: _AsyncBaseClient) -> None: + self._client = client + + async def get(self) -> UserShares: + """GET /2/shares/user — Get all user shares (incoming and outgoing).""" + resp = await self._client._request("GET", "/2/shares/user") + return UserShares.from_dict(unwrap(resp)) + + async def create_invite( + self, + shockers: Sequence[ShareInviteShocker | dict[str, Any]], + *, + user: str | UUID | None = None, + ) -> UUID: + """ + POST /2/shares/user/invites — Create a share invite. Returns the invite ID. + + ``user`` targets a specific user; leave it out to create an open invite. + """ + shocker_list = [] + for s in shockers: + if isinstance(s, ShareInviteShocker): + shocker_list.append(s.to_dict()) + else: + shocker_list.append(s) + + body: dict[str, Any] = {"shockers": shocker_list} + if user is not None: + body["user"] = str(user) + + resp = await self._client._request("POST", "/2/shares/user/invites", json=body) + return UUID(str(unwrap(resp)).strip().strip('"')) + + async def list_outgoing_invites(self) -> list[ShareInvite]: + """GET /2/shares/user/invites/outgoing — List pending outgoing invites.""" + resp = await self._client._request("GET", "/2/shares/user/invites/outgoing") + return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] + + async def list_incoming_invites(self) -> list[ShareInvite]: + """GET /2/shares/user/invites/incoming — List pending incoming invites.""" + resp = await self._client._request("GET", "/2/shares/user/invites/incoming") + return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] + + async def accept_invite(self, invite_id: str | UUID) -> UserShare: + """POST /2/shares/user/invites/incoming/{inviteId} — Accept a share invite.""" + resp = await self._client._request("POST", f"/2/shares/user/invites/incoming/{invite_id}") + return UserShare.from_dict(unwrap(resp)) + + async def delete_outgoing_invite(self, invite_id: str | UUID) -> None: + """DELETE /2/shares/user/invites/outgoing/{inviteId} — Cancel an outgoing invite.""" + await self._client._request("DELETE", f"/2/shares/user/invites/outgoing/{invite_id}") + + async def deny_incoming_invite(self, invite_id: str | UUID) -> None: + """DELETE /2/shares/user/invites/incoming/{inviteId} — Deny an incoming invite.""" + await self._client._request("DELETE", f"/2/shares/user/invites/incoming/{invite_id}") + + async def bulk_pause_shockers( + self, + user_id: str | UUID, + shockers: Sequence[str | UUID], + pause: bool, + ) -> BulkPauseResult: + """POST /2/shares/user/{userId}/shockers/pause — Bulk pause/unpause shared shockers.""" + body = { + "shockers": [str(s) for s in shockers], + "pause": pause, + } + resp = await self._client._request("POST", f"/2/shares/user/{user_id}/shockers/pause", json=body) + return BulkPauseResult.from_dict(unwrap(resp) or {}) + + async def bulk_remove_shockers( + self, + user_id: str | UUID, + shockers: Sequence[str | UUID], + ) -> int: + """DELETE /2/shares/user/{userId}/shockers — Bulk remove shared shockers. Returns the number removed.""" + resp = await self._client._request( + "DELETE", + f"/2/shares/user/{user_id}/shockers", + json=[str(s) for s in shockers], + ) + data = unwrap(resp) + return int(data.get("affectedRecords", 0)) if isinstance(data, dict) else 0 + + async def bulk_update_shockers( + self, + user_id: str | UUID, + shockers: Sequence[str | UUID], + *, + permissions: ShockerPermissions, + limits: ShockerLimits, + ) -> None: + """PATCH /2/shares/user/{userId}/shockers — Bulk update shared shocker permissions.""" + body = { + "permissions": permissions.to_dict(), + "limits": limits.to_dict(), + "shockers": [str(s) for s in shockers], + } + await self._client._request("PATCH", f"/2/shares/user/{user_id}/shockers", json=body) diff --git a/openshock/_core.py b/openshock/_core.py new file mode 100644 index 0000000..b05f3e6 --- /dev/null +++ b/openshock/_core.py @@ -0,0 +1,117 @@ +"""IO-free pieces shared by the sync client, the async client and the realtime clients.""" + +from __future__ import annotations + +import platform +import re +from collections.abc import Callable +from typing import Any, TypeVar + +import httpx + +from ._version import __version__ +from .exceptions import OpenShockApiError, error_from_response + +T = TypeVar("T") + +DEFAULT_BASE_URL = "https://api.openshock.app" +DEFAULT_TIMEOUT = 10.0 + +_UA_UNSAFE = re.compile(r"[^\w.\-+ ]") + + +def _os_name() -> str: + system = platform.system() + return {"Windows": "Windows NT", "Darwin": "macOS", "Linux": "Linux"}.get(system, system or "Unknown OS") + + +def build_user_agent( + *, + component: str = "", + app_name: str | None = None, + app_version: str | None = None, + libraries: dict[str, str] | None = None, +) -> str: + """ + Build the SDK User-Agent, e.g.:: + + OpenShock.SDK.Python/0.2.0 (Python 3.13.0; Linux; httpx 0.28.1; MyApp 1.4.0) + + ``app_name`` / ``app_version`` identify the program using the SDK. Setting them is + strongly encouraged: it lets the OpenShock team tell integrations apart. + """ + product = "OpenShock.SDK.Python" + (f".{component}" if component else "") + parts = [f"Python {platform.python_version()}", _os_name()] + for name, ver in (libraries or {}).items(): + parts.append(f"{name} {ver}") + if app_name: + app = _UA_UNSAFE.sub("", app_name).strip() + ver = _UA_UNSAFE.sub("", app_version or "").strip() + if app: + parts.append(f"{app} {ver}".strip()) + return f"{product}/{__version__} ({'; '.join(parts)})" + + +def http_user_agent(app_name: str | None, app_version: str | None) -> str: + return build_user_agent(app_name=app_name, app_version=app_version, libraries={"httpx": httpx.__version__}) + + +def _retry_after(resp: httpx.Response) -> float | None: + raw = resp.headers.get("Retry-After") + if raw is None: + return None + try: + return float(raw) + except ValueError: + return None + + +def error_from_httpx(resp: httpx.Response) -> OpenShockApiError: + try: + body_json: Any = resp.json() + except ValueError: + body_json = None + return error_from_response( + status_code=resp.status_code, + body_text=resp.text, + body_json=body_json, + method=resp.request.method, + url=str(resp.request.url), + retry_after=_retry_after(resp), + ) + + +def handle_response(resp: httpx.Response, transform: Callable[[Any], T] | None = None) -> T | Any: + """ + Turn a completed response into a payload, or raise the matching ``OpenShockApiError``. + + 2xx bodies are returned JSON-decoded when possible, else as text (``None`` when empty). + Legacy ``{"message", "data"}`` envelopes are *not* unwrapped here; resources do that. + """ + if not resp.is_success: + raise error_from_httpx(resp) + + payload: Any + if not resp.content: + payload = None + else: + try: + payload = resp.json() + except ValueError: + payload = resp.text + + if transform is not None: + return transform(payload) + return payload + + +def unwrap(payload: Any) -> Any: + """Unwrap the legacy ``{"message": ..., "data": ...}`` envelope if present.""" + if isinstance(payload, dict) and "data" in payload: + return payload["data"] + return payload + + +def unwrap_list(payload: Any) -> list[Any]: + data = unwrap(payload) + return data if isinstance(data, list) else [] diff --git a/openshock/_sync/__init__.py b/openshock/_sync/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/openshock/_sync/client.py b/openshock/_sync/client.py new file mode 100644 index 0000000..0716662 --- /dev/null +++ b/openshock/_sync/client.py @@ -0,0 +1,192 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. +from __future__ import annotations + +from collections.abc import Callable, Mapping +from types import TracebackType +from typing import Any, TypeVar + +import httpx + +from .._core import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, handle_response, http_user_agent +from ..auth import ApiTokenAuth, Auth, HubTokenAuth +from .resources.account import AccountResource +from .resources.devices import DevicesResource +from .resources.hub import HubResource +from .resources.meta import MetaResource +from .resources.sessions import SessionsResource +from .resources.shares import SharesResource +from .resources.shockers import ShockersResource +from .resources.user_shares import UserSharesResource + +T = TypeVar("T") +_SelfT = TypeVar("_SelfT", bound="_BaseClient") + + +class _BaseClient: + """ + Internal base client that handles HTTP, auth and error mapping. + Concrete clients subclass this and attach resources. + """ + + def __init__( + self, + *, + auth: Auth, + base_url: str = DEFAULT_BASE_URL, + timeout: float = DEFAULT_TIMEOUT, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + transport: httpx.BaseTransport | None = None, + ) -> None: + self._auth = auth + self._base_url = base_url.rstrip("/") + self._app_name = app_name + self._app_version = app_version + self._client = httpx.Client( + base_url=self._base_url, + timeout=timeout, + transport=transport, + headers={**(headers or {}), "User-Agent": http_user_agent(app_name, app_version)}, + ) + + # --- introspection ----------------------------------------------------- + + @property + def auth(self) -> Auth: + return self._auth + + @property + def base_url(self) -> str: + return self._base_url + + # --- lifecycle --------------------------------------------------------- + + def close(self) -> None: + self._client.close() + + def __enter__(self: _SelfT) -> _SelfT: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + # --- internal helpers -------------------------------------------------- + + def _request( + self, + method: str, + path: str, + *, + params: dict[str, Any] | None = None, + json: Any = None, + transform: Callable[[Any], T] | None = None, + ) -> T | Any: + """ + Perform an HTTP request and return the parsed payload for 2xx responses + (JSON-decoded when possible, otherwise text, ``None`` for an empty body). + + On non-2xx an :class:`~openshock.exceptions.OpenShockApiError` subclass is raised; + see :func:`openshock.exceptions.error_from_response` for the mapping. + """ + resp = self._client.request( + method, + path, + params=params, + json=json, + headers=dict(self._auth.headers()), + ) + return handle_response(resp, transform) + + +class OpenShockClient(_BaseClient): + """ + High-level client for the *user* OpenShock REST API (ApiToken-based). + + ``app_name`` / ``app_version`` identify your program in the User-Agent header. + """ + + def __init__( + self, + *, + auth: ApiTokenAuth | None = None, + api_token: str | None = None, + base_url: str = DEFAULT_BASE_URL, + timeout: float = DEFAULT_TIMEOUT, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + transport: httpx.BaseTransport | None = None, + ) -> None: + if auth is not None and api_token is not None: + raise ValueError("Provide either `auth` or `api_token`, not both.") + + if auth is None: + if api_token is None: + raise ValueError("You must provide either `auth` or `api_token`.") + auth = ApiTokenAuth(api_token) + + super().__init__( + auth=auth, + base_url=base_url, + timeout=timeout, + app_name=app_name, + app_version=app_version, + headers=headers, + transport=transport, + ) + + self.meta = MetaResource(self) + self.account = AccountResource(self) + self.devices = DevicesResource(self) + self.shockers = ShockersResource(self) + self.shares = SharesResource(self) + self.sessions = SessionsResource(self) + self.user_shares = UserSharesResource(self) + + +class OpenShockHubClient(_BaseClient): + """ + High-level client for the *hub/device* OpenShock REST API (DeviceToken-based). + + This is what a hub (the ESP32 device) itself talks to. To receive realtime user + events use :class:`openshock.realtime.UserHubClient` instead. + """ + + def __init__( + self, + *, + auth: HubTokenAuth | None = None, + hub_token: str | None = None, + base_url: str = DEFAULT_BASE_URL, + timeout: float = DEFAULT_TIMEOUT, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + transport: httpx.BaseTransport | None = None, + ) -> None: + if auth is not None and hub_token is not None: + raise ValueError("Provide either `auth` or `hub_token`, not both.") + + if auth is None: + if hub_token is None: + raise ValueError("You must provide either `auth` or `hub_token`.") + auth = HubTokenAuth(hub_token) + + super().__init__( + auth=auth, + base_url=base_url, + timeout=timeout, + app_name=app_name, + app_version=app_version, + headers=headers, + transport=transport, + ) + + self.hub = HubResource(self) + self.meta = MetaResource(self) diff --git a/openshock/_sync/resources/__init__.py b/openshock/_sync/resources/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/openshock/resources/account.py b/openshock/_sync/resources/account.py similarity index 57% rename from openshock/resources/account.py rename to openshock/_sync/resources/account.py index cdf7072..51e1322 100644 --- a/openshock/resources/account.py +++ b/openshock/_sync/resources/account.py @@ -1,14 +1,22 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. from __future__ import annotations +from collections.abc import Sequence +from datetime import datetime from typing import TYPE_CHECKING, Any from uuid import UUID -from ..models import Token, User +from ..._core import unwrap, unwrap_list +from ...models import CreatedToken, PermissionType, Token, User if TYPE_CHECKING: from ..client import _BaseClient +def _permissions(permissions: Sequence[PermissionType | str]) -> list[str]: + return [PermissionType(p).value for p in permissions] + + class AccountResource: def __init__(self, client: _BaseClient) -> None: self._client = client @@ -16,49 +24,53 @@ def __init__(self, client: _BaseClient) -> None: def user_self(self) -> User: """GET /1/users/self — Get the authenticated user's info.""" resp = self._client._request("GET", "/1/users/self") - return User.from_dict(resp.get("data", resp)) + return User.from_dict(unwrap(resp)) def token_self(self) -> Token: """GET /1/tokens/self — Get info about the API token being used.""" resp = self._client._request("GET", "/1/tokens/self") - return Token.from_dict(resp.get("data", resp)) + return Token.from_dict(unwrap(resp)) def list_tokens(self) -> list[Token]: """GET /1/tokens — List all API tokens for the authenticated user.""" resp = self._client._request("GET", "/1/tokens") - return [Token.from_dict(t) for t in (resp.get("data") or [])] + return [Token.from_dict(t) for t in unwrap_list(resp)] def create_token( self, name: str, - permissions: list[str], - valid_until: str | None = None, - ) -> Token: - """POST /1/tokens — Create a new API token.""" - body: dict[str, Any] = {"name": name, "permissions": permissions} + permissions: Sequence[PermissionType | str], + valid_until: datetime | str | None = None, + ) -> CreatedToken: + """ + POST /1/tokens — Create a new API token. + + The returned object carries the token secret; it cannot be retrieved again later. + """ + body: dict[str, Any] = {"name": name, "permissions": _permissions(permissions)} if valid_until is not None: - body["validUntil"] = valid_until + body["validUntil"] = valid_until.isoformat() if isinstance(valid_until, datetime) else valid_until resp = self._client._request("POST", "/1/tokens", json=body) - return Token.from_dict(resp.get("data", resp)) + return CreatedToken.from_dict(unwrap(resp)) def get_token(self, token_id: str | UUID) -> Token: """GET /1/tokens/{tokenId} — Get a token by ID.""" resp = self._client._request("GET", f"/1/tokens/{token_id}") - return Token.from_dict(resp.get("data", resp)) + return Token.from_dict(unwrap(resp)) def edit_token( self, token_id: str | UUID, *, name: str | None = None, - permissions: list[str] | None = None, + permissions: Sequence[PermissionType | str] | None = None, ) -> None: """PATCH /1/tokens/{tokenId} — Edit a token's name or permissions.""" body: dict[str, Any] = {} if name is not None: body["name"] = name if permissions is not None: - body["permissions"] = permissions + body["permissions"] = _permissions(permissions) self._client._request("PATCH", f"/1/tokens/{token_id}", json=body) def revoke_token(self, token_id: str | UUID) -> None: diff --git a/openshock/_sync/resources/devices.py b/openshock/_sync/resources/devices.py new file mode 100644 index 0000000..d80dfb1 --- /dev/null +++ b/openshock/_sync/resources/devices.py @@ -0,0 +1,81 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. +from __future__ import annotations + +import builtins +from typing import TYPE_CHECKING +from uuid import UUID + +from ..._core import unwrap, unwrap_list +from ...models import Device, DeviceWithToken, HubGateway, LcgInfo, OtaUpdate, Shocker + +if TYPE_CHECKING: + from ..client import _BaseClient + + +class DevicesResource: + """Hub (device) management.""" + + def __init__(self, client: _BaseClient) -> None: + self._client = client + + def list(self) -> builtins.list[Device]: + """GET /1/devices — List all hubs owned by the authenticated user.""" + resp = self._client._request("GET", "/1/devices") + return [Device.from_dict(d) for d in unwrap_list(resp)] + + def create(self, name: str) -> UUID: + """POST /2/devices — Create a new hub. Returns the new hub's ID.""" + resp = self._client._request("POST", "/2/devices", json={"name": name}) + return UUID(str(unwrap(resp)).strip().strip('"')) + + def get(self, device_id: str | UUID) -> DeviceWithToken: + """ + GET /1/devices/{deviceId} — Get a hub. + + The hub's device token is included when you are allowed to see it. + """ + resp = self._client._request("GET", f"/1/devices/{device_id}") + return DeviceWithToken.from_dict(unwrap(resp)) + + def edit(self, device_id: str | UUID, *, name: str) -> None: + """PATCH /1/devices/{deviceId} — Rename a hub.""" + self._client._request("PATCH", f"/1/devices/{device_id}", json={"name": name}) + + def delete(self, device_id: str | UUID) -> None: + """DELETE /1/devices/{deviceId} — Delete a hub.""" + self._client._request("DELETE", f"/1/devices/{device_id}") + + def regenerate_token(self, device_id: str | UUID) -> str: + """PUT /1/devices/{deviceId} — Regenerate the hub's device token. Returns the new token.""" + resp = self._client._request("PUT", f"/1/devices/{device_id}") + return str(unwrap(resp)) + + def shockers(self, device_id: str | UUID) -> builtins.list[Shocker]: + """GET /1/devices/{deviceId}/shockers — List the shockers of a hub.""" + resp = self._client._request("GET", f"/1/devices/{device_id}/shockers") + return [Shocker.from_dict(s) for s in unwrap_list(resp)] + + def pair_code(self, device_id: str | UUID) -> str: + """GET /1/devices/{deviceId}/pair — Generate a pair code for a hub (valid 15 minutes).""" + resp = self._client._request("GET", f"/1/devices/{device_id}/pair") + return str(unwrap(resp)) + + def gateway(self, device_id: str | UUID) -> HubGateway: + """ + GET /2/devices/{deviceId}/lcg — Get the live control gateway a hub is connected to. + + Raises :class:`~openshock.exceptions.HubOffline` when the hub is not online and + :class:`~openshock.exceptions.HubNotFound` when it does not exist or is not yours. + """ + resp = self._client._request("GET", f"/2/devices/{device_id}/lcg") + return HubGateway.from_dict(unwrap(resp)) + + def lcg_info(self, device_id: str | UUID) -> LcgInfo: + """GET /1/devices/{deviceId}/lcg — Legacy gateway lookup. Prefer :meth:`gateway`.""" + resp = self._client._request("GET", f"/1/devices/{device_id}/lcg") + return LcgInfo.from_dict(unwrap(resp)) + + def ota_history(self, device_id: str | UUID) -> builtins.list[OtaUpdate]: + """GET /1/devices/{deviceId}/ota — Get the firmware update history of a hub.""" + resp = self._client._request("GET", f"/1/devices/{device_id}/ota") + return [OtaUpdate.from_dict(o) for o in unwrap_list(resp)] diff --git a/openshock/resources/hub.py b/openshock/_sync/resources/hub.py similarity index 65% rename from openshock/resources/hub.py rename to openshock/_sync/resources/hub.py index cb38ec3..851462b 100644 --- a/openshock/resources/hub.py +++ b/openshock/_sync/resources/hub.py @@ -1,8 +1,10 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. from __future__ import annotations from typing import TYPE_CHECKING, Any -from ..models import DeviceSelf, LcgNodeV2 +from ..._core import unwrap +from ...models import DeviceSelf, LcgNodeV2 if TYPE_CHECKING: from ..client import _BaseClient @@ -17,7 +19,7 @@ def __init__(self, client: _BaseClient) -> None: def self_info(self) -> DeviceSelf: """GET /1/device/self — Get info about the authenticated hub.""" resp = self._client._request("GET", "/1/device/self") - return DeviceSelf.from_dict(resp.get("data", resp)) + return DeviceSelf.from_dict(unwrap(resp)) def assign_lcg(self, *, version: int | None = None) -> LcgNodeV2: """GET /2/device/assignLCG — Get the best LCG node for this hub (V2).""" @@ -25,11 +27,9 @@ def assign_lcg(self, *, version: int | None = None) -> LcgNodeV2: if version is not None: params["version"] = version resp = self._client._request("GET", "/2/device/assignLCG", params=params or None) - return LcgNodeV2.from_dict(resp) + return LcgNodeV2.from_dict(unwrap(resp)) def pair(self, pair_code: str) -> str: - """GET /1/device/pair/{pairCode} — Pair hub with account.""" - resp: Any = self._client._request("GET", f"/1/device/pair/{pair_code}") - if isinstance(resp, dict): - return str(resp.get("data", "")) - return str(resp) + """GET /1/device/pair/{pairCode} — Exchange a pair code for the hub's device token.""" + resp = self._client._request("GET", f"/1/device/pair/{pair_code}") + return str(unwrap(resp)) diff --git a/openshock/resources/meta.py b/openshock/_sync/resources/meta.py similarity index 68% rename from openshock/resources/meta.py rename to openshock/_sync/resources/meta.py index 031c6a0..a1e8cd0 100644 --- a/openshock/resources/meta.py +++ b/openshock/_sync/resources/meta.py @@ -1,8 +1,10 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. from __future__ import annotations from typing import TYPE_CHECKING -from ..models import BackendInfo, Stats +from ..._core import unwrap +from ...models import BackendInfo, Stats if TYPE_CHECKING: from ..client import _BaseClient @@ -15,9 +17,9 @@ def __init__(self, client: _BaseClient) -> None: def backend_info(self) -> BackendInfo: """GET /1 — Returns backend version and metadata.""" resp = self._client._request("GET", "/1") - return BackendInfo.from_any(resp.get("data", resp)) + return BackendInfo.from_any(unwrap(resp)) def online_stats(self) -> Stats: """GET /1/public/stats — Returns online device/shocker counts.""" resp = self._client._request("GET", "/1/public/stats") - return Stats.from_any(resp.get("data", resp)) + return Stats.from_any(unwrap(resp)) diff --git a/openshock/resources/sessions.py b/openshock/_sync/resources/sessions.py similarity index 52% rename from openshock/resources/sessions.py rename to openshock/_sync/resources/sessions.py index 90b5748..346db9d 100644 --- a/openshock/resources/sessions.py +++ b/openshock/_sync/resources/sessions.py @@ -1,29 +1,33 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. from __future__ import annotations import builtins from typing import TYPE_CHECKING from uuid import UUID -from ..models import Session +from ..._core import unwrap, unwrap_list +from ...models import Session if TYPE_CHECKING: from ..client import _BaseClient class SessionsResource: + """Login session management. These endpoints require user-session auth.""" + def __init__(self, client: _BaseClient) -> None: self._client = client def list(self) -> builtins.list[Session]: - """GET /1/sessions — List all active login sessions.""" + """GET /1/sessions — List all login sessions.""" resp = self._client._request("GET", "/1/sessions") - return [Session.from_dict(s) for s in (resp.get("data") or [])] + return [Session.from_dict(s) for s in unwrap_list(resp)] def get_current(self) -> Session: - """GET /1/sessions/self — Get info about the current session.""" + """GET /1/sessions/self — Get the current session.""" resp = self._client._request("GET", "/1/sessions/self") - return Session.from_dict(resp.get("data", resp)) + return Session.from_dict(unwrap(resp)) def delete(self, session_id: str | UUID) -> None: - """DELETE /1/sessions/{sessionId} — Revoke a session.""" + """DELETE /1/sessions/{sessionId} — Invalidate a session.""" self._client._request("DELETE", f"/1/sessions/{session_id}") diff --git a/openshock/resources/shares.py b/openshock/_sync/resources/shares.py similarity index 69% rename from openshock/resources/shares.py rename to openshock/_sync/resources/shares.py index f263f43..2f3ff79 100644 --- a/openshock/resources/shares.py +++ b/openshock/_sync/resources/shares.py @@ -1,14 +1,19 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. from __future__ import annotations +from datetime import datetime from typing import TYPE_CHECKING, Any from uuid import UUID -from ..models import ( +from ..._core import unwrap, unwrap_list +from ...models import ( OwnPublicShare, + PauseReason, PublicShare, ShockerLimits, ShockerPermissions, ) +from ...models.common import parse_pause_reason if TYPE_CHECKING: from ..client import _BaseClient @@ -23,22 +28,20 @@ def __init__(self, client: _BaseClient) -> None: def list_public(self) -> list[OwnPublicShare]: """GET /1/shares/links — List all public shares owned by the user.""" resp = self._client._request("GET", "/1/shares/links") - return [OwnPublicShare.from_dict(s) for s in (resp.get("data") or [])] + return [OwnPublicShare.from_dict(s) for s in unwrap_list(resp)] def create_public( self, name: str, *, - expires_on: str | None = None, - ) -> str: - """POST /1/shares/links — Create a new public share. Returns share ID.""" + expires_on: datetime | str | None = None, + ) -> UUID: + """POST /1/shares/links — Create a new public share. Returns the share ID.""" body: dict[str, Any] = {"name": name} if expires_on is not None: - body["expiresOn"] = expires_on - resp: Any = self._client._request("POST", "/1/shares/links", json=body) - if isinstance(resp, dict): - return str(resp.get("data", "")) - return str(resp) + body["expiresOn"] = expires_on.isoformat() if isinstance(expires_on, datetime) else expires_on + resp = self._client._request("POST", "/1/shares/links", json=body) + return UUID(str(unwrap(resp)).strip().strip('"')) def delete_public(self, public_share_id: str | UUID) -> None: """DELETE /1/shares/links/{publicShareId} — Delete a public share.""" @@ -47,7 +50,7 @@ def delete_public(self, public_share_id: str | UUID) -> None: def public_get(self, public_share_id: str | UUID) -> PublicShare: """GET /1/public/shares/links/{publicShareId} — Get public share info (unauthenticated).""" resp = self._client._request("GET", f"/1/public/shares/links/{public_share_id}") - return PublicShare.from_dict(resp.get("data", resp)) + return PublicShare.from_dict(unwrap(resp)) # --- shockers within public shares --- @@ -56,7 +59,7 @@ def add_shocker( public_share_id: str | UUID, shocker_id: str | UUID, ) -> None: - """POST /1/shares/links/{publicShareId}/{shockerId}""" + """POST /1/shares/links/{publicShareId}/{shockerId} — Add a shocker to a public share.""" self._client._request("POST", f"/1/shares/links/{public_share_id}/{shocker_id}") def edit_shocker( @@ -68,7 +71,7 @@ def edit_shocker( limits: ShockerLimits, cooldown: int | None = None, ) -> None: - """PATCH /1/shares/links/{publicShareId}/{shockerId}""" + """PATCH /1/shares/links/{publicShareId}/{shockerId} — Edit a shocker within a public share.""" body: dict[str, Any] = { "permissions": permissions.to_dict(), "limits": limits.to_dict(), @@ -86,7 +89,7 @@ def remove_shocker( public_share_id: str | UUID, shocker_id: str | UUID, ) -> None: - """DELETE /1/shares/links/{publicShareId}/{shockerId}""" + """DELETE /1/shares/links/{publicShareId}/{shockerId} — Remove a shocker from a public share.""" self._client._request("DELETE", f"/1/shares/links/{public_share_id}/{shocker_id}") def pause_shocker( @@ -94,13 +97,17 @@ def pause_shocker( public_share_id: str | UUID, shocker_id: str | UUID, pause: bool, - ) -> Any: - """POST /1/shares/links/{publicShareId}/{shockerId}/pause""" - return self._client._request( + ) -> PauseReason: + """ + POST /1/shares/links/{publicShareId}/{shockerId}/pause — Pause or unpause a shocker + within a public share. Returns the resulting pause reasons. + """ + resp = self._client._request( "POST", f"/1/shares/links/{public_share_id}/{shocker_id}/pause", json={"pause": pause}, ) + return parse_pause_reason(unwrap(resp)) # --- share codes --- diff --git a/openshock/resources/shockers.py b/openshock/_sync/resources/shockers.py similarity index 59% rename from openshock/resources/shockers.py rename to openshock/_sync/resources/shockers.py index 8bc88f3..5e46316 100644 --- a/openshock/resources/shockers.py +++ b/openshock/_sync/resources/shockers.py @@ -1,15 +1,22 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. from __future__ import annotations from collections.abc import Sequence from typing import TYPE_CHECKING, Any from uuid import UUID -from ..models import ( +from ..._core import unwrap, unwrap_list +from ...models import ( Control, + DeviceWithShockers, ShareCode, ShareInfo, + Shocker, ShockerLimits, ShockerLog, + ShockerLogWithHub, + ShockerModelType, + ShockerOwner, ShockerPermissions, ) @@ -23,20 +30,20 @@ def __init__(self, client: _BaseClient) -> None: # --- lists & info --- - def list_own(self) -> list[dict[str, Any]]: - """GET /1/shockers/own — List all shockers belonging to the authenticated user.""" + def list_own(self) -> list[DeviceWithShockers]: + """GET /1/shockers/own — List your hubs, each with its shockers.""" resp = self._client._request("GET", "/1/shockers/own") - return resp.get("data") or [] + return [DeviceWithShockers.from_dict(d) for d in unwrap_list(resp)] - def list_shared(self) -> list[dict[str, Any]]: - """GET /1/shockers/shared — List all shockers shared with the authenticated user.""" + def list_shared(self) -> list[ShockerOwner]: + """GET /1/shockers/shared — List shockers shared with you, grouped by owner and hub.""" resp = self._client._request("GET", "/1/shockers/shared") - return resp.get("data") or [] + return [ShockerOwner.from_dict(o) for o in unwrap_list(resp)] - def get(self, shocker_id: str | UUID) -> dict[str, Any]: - """GET /1/shockers/{shockerId} — Get shocker info with device details.""" + def get(self, shocker_id: str | UUID) -> Shocker: + """GET /1/shockers/{shockerId} — Get a shocker, including the ID of its hub (``.device``).""" resp = self._client._request("GET", f"/1/shockers/{shocker_id}") - return resp.get("data") or {} + return Shocker.from_dict(unwrap(resp)) # --- CRUD --- @@ -46,19 +53,17 @@ def register( name: str, rf_id: int, device: str | UUID, - model: str, - ) -> str: + model: ShockerModelType | str, + ) -> UUID: """POST /1/shockers — Register a new shocker. Returns the new shocker ID.""" body = { "name": name, "rfId": rf_id, "device": str(device), - "model": model, + "model": ShockerModelType(model).value, } - resp: Any = self._client._request("POST", "/1/shockers", json=body) - if isinstance(resp, dict): - return str(resp.get("data", "")) - return str(resp) + resp = self._client._request("POST", "/1/shockers", json=body) + return UUID(str(unwrap(resp)).strip().strip('"')) def edit( self, @@ -67,7 +72,7 @@ def edit( name: str | None = None, rf_id: int | None = None, device: str | UUID | None = None, - model: str | None = None, + model: ShockerModelType | str | None = None, ) -> None: """PATCH /1/shockers/{shockerId} — Update a shocker.""" body: dict[str, Any] = {} @@ -78,41 +83,47 @@ def edit( if device is not None: body["device"] = str(device) if model is not None: - body["model"] = model + body["model"] = ShockerModelType(model).value self._client._request("PATCH", f"/1/shockers/{shocker_id}", json=body) def delete(self, shocker_id: str | UUID) -> None: - """DELETE /1/shockers/{shockerId} — Remove a shocker.""" + """DELETE /1/shockers/{shockerId} — Delete a shocker.""" self._client._request("DELETE", f"/1/shockers/{shocker_id}") # --- control & pause --- def control( self, - controls: Sequence[Control | dict[str, Any]], + controls: Sequence[Control | dict[str, Any]] | Control, *, custom_name: str | None = None, - ) -> Any: - """POST /2/shockers/control — Send control commands to shockers (V2).""" + ) -> None: + """ + POST /2/shockers/control — Send control commands to shockers. + + ``custom_name`` is shown in the control logs as the sender name. + + Raises :class:`~openshock.exceptions.ShockerNotFoundOrNoAccess`, + :class:`~openshock.exceptions.ShockerPaused` or + :class:`~openshock.exceptions.ShockerNoPermission` (each with ``.shocker_id``) + when the backend rejects a command. + """ + if isinstance(controls, Control): + controls = [controls] if not controls: raise ValueError("controls must be a non-empty sequence") - shocks = [] - for c in controls: - if isinstance(c, Control): - shocks.append(c.to_dict()) - else: - shocks.append(c) - - body: dict[str, Any] = {"shocks": shocks} + body: dict[str, Any] = {"shocks": [c.to_dict() if isinstance(c, Control) else c for c in controls]} if custom_name is not None: body["customName"] = custom_name - return self._client._request("POST", "/2/shockers/control", json=body) + self._client._request("POST", "/2/shockers/control", json=body) - def pause(self, shocker_id: str | UUID, pause: bool) -> Any: - """POST /1/shockers/{shockerId}/pause — Pause or unpause a shocker.""" - return self._client._request("POST", f"/1/shockers/{shocker_id}/pause", json={"pause": pause}) + def pause(self, shocker_id: str | UUID, pause: bool) -> bool: + """POST /1/shockers/{shockerId}/pause — Pause or unpause a shocker. Returns the new pause state.""" + resp = self._client._request("POST", f"/1/shockers/{shocker_id}/pause", json={"pause": pause}) + data = unwrap(resp) + return bool(data) if data is not None else pause # --- logs --- @@ -126,25 +137,25 @@ def logs( """GET /1/shockers/{shockerId}/logs — Get control log history.""" params = {"offset": offset, "limit": limit} resp = self._client._request("GET", f"/1/shockers/{shocker_id}/logs", params=params) - return [ShockerLog.from_dict(e) for e in (resp.get("data") or [])] + return [ShockerLog.from_dict(e) for e in unwrap_list(resp)] def all_logs( self, *, offset: int = 0, limit: int = 100, - ) -> list[dict[str, Any]]: + ) -> list[ShockerLogWithHub]: """GET /1/shockers/logs — Get logs across all owned shockers.""" params = {"offset": offset, "limit": limit} resp = self._client._request("GET", "/1/shockers/logs", params=params) - return resp.get("data") or [] + return [ShockerLogWithHub.from_dict(e) for e in unwrap_list(resp)] # --- shares --- def get_shares(self, shocker_id: str | UUID) -> list[ShareInfo]: """GET /1/shockers/{shockerId}/shares — Get all user shares for a shocker.""" resp = self._client._request("GET", f"/1/shockers/{shocker_id}/shares") - return [ShareInfo.from_dict(s) for s in (resp.get("data") or [])] + return [ShareInfo.from_dict(s) for s in unwrap_list(resp)] def create_share_code( self, @@ -152,21 +163,19 @@ def create_share_code( *, permissions: ShockerPermissions, limits: ShockerLimits, - ) -> str: - """POST /1/shockers/{shockerId}/shares — Create a share code. Returns code ID.""" + ) -> UUID: + """POST /1/shockers/{shockerId}/shares — Create a share code. Returns the code ID.""" body = { "permissions": permissions.to_dict(), "limits": limits.to_dict(), } - resp: Any = self._client._request("POST", f"/1/shockers/{shocker_id}/shares", json=body) - if isinstance(resp, dict): - return str(resp.get("data", "")) - return str(resp) + resp = self._client._request("POST", f"/1/shockers/{shocker_id}/shares", json=body) + return UUID(str(unwrap(resp)).strip().strip('"')) def list_share_codes(self, shocker_id: str | UUID) -> list[ShareCode]: """GET /1/shockers/{shockerId}/shareCodes — List all share codes.""" resp = self._client._request("GET", f"/1/shockers/{shocker_id}/shareCodes") - return [ShareCode.from_dict(c) for c in (resp.get("data") or [])] + return [ShareCode.from_dict(c) for c in unwrap_list(resp)] def update_share( self, @@ -176,7 +185,7 @@ def update_share( permissions: ShockerPermissions, limits: ShockerLimits, ) -> None: - """PATCH /1/shockers/{shockerId}/shares/{sharedWithUserId}""" + """PATCH /1/shockers/{shockerId}/shares/{sharedWithUserId} — Update a share's permissions and limits.""" body = { "permissions": permissions.to_dict(), "limits": limits.to_dict(), @@ -192,7 +201,7 @@ def remove_share( shocker_id: str | UUID, shared_with_user_id: str | UUID, ) -> None: - """DELETE /1/shockers/{shockerId}/shares/{sharedWithUserId}""" + """DELETE /1/shockers/{shockerId}/shares/{sharedWithUserId} — Stop sharing a shocker with a user.""" self._client._request( "DELETE", f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}", @@ -203,10 +212,15 @@ def pause_share( shocker_id: str | UUID, shared_with_user_id: str | UUID, pause: bool, - ) -> Any: - """POST /1/shockers/{shockerId}/shares/{sharedWithUserId}/pause""" - return self._client._request( + ) -> bool: + """ + POST /1/shockers/{shockerId}/shares/{sharedWithUserId}/pause — Pause or unpause a share. + Returns the new pause state. + """ + resp = self._client._request( "POST", f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}/pause", json={"pause": pause}, ) + data = unwrap(resp) + return bool(data) if data is not None else pause diff --git a/openshock/resources/user_shares.py b/openshock/_sync/resources/user_shares.py similarity index 77% rename from openshock/resources/user_shares.py rename to openshock/_sync/resources/user_shares.py index 82c456c..5a31dc9 100644 --- a/openshock/resources/user_shares.py +++ b/openshock/_sync/resources/user_shares.py @@ -1,10 +1,13 @@ +# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. from __future__ import annotations from collections.abc import Sequence from typing import TYPE_CHECKING, Any from uuid import UUID -from ..models import ( +from ..._core import unwrap, unwrap_list +from ...models import ( + BulkPauseResult, ShareInvite, ShareInviteShocker, ShockerLimits, @@ -26,15 +29,19 @@ def __init__(self, client: _BaseClient) -> None: def get(self) -> UserShares: """GET /2/shares/user — Get all user shares (incoming and outgoing).""" resp = self._client._request("GET", "/2/shares/user") - return UserShares.from_dict(resp) + return UserShares.from_dict(unwrap(resp)) def create_invite( self, shockers: Sequence[ShareInviteShocker | dict[str, Any]], *, user: str | UUID | None = None, - ) -> str: - """POST /2/shares/user/invites — Create a share invite. Returns invite ID.""" + ) -> UUID: + """ + POST /2/shares/user/invites — Create a share invite. Returns the invite ID. + + ``user`` targets a specific user; leave it out to create an open invite. + """ shocker_list = [] for s in shockers: if isinstance(s, ShareInviteShocker): @@ -47,24 +54,22 @@ def create_invite( body["user"] = str(user) resp = self._client._request("POST", "/2/shares/user/invites", json=body) - if isinstance(resp, str): - return resp - return str(resp) + return UUID(str(unwrap(resp)).strip().strip('"')) def list_outgoing_invites(self) -> list[ShareInvite]: """GET /2/shares/user/invites/outgoing — List pending outgoing invites.""" resp = self._client._request("GET", "/2/shares/user/invites/outgoing") - return [ShareInvite.from_dict(i) for i in (resp if isinstance(resp, list) else [])] + return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] def list_incoming_invites(self) -> list[ShareInvite]: """GET /2/shares/user/invites/incoming — List pending incoming invites.""" resp = self._client._request("GET", "/2/shares/user/invites/incoming") - return [ShareInvite.from_dict(i) for i in (resp if isinstance(resp, list) else [])] + return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] def accept_invite(self, invite_id: str | UUID) -> UserShare: """POST /2/shares/user/invites/incoming/{inviteId} — Accept a share invite.""" resp = self._client._request("POST", f"/2/shares/user/invites/incoming/{invite_id}") - return UserShare.from_dict(resp) + return UserShare.from_dict(unwrap(resp)) def delete_outgoing_invite(self, invite_id: str | UUID) -> None: """DELETE /2/shares/user/invites/outgoing/{inviteId} — Cancel an outgoing invite.""" @@ -79,25 +84,28 @@ def bulk_pause_shockers( user_id: str | UUID, shockers: Sequence[str | UUID], pause: bool, - ) -> dict[str, Any]: + ) -> BulkPauseResult: """POST /2/shares/user/{userId}/shockers/pause — Bulk pause/unpause shared shockers.""" body = { "shockers": [str(s) for s in shockers], "pause": pause, } - return self._client._request("POST", f"/2/shares/user/{user_id}/shockers/pause", json=body) + resp = self._client._request("POST", f"/2/shares/user/{user_id}/shockers/pause", json=body) + return BulkPauseResult.from_dict(unwrap(resp) or {}) def bulk_remove_shockers( self, user_id: str | UUID, shockers: Sequence[str | UUID], - ) -> dict[str, Any]: - """DELETE /2/shares/user/{userId}/shockers — Bulk remove shared shockers.""" - return self._client._request( + ) -> int: + """DELETE /2/shares/user/{userId}/shockers — Bulk remove shared shockers. Returns the number removed.""" + resp = self._client._request( "DELETE", f"/2/shares/user/{user_id}/shockers", json=[str(s) for s in shockers], ) + data = unwrap(resp) + return int(data.get("affectedRecords", 0)) if isinstance(data, dict) else 0 def bulk_update_shockers( self, diff --git a/openshock/_version.py b/openshock/_version.py new file mode 100644 index 0000000..2d76904 --- /dev/null +++ b/openshock/_version.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("openshock") +except PackageNotFoundError: # running from a source checkout that is not installed + __version__ = "0.0.0" diff --git a/openshock/client.py b/openshock/client.py index 15bf2da..60998c8 100644 --- a/openshock/client.py +++ b/openshock/client.py @@ -1,192 +1,6 @@ -from __future__ import annotations +"""Public home of the REST clients. The sync classes are generated from the async ones.""" -from collections.abc import Callable -from types import TracebackType -from typing import Any, TypeVar - -import httpx - -from .auth import ApiTokenAuth, Auth, HubTokenAuth -from .exceptions import ( - OpenShockApiError, - OpenShockAuthError, - OpenShockNotFound, -) -from .resources.account import AccountResource -from .resources.devices import DevicesResource -from .resources.hub import HubResource -from .resources.meta import MetaResource -from .resources.sessions import SessionsResource -from .resources.shares import SharesResource -from .resources.shockers import ShockersResource -from .resources.user_shares import UserSharesResource - -T = TypeVar("T") -_SelfT = TypeVar("_SelfT", bound="_BaseClient") - - -class _BaseClient: - """ - Internal base client that handles HTTP, auth and error mapping. - Concrete clients subclass this and attach resources. - """ - - def __init__( - self, - *, - auth: Auth, - base_url: str = "https://api.openshock.app", - timeout: float = 10.0, - ) -> None: - self._auth = auth - self._client = httpx.Client( - base_url=base_url, - timeout=timeout, - ) - - # --- lifecycle --------------------------------------------------------- - - def close(self) -> None: - self._client.close() - - def __enter__(self: _SelfT) -> _SelfT: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - self.close() - - # --- internal helpers -------------------------------------------------- - - def _request( - self, - method: str, - path: str, - *, - params: dict[str, Any] | None = None, - json: Any = None, - transform: Callable[[Any], T] | None = None, - ) -> T | Any: - """ - Perform an HTTP request and return parsed JSON/text for 2xx responses. - - - NO special handling of any "wrapper" formats. - - If `transform` is provided, it's called with the parsed payload - (JSON-decoded object or text), and its return value is returned. - - Otherwise the parsed payload is returned as-is. - - On non-2xx, raises: - - OpenShockAuthError (401/403) - - OpenShockNotFound (404) - - OpenShockApiError (anything else) - """ - headers = dict(self._auth.headers() or {}) - - resp = self._client.request( - method, - path, - params=params, - json=json, - headers=headers, - ) - - # Success - if 200 <= resp.status_code < 300: - # Parse body -> payload - if "application/json" in resp.headers.get("Content-Type", ""): - payload: Any = resp.json() - else: - try: - payload = resp.json() - except ValueError: - payload = resp.text - - if transform is not None: - return transform(payload) - return payload - - # Error path: try to parse problem details if present. - message = None - detail = None - title = None - try: - body = resp.json() - message = body.get("message") or body.get("detail") or body.get("title") - detail = body.get("detail") - title = body.get("title") - except Exception: - body = None # noqa: F841 - - text = message or detail or title or resp.text or f"HTTP {resp.status_code}" - - if resp.status_code in (401, 403): - raise OpenShockAuthError(text) - if resp.status_code == 404: - raise OpenShockNotFound(text) - - raise OpenShockApiError(f"{resp.status_code} error calling {resp.request.method} {resp.request.url}: {text}") - - -class OpenShockClient(_BaseClient): - """ - High-level client for the *user* OpenShock REST API (ApiToken-based). - """ - - def __init__( - self, - *, - auth: ApiTokenAuth | None = None, - api_token: str | None = None, - base_url: str = "https://api.openshock.app", - timeout: float = 10.0, - ) -> None: - if auth is not None and api_token is not None: - raise ValueError("Provide either `auth` or `api_token`, not both.") - - if auth is None and api_token is None: - raise ValueError("You must provide either `auth` or `api_token`.") - - if auth is None: - auth = ApiTokenAuth(api_token) # type: ignore[arg-type] - - super().__init__(auth=auth, base_url=base_url, timeout=timeout) - - self.meta = MetaResource(self) - self.account = AccountResource(self) - self.devices = DevicesResource(self) - self.shockers = ShockersResource(self) - self.shares = SharesResource(self) - self.sessions = SessionsResource(self) - self.user_shares = UserSharesResource(self) - - -class OpenShockHubClient(_BaseClient): - """ - High-level client for the *hub/device* OpenShock REST API (HubToken-based). - """ - - def __init__( - self, - *, - auth: HubTokenAuth | None = None, - hub_token: str | None = None, - base_url: str = "https://api.openshock.app", - timeout: float = 10.0, - ) -> None: - if auth is not None and hub_token is not None: - raise ValueError("Provide either `auth` or `hub_token`, not both.") - - if auth is None and hub_token is None: - raise ValueError("You must provide either `auth` or `hub_token`.") - - if auth is None: - auth = HubTokenAuth(hub_token) # type: ignore[arg-type] - - super().__init__(auth=auth, base_url=base_url, timeout=timeout) - - self.hub = HubResource(self) - self.meta = MetaResource(self) +from ._async.client import AsyncOpenShockClient as AsyncOpenShockClient +from ._async.client import AsyncOpenShockHubClient as AsyncOpenShockHubClient +from ._sync.client import OpenShockClient as OpenShockClient +from ._sync.client import OpenShockHubClient as OpenShockHubClient diff --git a/openshock/exceptions.py b/openshock/exceptions.py index a380e22..f2a11fb 100644 --- a/openshock/exceptions.py +++ b/openshock/exceptions.py @@ -1,14 +1,193 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any +from uuid import UUID + + +@dataclass(frozen=True) +class ProblemDetails: + """An RFC 7807 problem document as returned by the OpenShock backend.""" + + type: str + title: str + status: int + detail: str | None = None + request_id: str | None = None + #: Problem-specific members, e.g. ``shockerId`` or ``requiredPermission``. + extensions: dict[str, Any] = field(default_factory=dict) + + @classmethod + def from_dict(cls, data: dict[str, Any], *, status: int | None = None) -> ProblemDetails: + known = {"type", "title", "status", "detail", "requestid", "traceid"} + return cls( + type=str(data.get("type") or ""), + title=str(data.get("title") or ""), + status=int(data.get("status") or status or 0), + detail=data.get("detail"), + request_id=data.get("requestId") or data.get("traceId"), + extensions={k: v for k, v in data.items() if k.lower() not in known}, + ) + + class OpenShockError(Exception): - """Base error for OpenShock client.""" + """Base error for everything raised by the OpenShock SDK.""" + + +class OpenShockApiError(OpenShockError): + """ + The backend answered with a non-2xx response. + + ``status_code`` is always set. ``problem`` holds the parsed problem document when the + backend sent one; ``problem.type`` (e.g. ``"Shocker.Control.Paused"``) is the stable + identifier to branch on. + """ + + def __init__( + self, + message: str, + *, + status_code: int = 0, + problem: ProblemDetails | None = None, + body: str | None = None, + ) -> None: + super().__init__(message) + self.message = message + self.status_code = status_code + self.problem = problem + self.body = body + @property + def problem_type(self) -> str | None: + return self.problem.type if self.problem else None -class OpenShockAuthError(OpenShockError): + +class OpenShockAuthError(OpenShockApiError): """Authentication / authorization failed (401/403).""" -class OpenShockNotFound(OpenShockError): +class OpenShockNotFound(OpenShockApiError): """Resource not found (404).""" -class OpenShockApiError(OpenShockError): - """Unexpected non-2xx response.""" +class OpenShockRateLimited(OpenShockApiError): + """Too many requests (429). ``retry_after`` is the server-suggested wait in seconds, if any.""" + + def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None: + super().__init__(message, **kwargs) + self.retry_after = retry_after + + +class TokenPermissionMissing(OpenShockAuthError): + """The API token lacks a permission this endpoint requires.""" + + @property + def required_permission(self) -> str | None: + value = _ext(self.problem, "requiredPermission") + return str(value) if value is not None else None + + @property + def granted_permissions(self) -> list[str]: + return list(_ext(self.problem, "grantedPermissions") or []) + + +class ApiTokenPaused(OpenShockAuthError): + """The API token is paused and may not control shockers.""" + + +class HubNotFound(OpenShockNotFound): + """The hub does not exist or you have no access to it.""" + + +class HubOffline(OpenShockNotFound): + """The hub exists but is not currently connected to a gateway.""" + + +class ShockerControlError(OpenShockApiError): + """A control request was rejected for a specific shocker.""" + + @property + def shocker_id(self) -> UUID | None: + raw = _ext(self.problem, "shockerId") + try: + return UUID(raw) if raw else None + except (ValueError, TypeError, AttributeError): + return None + + +class ShockerNotFoundOrNoAccess(ShockerControlError, OpenShockNotFound): + """The shocker does not exist or is not shared with you.""" + + +class ShockerPaused(ShockerControlError): + """The shocker (or the share it is controlled through) is paused.""" + + +class ShockerNoPermission(ShockerControlError, OpenShockAuthError): + """You are not permitted to use this control type on the shocker.""" + + +class OpenShockConnectionError(OpenShockError): + """A realtime connection could not be established or was lost for good.""" + + +class HubInvocationError(OpenShockError): + """The SignalR hub reported an error for a method invocation.""" + + +def _ext(problem: ProblemDetails | None, key: str) -> Any: + if problem is None: + return None + for k, v in problem.extensions.items(): + if k.lower() == key.lower(): + return v + return None + + +#: Problem ``type`` -> exception class. Anything not listed falls back to the HTTP status. +PROBLEM_TYPES: dict[str, type[OpenShockApiError]] = { + "Shocker.Control.NotFound": ShockerNotFoundOrNoAccess, + "Shocker.Control.Paused": ShockerPaused, + "Shocker.Control.NoPermission": ShockerNoPermission, + "Device.NotFound": HubNotFound, + "Device.NotOnline": HubOffline, + "Websocket.LiveControl.HubNotFound": HubNotFound, + "Websocket.LiveControl.HubNotConnected": HubOffline, + "Authorization.Token.PermissionMissing": TokenPermissionMissing, + "ApiToken.Paused": ApiTokenPaused, +} + + +def error_from_response( + *, + status_code: int, + body_text: str, + body_json: Any = None, + method: str = "", + url: str = "", + retry_after: float | None = None, +) -> OpenShockApiError: + """Build the most specific exception for a non-2xx response.""" + problem: ProblemDetails | None = None + text: str | None = None + if isinstance(body_json, dict): + if "type" in body_json or "title" in body_json: + problem = ProblemDetails.from_dict(body_json, status=status_code) + text = body_json.get("message") or body_json.get("detail") or body_json.get("title") + text = text or body_text or f"HTTP {status_code}" + + where = f" calling {method} {url}" if method or url else "" + message = f"{status_code}{where}: {text}" + kwargs: dict[str, Any] = {"status_code": status_code, "problem": problem, "body": body_text} + + cls = PROBLEM_TYPES.get(problem.type) if problem else None + if cls is None: + if status_code in (401, 403): + cls = OpenShockAuthError + elif status_code == 404: + cls = OpenShockNotFound + elif status_code == 429: + return OpenShockRateLimited(message, retry_after=retry_after, **kwargs) + else: + cls = OpenShockApiError + return cls(message, **kwargs) diff --git a/openshock/models/__init__.py b/openshock/models/__init__.py index ab6e93d..12ea682 100644 --- a/openshock/models/__init__.py +++ b/openshock/models/__init__.py @@ -1,24 +1,29 @@ +from .account import CreatedToken as CreatedToken from .account import Token as Token from .account import User as User +from .common import BasicUserInfo as BasicUserInfo from .common import ControlType as ControlType +from .common import OtaUpdateStatus as OtaUpdateStatus from .common import PauseReason as PauseReason from .common import PermissionType as PermissionType from .common import RoleType as RoleType from .common import ShockerModelType as ShockerModelType +from .common import WireEnum as WireEnum from .common import parse_dt as parse_dt from .common import parse_uuid as parse_uuid from .device import Device as Device from .device import DeviceSelf as DeviceSelf +from .device import DeviceWithShockers as DeviceWithShockers from .device import DeviceWithToken as DeviceWithToken +from .device import HubGateway as HubGateway from .device import LcgInfo as LcgInfo from .device import LcgNode as LcgNode from .device import LcgNodeV2 as LcgNodeV2 from .device import OtaUpdate as OtaUpdate -from .device import PairCode as PairCode from .meta import BackendInfo as BackendInfo from .meta import Stats as Stats from .session import Session as Session -from .share import BasicUserInfo as BasicUserInfo +from .share import BulkPauseResult as BulkPauseResult from .share import OwnPublicShare as OwnPublicShare from .share import PublicShare as PublicShare from .share import PublicShareDevice as PublicShareDevice @@ -32,8 +37,12 @@ from .shocker import ControlLogSender as ControlLogSender from .shocker import MinimalShocker as MinimalShocker from .shocker import ShareCode as ShareCode +from .shocker import SharedDevice as SharedDevice +from .shocker import SharedShocker as SharedShocker from .shocker import ShareInfo as ShareInfo from .shocker import Shocker as Shocker from .shocker import ShockerLimits as ShockerLimits from .shocker import ShockerLog as ShockerLog +from .shocker import ShockerLogWithHub as ShockerLogWithHub +from .shocker import ShockerOwner as ShockerOwner from .shocker import ShockerPermissions as ShockerPermissions diff --git a/openshock/models/account.py b/openshock/models/account.py index 3ff30e5..cca688c 100644 --- a/openshock/models/account.py +++ b/openshock/models/account.py @@ -1,4 +1,3 @@ -# openshock/models/account.py from __future__ import annotations from dataclasses import dataclass @@ -16,7 +15,8 @@ class User: email: str image: str roles: list[RoleType] - rank: str + rank: str = "" + has_password: bool | None = None @classmethod def from_dict(cls, data: dict[str, Any]) -> User: @@ -25,8 +25,9 @@ def from_dict(cls, data: dict[str, Any]) -> User: name=data["name"], email=data["email"], image=data["image"], - roles=list(data.get("roles", [])), - rank=data["rank"], + roles=[RoleType(r) for r in data.get("roles") or []], + rank=data.get("rank") or "", + has_password=data.get("hasPassword"), ) @@ -47,5 +48,34 @@ def from_dict(cls, data: dict[str, Any]) -> Token: created_on=require_dt(data["createdOn"]), valid_until=parse_dt(data.get("validUntil")), last_used=parse_dt(data.get("lastUsed")), - permissions=list(data.get("permissions", [])), + permissions=[PermissionType(p) for p in data.get("permissions") or []], + ) + + +@dataclass +class CreatedToken: + """ + Response of ``account.create_token()``. + + ``token`` is the secret itself. It is only ever returned here, at creation time. + """ + + id: UUID + name: str + token: str + created_on: datetime + valid_until: datetime | None + last_used: datetime | None + permissions: list[PermissionType] + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> CreatedToken: + return cls( + id=require_uuid(data["id"]), + name=data["name"], + token=data["token"], + created_on=require_dt(data.get("createdAt") or data["createdOn"]), + valid_until=parse_dt(data.get("validUntil")), + last_used=parse_dt(data.get("lastUsed")), + permissions=[PermissionType(p) for p in data.get("permissions") or []], ) diff --git a/openshock/models/common.py b/openshock/models/common.py index 8f847f6..5a7ea53 100644 --- a/openshock/models/common.py +++ b/openshock/models/common.py @@ -1,16 +1,18 @@ from __future__ import annotations +from dataclasses import dataclass from datetime import datetime -from enum import IntFlag +from enum import Enum, IntFlag +from typing import Any, TypeVar from uuid import UUID +_E = TypeVar("_E", bound="WireEnum") + def parse_dt(value: str | None) -> datetime | None: if value is None: return None - # Handle "2023-01-01T00:00:00Z" style - value = value.replace("Z", "+00:00") - return datetime.fromisoformat(value) + return require_dt(value) def parse_uuid(value: str | None) -> UUID | None: @@ -20,8 +22,26 @@ def parse_uuid(value: str | None) -> UUID | None: def require_dt(value: str) -> datetime: - """Parse a required datetime string (never None).""" - return datetime.fromisoformat(value.replace("Z", "+00:00")) + """Parse a required ISO-8601 datetime string (never None).""" + value = value.replace("Z", "+00:00") + try: + return datetime.fromisoformat(value) + except ValueError: + # Python 3.10 only accepts 0, 3 or 6 fractional digits; .NET emits up to 7. + return datetime.fromisoformat(_normalize_fraction(value)) + + +def _normalize_fraction(value: str) -> str: + head, dot, rest = value.partition(".") + if not dot: + return value + digits = "" + for ch in rest: + if not ch.isdigit(): + break + digits += ch + tz = rest[len(digits) :] + return f"{head}.{digits[:6].ljust(6, '0')}{tz}" def require_uuid(value: str) -> UUID: @@ -29,11 +49,101 @@ def require_uuid(value: str) -> UUID: return UUID(value) -# A couple of simple enum-ish types as strings -ControlType = str # "Stop" | "Shock" | "Vibrate" | "Sound" -ShockerModelType = str # "CaiXianlin" | "PetTrainer" | "Petrainer998DR" -PermissionType = str # "shockers.use" | "shockers.edit" | ... -RoleType = str # "Support" | "Staff" | "Admin" | "System" +class WireEnum(str, Enum): + """ + String enum that mirrors a backend enum. + + - Members compare equal to their wire string (``ControlType.SHOCK == "Shock"``), + so plain strings keep working wherever an enum is accepted. + - Lookup is case-insensitive and also accepts the backend's integer value + (SignalR sends enums as integers, REST sends them as strings). + - Values this SDK version does not know about do not raise: they become a + pseudo-member carrying the raw value, with ``is_known`` set to ``False``. + This keeps older SDK versions working when the backend adds a value. + """ + + @classmethod + def _missing_(cls, value: object) -> WireEnum | None: + members = list(cls) + if isinstance(value, bool): + return None + if isinstance(value, int): + if 0 <= value < len(members): + return members[value] + return cls._unknown(str(value)) + if isinstance(value, str): + lowered = value.lower() + for member in members: + if member.value.lower() == lowered or member.name.lower() == lowered: + return member + if value.isdigit(): + return cls._missing_(int(value)) + return cls._unknown(value) + return None + + @classmethod + def _unknown(cls: type[_E], value: str) -> _E: + obj = str.__new__(cls, value) + obj._name_ = "UNKNOWN" + obj._value_ = value + return obj + + @property + def is_known(self) -> bool: + """False when the backend sent a value this SDK version has no member for.""" + return self._name_ != "UNKNOWN" + + def to_int(self) -> int: + """The backend's integer value for this member (used on the SignalR wire).""" + if not self.is_known: + raise ValueError(f"{type(self).__name__} value {self.value!r} is not known to this SDK version") + return list(type(self)).index(self) + + def __str__(self) -> str: + return str(self.value) + + +class ControlType(WireEnum): + STOP = "Stop" + SHOCK = "Shock" + VIBRATE = "Vibrate" + SOUND = "Sound" + + +class ShockerModelType(WireEnum): + CAIXIANLIN = "CaiXianlin" + PETTRAINER = "PetTrainer" + PETRAINER_998DR = "Petrainer998DR" + WELLTURN_T330 = "WellturnT330" + + +class PermissionType(WireEnum): + """API token permissions.""" + + SHOCKERS_USE = "shockers.use" + SHOCKERS_EDIT = "shockers.edit" + SHOCKERS_PAUSE = "shockers.pause" + DEVICES_EDIT = "devices.edit" + DEVICES_AUTH = "devices.auth" + USERSHARES_EDIT = "usershares.edit" + USERSHARES_PAUSE = "usershares.pause" + PUBLICSHARES_PAUSE = "publicshares.pause" + PUBLICSHARES_EDIT = "publicshares.edit" + + +class RoleType(WireEnum): + SUPPORT = "Support" + STAFF = "Staff" + ADMIN = "Admin" + SYSTEM = "System" + + +class OtaUpdateStatus(WireEnum): + STARTED = "Started" + RUNNING = "Running" + FINISHED = "Finished" + ERROR = "Error" + TIMEOUT = "Timeout" class PauseReason(IntFlag): @@ -43,3 +153,34 @@ class PauseReason(IntFlag): SHOCKER = 1 USER_SHARE = 2 PUBLIC_SHARE = 4 + + +def parse_pause_reason(value: Any) -> PauseReason: + """Parse a pause reason sent as an integer bitfield or as comma-separated flag names.""" + if value is None: + return PauseReason.NONE + if isinstance(value, int): + return PauseReason(value) + text = str(value).strip() + if text.lstrip("-").isdigit(): + return PauseReason(int(text)) + names = {"none": 0, "shocker": 1, "usershare": 2, "publicshare": 4} + result = PauseReason.NONE + for part in text.split(","): + result |= PauseReason(names.get(part.strip().lower().replace("_", ""), 0)) + return result + + +@dataclass +class BasicUserInfo: + id: UUID + name: str + image: str + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> BasicUserInfo: + return cls( + id=require_uuid(data["id"]), + name=data["name"], + image=data["image"], + ) diff --git a/openshock/models/device.py b/openshock/models/device.py index 7f62bd0..169b9c7 100644 --- a/openshock/models/device.py +++ b/openshock/models/device.py @@ -5,7 +5,8 @@ from typing import Any from uuid import UUID -from .common import require_dt, require_uuid +from .common import OtaUpdateStatus, require_dt, require_uuid +from .shocker import MinimalShocker, Shocker @dataclass @@ -24,34 +25,39 @@ def from_dict(cls, data: dict[str, Any]) -> Device: @dataclass -class DeviceWithToken: - """Response from creating a new device.""" +class DeviceWithShockers(Device): + """A hub together with its shockers, as returned by ``shockers.list_own()``.""" - id: UUID - name: str - created_on: datetime - token: str + shockers: list[Shocker] @classmethod - def from_dict(cls, data: dict[str, Any]) -> DeviceWithToken: + def from_dict(cls, data: dict[str, Any]) -> DeviceWithShockers: return cls( id=require_uuid(data["id"]), name=data["name"], created_on=require_dt(data["createdOn"]), - token=data["token"], + shockers=[Shocker.from_dict(s) for s in data.get("shockers") or []], ) @dataclass -class PairCode: - id: str - created_on: datetime +class DeviceWithToken(Device): + """ + A hub as returned by ``devices.get()``. + + ``token`` is the hub's device token. It is only present when authenticated with a + user session or an API token holding the ``devices.auth`` permission. + """ + + token: str | None = None @classmethod - def from_dict(cls, data: dict[str, Any]) -> PairCode: + def from_dict(cls, data: dict[str, Any]) -> DeviceWithToken: return cls( - id=data["id"], + id=require_uuid(data["id"]), + name=data["name"], created_on=require_dt(data["createdOn"]), + token=data.get("token"), ) @@ -104,11 +110,44 @@ def from_dict(cls, data: dict[str, Any]) -> LcgInfo: ) +@dataclass +class HubGateway: + """ + The live control gateway a hub is currently connected to (GET /2/devices/{id}/lcg). + """ + + host: str + port: int + #: Path prefix the gateway is served under, e.g. "/gateway" (empty for root). + path_prefix: str + country: str + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> HubGateway: + return cls( + host=data["host"], + port=int(data.get("port") or 443), + path_prefix=data.get("pathPrefix") or "", + country=data.get("country") or "", + ) + + @property + def display_url(self) -> str: + port = "" if self.port == 443 else f":{self.port}" + prefix = self.path_prefix.strip("/") + return f"{self.host}{port}{'/' + prefix if prefix else ''}" + + @property + def ws_url(self) -> str: + """Base WebSocket URL of the gateway, without a trailing slash.""" + return f"wss://{self.display_url}" + + @dataclass class OtaUpdate: id: int started_at: datetime - status: str + status: OtaUpdateStatus version: str message: str | None = None @@ -117,7 +156,7 @@ def from_dict(cls, data: dict[str, Any]) -> OtaUpdate: return cls( id=data["id"], started_at=require_dt(data["startedAt"]), - status=data["status"], + status=OtaUpdateStatus(data["status"]), version=data["version"], message=data.get("message"), ) @@ -129,12 +168,12 @@ class DeviceSelf: id: UUID name: str - shockers: list[Any] + shockers: list[MinimalShocker] @classmethod def from_dict(cls, data: dict[str, Any]) -> DeviceSelf: return cls( id=require_uuid(data["id"]), name=data["name"], - shockers=data.get("shockers", []), + shockers=[MinimalShocker.from_dict(s) for s in data.get("shockers") or []], ) diff --git a/openshock/models/session.py b/openshock/models/session.py index 7496296..ec6cfde 100644 --- a/openshock/models/session.py +++ b/openshock/models/session.py @@ -16,6 +16,10 @@ class Session: created: datetime expires: datetime last_used: datetime | None = None + asn_org: str | None = None + is_vpn: bool | None = None + country_code: str | None = None + city: str | None = None @classmethod def from_dict(cls, data: dict[str, Any]) -> Session: @@ -26,4 +30,8 @@ def from_dict(cls, data: dict[str, Any]) -> Session: created=require_dt(data["created"]), expires=require_dt(data["expires"]), last_used=parse_dt(data.get("lastUsed")), + asn_org=data.get("asnOrg"), + is_vpn=data.get("isVpn"), + country_code=data.get("countryCode"), + city=data.get("city"), ) diff --git a/openshock/models/share.py b/openshock/models/share.py index 53a5e7f..b002702 100644 --- a/openshock/models/share.py +++ b/openshock/models/share.py @@ -5,25 +5,10 @@ from typing import Any from uuid import UUID -from .common import PauseReason, parse_dt, parse_uuid, require_dt, require_uuid +from .common import BasicUserInfo, PauseReason, parse_dt, parse_pause_reason, parse_uuid, require_dt, require_uuid from .shocker import ShockerLimits, ShockerPermissions -@dataclass -class BasicUserInfo: - id: UUID - name: str - image: str - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> BasicUserInfo: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - image=data["image"], - ) - - @dataclass class PublicShareShocker: id: UUID @@ -39,7 +24,7 @@ def from_dict(cls, data: dict[str, Any]) -> PublicShareShocker: name=data["name"], permissions=ShockerPermissions.from_dict(data["permissions"]), limits=ShockerLimits.from_dict(data["limits"]), - paused=PauseReason(data.get("paused", 0)), + paused=parse_pause_reason(data.get("paused")), ) @@ -115,7 +100,7 @@ def from_dict(cls, data: dict[str, Any]) -> UserShareInfo: created_on=require_dt(data["createdOn"]), permissions=ShockerPermissions.from_dict(data["permissions"]), limits=ShockerLimits.from_dict(data["limits"]), - paused=PauseReason(data.get("paused", 0)), + paused=parse_pause_reason(data.get("paused")), ) @@ -196,3 +181,19 @@ def from_dict(cls, data: dict[str, Any]) -> ShareInvite: shared_with=BasicUserInfo.from_dict(data["sharedWith"]), shockers=[ShareInviteShocker.from_dict(s) for s in data.get("shockers", [])], ) + + +@dataclass +class BulkPauseResult: + """Response of ``user_shares.bulk_pause_shockers()``.""" + + affected_records: int + #: Resulting pause reasons per shocker ID. + pause_states: dict[UUID, PauseReason] + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> BulkPauseResult: + return cls( + affected_records=int(data.get("affectedRecords", 0)), + pause_states={require_uuid(k): parse_pause_reason(v) for k, v in (data.get("pauseStates") or {}).items()}, + ) diff --git a/openshock/models/shocker.py b/openshock/models/shocker.py index 7ba5429..1e2f678 100644 --- a/openshock/models/shocker.py +++ b/openshock/models/shocker.py @@ -5,7 +5,7 @@ from typing import Any from uuid import UUID -from .common import ControlType, ShockerModelType, require_dt, require_uuid +from .common import BasicUserInfo, ControlType, ShockerModelType, require_dt, require_uuid @dataclass @@ -60,16 +60,26 @@ class Shocker: model: ShockerModelType created_on: datetime is_paused: bool = False + permissions: ShockerPermissions | None = None + limits: ShockerLimits | None = None + #: ID of the hub this shocker belongs to. Only set by ``shockers.get()``. + device: UUID | None = None @classmethod def from_dict(cls, data: dict[str, Any]) -> Shocker: + permissions = data.get("permissions") + limits = data.get("limits") + device = data.get("device") return cls( id=require_uuid(data["id"]), name=data["name"], rf_id=data["rfId"], - model=data["model"], + model=ShockerModelType(data["model"]), created_on=require_dt(data["createdOn"]), is_paused=data.get("isPaused", False), + permissions=ShockerPermissions.from_dict(permissions) if permissions else None, + limits=ShockerLimits.from_dict(limits) if limits else None, + device=require_uuid(device) if device else None, ) @@ -84,7 +94,64 @@ def from_dict(cls, data: dict[str, Any]) -> MinimalShocker: return cls( id=require_uuid(data["id"]), rf_id=data["rfId"], - model=data["model"], + model=ShockerModelType(data["model"]), + ) + + +@dataclass +class SharedShocker: + """A shocker somebody else shared with you.""" + + id: UUID + name: str + is_paused: bool + permissions: ShockerPermissions + limits: ShockerLimits + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> SharedShocker: + return cls( + id=require_uuid(data["id"]), + name=data["name"], + is_paused=data.get("isPaused", False), + permissions=ShockerPermissions.from_dict(data["permissions"]), + limits=ShockerLimits.from_dict(data["limits"]), + ) + + +@dataclass +class SharedDevice: + """A hub of another user, holding the shockers they shared with you.""" + + id: UUID + name: str + shockers: list[SharedShocker] + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> SharedDevice: + return cls( + id=require_uuid(data["id"]), + name=data["name"], + shockers=[SharedShocker.from_dict(s) for s in data.get("shockers") or []], + ) + + +@dataclass +class ShockerOwner: + """An entry of ``shockers.list_shared()``: a user and what they shared with you.""" + + id: UUID + name: str + image: str + devices: list[SharedDevice] + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ShockerOwner: + return cls( + id=require_uuid(data["id"]), + name=data["name"], + image=data["image"], + devices=[SharedDevice.from_dict(d) for d in data.get("devices") or []], ) @@ -113,42 +180,84 @@ class ShockerLog: controlled_by: ControlLogSender intensity: int duration: int + live_control: bool = False @classmethod def from_dict(cls, data: dict[str, Any]) -> ShockerLog: return cls( id=require_uuid(data["id"]), created_on=require_dt(data["createdOn"]), - type=data["type"], + type=ControlType(data["type"]), controlled_by=ControlLogSender.from_dict(data["controlledBy"]), intensity=data["intensity"], duration=data["duration"], + live_control=data.get("liveControl", False), + ) + + +@dataclass +class ShockerLogWithHub(ShockerLog): + """A log entry of ``shockers.all_logs()``, which spans every owned shocker.""" + + hub_id: UUID | None = None + hub_name: str = "" + shocker_id: UUID | None = None + shocker_name: str = "" + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ShockerLogWithHub: + hub_id = data.get("hubId") + shocker_id = data.get("shockerId") + return cls( + id=require_uuid(data["id"]), + created_on=require_dt(data["createdOn"]), + type=ControlType(data["type"]), + controlled_by=ControlLogSender.from_dict(data["controlledBy"]), + intensity=data["intensity"], + duration=data["duration"], + live_control=data.get("liveControl", False), + hub_id=require_uuid(hub_id) if hub_id else None, + hub_name=data.get("hubName") or "", + shocker_id=require_uuid(shocker_id) if shocker_id else None, + shocker_name=data.get("shockerName") or "", ) @dataclass class Control: - """A single control command for POST /2/shockers/control.""" + """ + A single control command. + + ``intensity`` is 0-100, ``duration`` is in milliseconds. ``exclusive`` makes this + command take precedence over live control for its duration. + """ id: str | UUID - type: ControlType + type: ControlType | str intensity: int duration: int exclusive: bool = False def to_dict(self) -> dict[str, Any]: + """REST wire form (control type as string).""" return { "id": str(self.id), - "type": self.type, + "type": ControlType(self.type).value, "intensity": self.intensity, "duration": self.duration, "exclusive": self.exclusive, } + def to_signalr(self) -> dict[str, Any]: + """SignalR wire form (control type as integer).""" + d = self.to_dict() + d["type"] = ControlType(self.type).to_int() + return d + @dataclass class ShareInfo: - shared_with: dict[str, Any] # BasicUserInfo + shared_with: BasicUserInfo created_on: datetime permissions: ShockerPermissions limits: ShockerLimits @@ -157,7 +266,7 @@ class ShareInfo: @classmethod def from_dict(cls, data: dict[str, Any]) -> ShareInfo: return cls( - shared_with=data["sharedWith"], + shared_with=BasicUserInfo.from_dict(data["sharedWith"]), created_on=require_dt(data["createdOn"]), permissions=ShockerPermissions.from_dict(data["permissions"]), limits=ShockerLimits.from_dict(data["limits"]), diff --git a/openshock/realtime/__init__.py b/openshock/realtime/__init__.py new file mode 100644 index 0000000..6630b91 --- /dev/null +++ b/openshock/realtime/__init__.py @@ -0,0 +1,31 @@ +""" +Realtime clients for OpenShock: the SignalR user hub and live control. + +These need the optional ``websockets`` dependency:: + + pip install "openshock[realtime]" +""" + +try: + import websockets as _websockets # noqa: F401 +except ModuleNotFoundError as exc: # pragma: no cover + raise ModuleNotFoundError( + 'openshock.realtime needs the "websockets" package. Install it with: pip install "openshock[realtime]"' + ) from exc + +from ._events import Event as Event +from ._signalr import SignalRConnection as SignalRConnection +from ._transport import ConnectionState as ConnectionState +from ._transport import RetryPolicy as RetryPolicy +from ._transport import StepRetryPolicy as StepRetryPolicy +from .live_control import LiveControlClient as LiveControlClient +from .live_control import LiveControlRetryPolicy as LiveControlRetryPolicy +from .models import BasicShockerInfo as BasicShockerInfo +from .models import ControlLog as ControlLog +from .models import HubControlLogSender as HubControlLogSender +from .models import HubOnlineState as HubOnlineState +from .models import HubUpdateType as HubUpdateType +from .models import LiveResponseType as LiveResponseType +from .models import OtaUpdateProgressTask as OtaUpdateProgressTask +from .user_hub import USER_HUB_RETRY_POLICY as USER_HUB_RETRY_POLICY +from .user_hub import UserHubClient as UserHubClient diff --git a/openshock/realtime/_events.py b/openshock/realtime/_events.py new file mode 100644 index 0000000..6720ffe --- /dev/null +++ b/openshock/realtime/_events.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import asyncio +import contextlib +import inspect +import logging +from collections.abc import Callable +from typing import Generic, ParamSpec, TypeVar + +P = ParamSpec("P") +F = TypeVar("F", bound=Callable[..., object]) + +logger = logging.getLogger("openshock.realtime") + + +class Event(Generic[P]): + """ + A subscribable event. Handlers may be plain functions or coroutine functions. + + Subscribe with the decorator form or with :meth:`subscribe`:: + + @hub.on_log + async def handle(sender, logs): ... + + unsubscribe = hub.on_log.subscribe(handle) + unsubscribe() + + An exception raised by a handler is logged and does not affect other handlers + or the connection. + """ + + def __init__(self, name: str = "event") -> None: + self.name = name + self._handlers: list[Callable[P, object]] = [] + + def subscribe(self, handler: Callable[P, object]) -> Callable[[], None]: + """Add a handler. Returns a function that removes it again.""" + self._handlers.append(handler) + + def unsubscribe() -> None: + self.unsubscribe(handler) + + return unsubscribe + + def unsubscribe(self, handler: Callable[P, object]) -> None: + with contextlib.suppress(ValueError): + self._handlers.remove(handler) + + def __call__(self, handler: F) -> F: + """Decorator form of :meth:`subscribe`.""" + self._handlers.append(handler) + return handler + + def __len__(self) -> int: + return len(self._handlers) + + async def emit(self, *args: P.args, **kwargs: P.kwargs) -> None: + for handler in list(self._handlers): + try: + result = handler(*args, **kwargs) + if inspect.isawaitable(result): + await result + except asyncio.CancelledError: + raise + except Exception: + logger.exception("Unhandled exception in %s handler %r", self.name, handler) diff --git a/openshock/realtime/_signalr.py b/openshock/realtime/_signalr.py new file mode 100644 index 0000000..110ae4a --- /dev/null +++ b/openshock/realtime/_signalr.py @@ -0,0 +1,192 @@ +""" +Minimal SignalR client: JSON hub protocol over WebSockets with negotiation skipped. + +Covers what the OpenShock hubs need: server-to-client invocations, client-to-server +invocations with and without completion, keep-alive pings and the close message. +Streaming and the MessagePack protocol are not implemented. +""" + +from __future__ import annotations + +import asyncio +import itertools +import json +import logging +from collections.abc import Callable, Mapping +from typing import Any + +from websockets.asyncio.client import ClientConnection + +from ..exceptions import HubInvocationError, OpenShockConnectionError +from ._events import Event +from ._transport import RetryPolicy, WebSocketSession, _ServerClose + +RECORD_SEPARATOR = "\x1e" + +_INVOCATION = 1 +_STREAM_ITEM = 2 +_COMPLETION = 3 +_PING = 6 +_CLOSE = 7 + +#: How often we ping. The server drops clients it has not heard from for 30 seconds. +KEEP_ALIVE_INTERVAL = 15.0 +HANDSHAKE_TIMEOUT = 15.0 + + +def encode(message: Mapping[str, Any]) -> str: + return json.dumps(message, separators=(",", ":")) + RECORD_SEPARATOR + + +def decode(data: str) -> list[dict[str, Any]]: + return [json.loads(part) for part in data.split(RECORD_SEPARATOR) if part] + + +class SignalRConnection(WebSocketSession): + _name = "signalr" + + def __init__( + self, + url: str, + *, + headers: Mapping[str, str], + user_agent: str, + retry_policy: RetryPolicy, + logger: logging.Logger | None = None, + ) -> None: + super().__init__(retry_policy=retry_policy, logger=logger) + self._url = url + self._headers = dict(headers) + self._user_agent = user_agent + self._targets: dict[str, Callable[[list[Any]], None]] = {} + self._raw_events: dict[str, Event[...]] = {} + self._pending: dict[str, asyncio.Future[Any]] = {} + self._ids = itertools.count(1) + self._keep_alive: asyncio.Task[None] | None = None + self._backlog: list[dict[str, Any]] = [] + + # --- public API -------------------------------------------------------- + + def on(self, target: str, handler: Callable[..., object] | None = None) -> Any: + """ + Subscribe to a server-to-client method by name. The handler receives the + invocation's arguments positionally, as decoded JSON. + + Use this for hub methods this SDK version has no typed event for. Works as a + decorator (``@hub.on("Method")``) or as a plain call returning an unsubscribe + function (``hub.on("Method", handler)``). + """ + event = self._raw_events.setdefault(target.lower(), Event(target)) + if handler is None: + return event + return event.subscribe(handler) + + async def send(self, target: str, *args: Any) -> None: + """Invoke a hub method without waiting for the server to finish it.""" + await self._send_text(encode({"type": _INVOCATION, "target": target, "arguments": list(args)})) + + async def invoke(self, target: str, *args: Any, timeout: float | None = 30.0) -> Any: + """ + Invoke a hub method and wait for its completion. Returns the method's result. + + Raises :class:`~openshock.exceptions.HubInvocationError` if the hub reports an + error and :class:`~openshock.exceptions.OpenShockConnectionError` if the + connection is lost before the completion arrives. + """ + invocation_id = str(next(self._ids)) + future: asyncio.Future[Any] = asyncio.get_running_loop().create_future() + self._pending[invocation_id] = future + try: + await self._send_text( + encode({"type": _INVOCATION, "invocationId": invocation_id, "target": target, "arguments": list(args)}) + ) + return await asyncio.wait_for(future, timeout) + finally: + self._pending.pop(invocation_id, None) + + # --- session hooks ----------------------------------------------------- + + def _register(self, target: str, callback: Callable[[list[Any]], None]) -> None: + """Internal typed handler for a server-to-client method.""" + self._targets[target.lower()] = callback + + async def _open(self) -> ClientConnection: + ws = await self._connect(self._url, self._headers, self._user_agent) + try: + await ws.send(encode({"protocol": "json", "version": 1})) + raw = await asyncio.wait_for(ws.recv(), HANDSHAKE_TIMEOUT) + text = raw if isinstance(raw, str) else raw.decode("utf-8") + messages = decode(text) + if not messages: + raise OpenShockConnectionError("Empty SignalR handshake response") + error = messages[0].get("error") + if error: + raise OpenShockConnectionError(f"SignalR handshake failed: {error}") + # Anything after the handshake response in the same frame is regular traffic. + self._backlog = messages[1:] + return ws + except BaseException: + await self._close_ws(ws) + raise + + async def _after_open(self) -> None: + self._keep_alive = asyncio.create_task(self._keep_alive_loop(), name="openshock-signalr-keepalive") + backlog, self._backlog = self._backlog, [] + for message in backlog: + self._handle_message(message) + + async def _after_close(self, error: BaseException | None) -> None: + task, self._keep_alive = self._keep_alive, None + if task is not None: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for future in self._pending.values(): + if not future.done(): + future.set_exception(OpenShockConnectionError("The connection was lost before the hub answered")) + self._pending.clear() + + async def _handle(self, message: str) -> None: + for decoded in decode(message): + self._handle_message(decoded) + + # --- internals --------------------------------------------------------- + + def _handle_message(self, message: dict[str, Any]) -> None: + kind = message.get("type") + if kind == _INVOCATION: + target = str(message.get("target", "")) + arguments = list(message.get("arguments") or []) + callback = self._targets.get(target.lower()) + if callback is not None: + try: + callback(arguments) + except Exception: + self._log.exception("Could not parse arguments of %s: %.200r", target, arguments) + raw = self._raw_events.get(target.lower()) + if raw is not None: + self._emit(raw.emit, *arguments) + if callback is None and raw is None: + self._log.debug("No handler for hub method %s", target) + elif kind == _COMPLETION: + future = self._pending.get(str(message.get("invocationId"))) + if future is None or future.done(): + return + if message.get("error"): + future.set_exception(HubInvocationError(str(message["error"]))) + else: + future.set_result(message.get("result")) + elif kind == _CLOSE: + raise _ServerClose(message.get("error"), bool(message.get("allowReconnect", False))) + elif kind in (_PING, _STREAM_ITEM): + return + else: + self._log.debug("Ignoring SignalR message of type %r", kind) + + async def _keep_alive_loop(self) -> None: + ping = encode({"type": _PING}) + while True: + await asyncio.sleep(KEEP_ALIVE_INTERVAL) + try: + await self._send_text(ping) + except OpenShockConnectionError: + return diff --git a/openshock/realtime/_transport.py b/openshock/realtime/_transport.py new file mode 100644 index 0000000..a4f811e --- /dev/null +++ b/openshock/realtime/_transport.py @@ -0,0 +1,416 @@ +"""A WebSocket session that keeps itself connected. Shared by the realtime clients.""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import logging +from collections.abc import Awaitable, Callable, Mapping, Sequence +from enum import Enum +from importlib.metadata import version as _package_version +from types import TracebackType +from typing import Any, Protocol, TypeVar + +import httpx +from websockets.asyncio.client import ClientConnection, connect +from websockets.exceptions import ConnectionClosed, InvalidMessage, InvalidStatus + +from ..exceptions import ( + HubNotFound, + OpenShockApiError, + OpenShockAuthError, + OpenShockConnectionError, + OpenShockNotFound, + error_from_response, +) +from ._events import Event + +_SelfT = TypeVar("_SelfT", bound="WebSocketSession") + +WEBSOCKETS_VERSION: str = _package_version("websockets") + + +class ConnectionState(str, Enum): + DISCONNECTED = "Disconnected" + CONNECTING = "Connecting" + CONNECTED = "Connected" + RECONNECTING = "Reconnecting" + + def __str__(self) -> str: + return str(self.value) + + +class RetryPolicy(Protocol): + """Decides how long to wait before a reconnect attempt.""" + + def next_delay(self, attempt: int) -> float | None: + """ + ``attempt`` is the number of consecutive failed attempts so far (0 for the first + retry after a connection loss). Return the delay in seconds, or ``None`` to give up. + """ + ... + + +class StepRetryPolicy: + """ + Walks through ``steps`` (seconds) and then keeps using the last one forever, + or gives up after ``max_attempts`` consecutive failures if that is set. + """ + + def __init__(self, steps: Sequence[float], *, max_attempts: int | None = None) -> None: + if not steps: + raise ValueError("steps must not be empty") + self.steps = tuple(steps) + self.max_attempts = max_attempts + + def next_delay(self, attempt: int) -> float | None: + if self.max_attempts is not None and attempt >= self.max_attempts: + return None + return self.steps[min(attempt, len(self.steps) - 1)] + + +class _ServerClose(Exception): + """The server asked us to close the connection at protocol level.""" + + def __init__(self, error: str | None, allow_reconnect: bool) -> None: + super().__init__(error or "Connection closed by server") + self.error = error + self.allow_reconnect = allow_reconnect + + +_SENTINEL: Any = object() + + +def _rejection(status_code: int, text: str, url: str) -> OpenShockApiError: + try: + body_json: Any = json.loads(text) if text else None + except ValueError: + body_json = None + return error_from_response(status_code=status_code, body_text=text, body_json=body_json, method="GET", url=url) + + +async def _probe_rejection(url: str, headers: Mapping[str, str], user_agent: str) -> OpenShockApiError | None: + """ + Repeat a failed WebSocket upgrade as a plain GET to learn why it was refused. + Returns an error only for answers that are meaningful without the upgrade. + """ + http_url = "http" + url[2:] if url.startswith(("ws://", "wss://")) else url + try: + async with httpx.AsyncClient(timeout=10) as client: + resp = await client.get(http_url, headers={**headers, "User-Agent": user_agent}) + except httpx.HTTPError: + return None + error = _rejection(resp.status_code, resp.text, url) + if resp.status_code in (401, 403) or type(error) not in (OpenShockApiError, OpenShockNotFound): + return error + return None + + +class WebSocketSession: + """ + Base class of the realtime clients: owns the socket, the receive loop, reconnection + and ordered event dispatch. Not meant to be used directly. + + Lifecycle events (available on every realtime client): + + - ``on_connected()`` — the first connection was established + - ``on_reconnecting(error)`` — the connection was lost, reconnecting + - ``on_reconnected()`` — a reconnect succeeded + - ``on_closed(error)`` — the session ended; ``error`` is ``None`` after :meth:`stop` + """ + + #: Keep retrying when the very first connection attempt fails with a non-fatal error. + _retry_initial = False + _name = "websocket" + + def __init__(self, *, retry_policy: RetryPolicy, logger: logging.Logger | None = None) -> None: + self._retry_policy = retry_policy + self._log = logger or logging.getLogger(f"openshock.realtime.{self._name}") + + self.on_connected: Event[[]] = Event("on_connected") + self.on_reconnecting: Event[[BaseException | None]] = Event("on_reconnecting") + self.on_reconnected: Event[[]] = Event("on_reconnected") + self.on_closed: Event[[BaseException | None]] = Event("on_closed") + + self._state = ConnectionState.DISCONNECTED + self._ws: ClientConnection | None = None + self._runner: asyncio.Task[None] | None = None + self._dispatcher: asyncio.Task[None] | None = None + self._queue: asyncio.Queue[Any] = asyncio.Queue() + self._connected = asyncio.Event() + self._closed = asyncio.Event() + self._closed.set() + self._close_error: BaseException | None = None + self._finalized = True + + # --- public API -------------------------------------------------------- + + @property + def state(self) -> ConnectionState: + return self._state + + @property + def is_connected(self) -> bool: + return self._state is ConnectionState.CONNECTED + + async def start(self) -> None: + """ + Open the connection and start processing messages in the background. + + Raises :class:`~openshock.exceptions.OpenShockAuthError` (or another + :class:`~openshock.exceptions.OpenShockError`) if the connection is refused. + """ + if self._runner is not None and not self._runner.done(): + raise RuntimeError(f"{type(self).__name__} is already started") + + self._queue = asyncio.Queue() + self._closed.clear() + self._close_error = None + self._state = ConnectionState.CONNECTING + + ws: ClientConnection | None = None + error: BaseException | None = None + try: + ws = await self._open() + except asyncio.CancelledError: + self._state = ConnectionState.DISCONNECTED + self._closed.set() + raise + except Exception as exc: + if not self._retry_initial or self._is_fatal(exc): + self._state = ConnectionState.DISCONNECTED + self._closed.set() + if isinstance(exc, OpenShockApiError | OpenShockConnectionError): + raise + raise OpenShockConnectionError(f"Could not connect: {exc}") from exc + self._log.info("Initial connection failed (%s), retrying in the background", exc) + error = exc + + self._finalized = False + if ws is not None: + # Be usable as soon as start() returns, before the background task first runs. + self._mark_connected(ws) + self._dispatcher = asyncio.create_task(self._dispatch_loop(), name=f"openshock-{self._name}-dispatch") + self._runner = asyncio.create_task(self._run(ws, error), name=f"openshock-{self._name}") + + async def stop(self) -> None: + """Close the connection and stop reconnecting. Safe to call more than once.""" + runner, self._runner = self._runner, None + if runner is not None: + runner.cancel() + await asyncio.gather(runner, return_exceptions=True) + # A task cancelled before it first ran never reaches its own cleanup. + await self._finalize(None) + dispatcher, self._dispatcher = self._dispatcher, None + if dispatcher is not None and dispatcher is not asyncio.current_task(): + await asyncio.gather(dispatcher, return_exceptions=True) + + async def wait_connected(self, timeout: float | None = None) -> None: + """Wait until the connection is established. Raises if the session closes first.""" + connected = asyncio.ensure_future(self._connected.wait()) + closed = asyncio.ensure_future(self._closed.wait()) + try: + done, _ = await asyncio.wait({connected, closed}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED) + finally: + connected.cancel() + closed.cancel() + if self._connected.is_set(): + return + if not done: + raise asyncio.TimeoutError() + raise self._close_error or OpenShockConnectionError("The connection was closed") + + async def wait_closed(self) -> None: + """ + Block until the session ends. Returns normally after :meth:`stop`; raises the + error if the session ended because of one (e.g. the token was revoked). + """ + await self._closed.wait() + if self._close_error is not None: + raise self._close_error + + async def __aenter__(self: _SelfT) -> _SelfT: + await self.start() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + await self.stop() + + # --- hooks for subclasses ---------------------------------------------- + + async def _open(self) -> ClientConnection: + """Establish one connection, including any protocol handshake.""" + raise NotImplementedError + + async def _handle(self, message: str) -> None: + """Process one incoming text message.""" + raise NotImplementedError + + async def _after_open(self) -> None: + """Called once a connection is established, before messages are pumped.""" + + async def _after_close(self, error: BaseException | None) -> None: + """Called after a connection ended, before any reconnect.""" + + def _is_fatal(self, exc: BaseException) -> bool: + """Errors for which retrying is pointless.""" + return isinstance(exc, OpenShockAuthError | HubNotFound) + + # --- helpers for subclasses -------------------------------------------- + + async def _connect(self, url: str, headers: Mapping[str, str], user_agent: str) -> ClientConnection: + """Open the socket, translating an HTTP rejection into an ``OpenShockApiError``.""" + try: + return await connect( + url, + additional_headers=dict(headers), + user_agent_header=user_agent, + open_timeout=15, + ping_interval=20, + ping_timeout=20, + max_size=4 * 1024 * 1024, + ) + except InvalidStatus as exc: + body = exc.response.body or b"" + raise _rejection(exc.response.status_code, body.decode("utf-8", errors="replace"), url) from exc + except (InvalidMessage, EOFError, ConnectionError) as exc: + if isinstance(exc, ConnectionRefusedError): + raise + # Behind some proxies a refused upgrade arrives as a response the WebSocket client + # cannot parse, which hides the status code. Ask again over plain HTTP so a bad + # token is reported as such instead of looking like a network problem. + rejection = await _probe_rejection(url, headers, user_agent) + if rejection is not None: + raise rejection from exc + raise + + async def _send_text(self, text: str) -> None: + ws = self._ws + if ws is None: + raise OpenShockConnectionError(f"{type(self).__name__} is not connected") + try: + await ws.send(text) + except ConnectionClosed as exc: + raise OpenShockConnectionError("The connection was lost while sending") from exc + + def _emit(self, event: Callable[..., Awaitable[None]], *args: Any) -> None: + """Queue an event emission. Events are delivered in order, off the receive loop.""" + self._queue.put_nowait((event, args)) + + # --- internals --------------------------------------------------------- + + async def _dispatch_loop(self) -> None: + while True: + item = await self._queue.get() + if item is _SENTINEL: + return + emit, args = item + try: + await emit(*args) + except asyncio.CancelledError: + raise + except Exception: + self._log.exception("Unhandled exception while dispatching an event") + + def _mark_connected(self, ws: ClientConnection) -> None: + self._ws = ws + self._state = ConnectionState.CONNECTED + self._connected.set() + + async def _run(self, ws: ClientConnection | None, error: BaseException | None) -> None: + ever_connected = False + final: BaseException | None = None + try: + while True: + if ws is None: + self._state = ConnectionState.RECONNECTING + self._emit(self.on_reconnecting.emit, error) + ws = await self._reconnect() + self._mark_connected(ws) + + try: + await self._after_open() + self._emit(self.on_reconnected.emit if ever_connected else self.on_connected.emit) + ever_connected = True + error = await self._pump(ws) + finally: + self._ws = None + self._connected.clear() + await asyncio.shield(self._close_ws(ws)) + await self._after_close(error) + if isinstance(error, _ServerClose) and not error.allow_reconnect: + raise OpenShockConnectionError(f"The server closed the connection: {error}") + self._log.info("Connection lost (%s), reconnecting", error or "closed") + ws = None + except asyncio.CancelledError: + final = None + except Exception as exc: + final = exc + self._log.error("Session ended: %s", exc) + finally: + await self._finalize(final) + + async def _finalize(self, final: BaseException | None) -> None: + """End the session: release the socket, notify ``on_closed``, stop the dispatcher. Runs once.""" + if self._finalized: + return + self._finalized = True + ws, self._ws = self._ws, None + self._connected.clear() + self._state = ConnectionState.DISCONNECTED + self._close_error = final + try: + if ws is not None: + await self._close_ws(ws) + await self._after_close(final) + except Exception: + self._log.exception("Error during cleanup") + self._emit(self.on_closed.emit, final) + self._queue.put_nowait(_SENTINEL) + self._closed.set() + + async def _reconnect(self) -> ClientConnection: + attempt = 0 + while True: + delay = self._retry_policy.next_delay(attempt) + if delay is None: + raise OpenShockConnectionError(f"Giving up reconnecting after {attempt} attempts") + if delay > 0: + await asyncio.sleep(delay) + attempt += 1 + try: + return await self._open() + except asyncio.CancelledError: + raise + except Exception as exc: + if self._is_fatal(exc): + raise + self._log.debug("Reconnect attempt %d failed: %s", attempt, exc) + + async def _pump(self, ws: ClientConnection) -> BaseException | None: + """Receive until the connection ends. Returns what ended it.""" + try: + async for message in ws: + text = message if isinstance(message, str) else message.decode("utf-8", errors="replace") + try: + await self._handle(text) + except _ServerClose as exc: + return exc + except asyncio.CancelledError: + raise + except Exception: + self._log.exception("Failed to handle message: %.200s", text) + except ConnectionClosed as exc: + return exc + return None + + @staticmethod + async def _close_ws(ws: ClientConnection) -> None: + with contextlib.suppress(Exception): + await asyncio.wait_for(ws.close(), timeout=5) diff --git a/openshock/realtime/live_control.py b/openshock/realtime/live_control.py new file mode 100644 index 0000000..5eb321f --- /dev/null +++ b/openshock/realtime/live_control.py @@ -0,0 +1,350 @@ +from __future__ import annotations + +import asyncio +import json +import logging +from collections.abc import Awaitable, Callable, Mapping +from dataclasses import dataclass +from typing import Any +from uuid import UUID + +from websockets.asyncio.client import ClientConnection + +from .._async.client import AsyncOpenShockClient +from .._core import DEFAULT_BASE_URL, build_user_agent +from ..auth import ApiTokenAuth +from ..models import ControlType, HubGateway +from ._events import Event +from ._transport import WEBSOCKETS_VERSION, RetryPolicy, WebSocketSession +from .models import LiveResponseType, _get + +#: Ticks per second assumed until the gateway announces the real value. +DEFAULT_TPS = 10 +#: A frame given to ``intake_frame`` stays active for this many ticks. +FRAME_HOLD_TICKS = 2.5 + +GatewayResolver = Callable[[], Awaitable["HubGateway | str"]] + + +class LiveControlRetryPolicy: + """Reconnect immediately, then back off to 5s, 10s and finally 30s between attempts.""" + + def next_delay(self, attempt: int) -> float | None: + if attempt >= 10: + return 30.0 + if attempt >= 3: + return 10.0 + if attempt >= 1: + return 5.0 + return 0.0 + + +@dataclass +class _ShockerState: + type: ControlType + intensity: int + active_until: float + + +class LiveControlClient(WebSocketSession): + """ + Live control of the shockers on one hub (``/1/ws/live/{hubId}`` on the hub's gateway). + + Live control is a stream: instead of "vibrate at 30 for 1 second" you keep telling the + hub what each shocker should be doing *right now*, several times per second. Feed the + current value with :meth:`intake_frame` whenever your input changes (or just + continuously); the client sends it to the gateway at the tick rate the gateway asks + for and stops by itself shortly after you stop feeding it:: + + async with LiveControlClient(hub_id, api_token="...") as live: + await live.wait_connected() + for intensity in range(0, 50): + live.intake_frame(shocker_id, ControlType.VIBRATE, intensity) + await asyncio.sleep(0.1) + + The gateway is looked up through the REST API on every connection attempt, so the + client follows the hub when it moves to another gateway and waits (retrying) while + the hub is offline. Pass ``gateway`` to pin a gateway, or ``gateway_resolver`` to + supply your own lookup. + + The shockers need the *live* permission for your account. + """ + + _name = "live-control" + _retry_initial = True + + def __init__( + self, + hub_id: str | UUID, + *, + api_token: str | None = None, + client: AsyncOpenShockClient | None = None, + base_url: str = DEFAULT_BASE_URL, + gateway: HubGateway | str | None = None, + gateway_resolver: GatewayResolver | None = None, + tps: int | None = None, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + retry_policy: RetryPolicy | None = None, + logger: logging.Logger | None = None, + ) -> None: + """ + Authenticate with ``api_token``, or pass an existing ``client`` to reuse its + token, base URL and HTTP connection pool. + + ``tps`` requests a tick rate (1-10); the gateway decides and announces the final value. + """ + super().__init__(retry_policy=retry_policy or LiveControlRetryPolicy(), logger=logger) + if client is not None and api_token is not None: + raise ValueError("Provide either `client` or `api_token`, not both.") + if tps is not None and not 1 <= tps <= 10: + raise ValueError("tps must be between 1 and 10") + + self.hub_id = UUID(str(hub_id)) + self._headers = dict(headers or {}) + self._owns_client = False + self._api_options: dict[str, Any] = {} + self._api: AsyncOpenShockClient | None = client + + if client is not None: + self._headers = {**client.auth.headers(), **self._headers} + elif api_token is not None: + self._headers = {**ApiTokenAuth(api_token).headers(), **self._headers} + if gateway is None and gateway_resolver is None: + # Created on first use and closed again in stop(), so the client can be restarted. + self._owns_client = True + self._api_options = { + "api_token": api_token, + "base_url": base_url, + "app_name": app_name, + "app_version": app_version, + } + if not any(k.lower() in ("openshocktoken", "cookie") for k in self._headers): + raise ValueError("You must provide `api_token`, `client`, or session credentials via `headers`.") + if gateway is None and gateway_resolver is None and self._api is None and not self._owns_client: + raise ValueError("Without `api_token` or `client` you must provide `gateway` or `gateway_resolver`.") + + self._fixed_gateway = gateway + self._gateway_resolver = gateway_resolver + self._requested_tps = tps + self._user_agent = build_user_agent( + component="Live", + app_name=app_name, + app_version=app_version, + libraries={"websockets": WEBSOCKETS_VERSION}, + ) + + self._gateway: HubGateway | str | None = gateway + self._tps = 0 + self._latency_ms: int | None = None + self._hub_latency_ms: int | None = None + self._hub_connected = False + self._states: dict[UUID, _ShockerState] = {} + self._ticker: asyncio.Task[None] | None = None + + #: ``()`` — the hub is connected to the gateway and accepts frames. + self.on_hub_connected: Event[[]] = Event("on_hub_connected") + #: ``()`` — the hub lost its connection to the gateway; frames are dropped until it is back. + self.on_hub_not_connected: Event[[]] = Event("on_hub_not_connected") + #: ``(latency_ms, hub_latency_ms)`` — measured round-trip time to the gateway, and gateway to hub. + self.on_latency: Event[[int, int]] = Event("on_latency") + #: ``(tps)`` — the gateway announced the tick rate to send frames at. + self.on_tps: Event[[int]] = Event("on_tps") + #: ``(response_type, data)`` — the gateway refused a frame, e.g. ``SHOCKER_PAUSED`` + #: or ``SHOCKER_MISSING_LIVE_PERMISSION``. The response does not say which shocker. + self.on_rejected: Event[[LiveResponseType, Any]] = Event("on_rejected") + + # --- state ------------------------------------------------------------- + + @property + def gateway(self) -> HubGateway | str | None: + """The gateway currently (or last) connected to.""" + return self._gateway + + @property + def tps(self) -> int: + """Ticks per second announced by the gateway; 0 while not connected.""" + return self._tps + + @property + def latency_ms(self) -> int | None: + """Last measured round-trip time to the gateway in milliseconds.""" + return self._latency_ms + + @property + def hub_latency_ms(self) -> int | None: + """Last reported latency between gateway and hub in milliseconds.""" + return self._hub_latency_ms + + @property + def hub_connected(self) -> bool: + """Whether the gateway currently reports the hub as connected.""" + return self._hub_connected and self.is_connected + + # --- sending ----------------------------------------------------------- + + def intake_frame( + self, + shocker: str | UUID, + type: ControlType | str, + intensity: int, + *, + hold_for: float | None = None, + ) -> None: + """ + Set what ``shocker`` should currently be doing. Does not block and never raises + for connection problems: the value is picked up by the next tick. + + The frame is repeated on every tick for a short hold window (2.5 ticks by + default, or ``hold_for`` seconds) and then dropped, so the shocker stops when you + stop calling this. Call it again before the window ends to keep going. + """ + if not 0 <= intensity <= 100: + raise ValueError("intensity must be between 0 and 100") + control_type = ControlType(type) + if not control_type.is_known: + raise ValueError(f"Unknown control type {type!r}") + window = hold_for if hold_for is not None else FRAME_HOLD_TICKS / (self._tps or DEFAULT_TPS) + self._states[UUID(str(shocker))] = _ShockerState( + type=control_type, + intensity=intensity, + active_until=asyncio.get_running_loop().time() + window, + ) + + def release(self, shocker: str | UUID | None = None) -> None: + """Stop sending frames for ``shocker`` right away, or for all shockers if omitted.""" + if shocker is None: + self._states.clear() + else: + self._states.pop(UUID(str(shocker)), None) + + async def send_frame(self, shocker: str | UUID, type: ControlType | str, intensity: int) -> None: + """ + Send a single frame immediately, outside the tick loop. + + Raises :class:`~openshock.exceptions.OpenShockConnectionError` when not connected. + """ + if not 0 <= intensity <= 100: + raise ValueError("intensity must be between 0 and 100") + await self._send("Frame", self._frame(UUID(str(shocker)), ControlType(type), intensity)) + + # --- session hooks ----------------------------------------------------- + + async def start(self) -> None: + try: + await super().start() + except BaseException: + await self._close_owned_client() + raise + + async def stop(self) -> None: + await super().stop() + await self._close_owned_client() + + async def _close_owned_client(self) -> None: + if self._owns_client and self._api is not None: + api, self._api = self._api, None + await api.aclose() + + def _url_for(self, gateway: HubGateway | str) -> str: + base = gateway.ws_url if isinstance(gateway, HubGateway) else gateway.rstrip("/") + if "://" not in base: + base = f"wss://{base}" + url = f"{base}/1/ws/live/{self.hub_id}" + if self._requested_tps is not None: + url += f"?tps={self._requested_tps}" + return url + + async def _resolve_gateway(self) -> HubGateway | str: + if self._fixed_gateway is not None: + return self._fixed_gateway + if self._gateway_resolver is not None: + return await self._gateway_resolver() + if self._api is None: + self._api = AsyncOpenShockClient(**self._api_options) + return await self._api.devices.gateway(self.hub_id) + + async def _open(self) -> ClientConnection: + gateway = await self._resolve_gateway() + self._gateway = gateway + return await self._connect(self._url_for(gateway), self._headers, self._user_agent) + + async def _after_open(self) -> None: + self._ticker = asyncio.create_task(self._tick_loop(), name="openshock-live-ticker") + + async def _after_close(self, error: BaseException | None) -> None: + task, self._ticker = self._ticker, None + if task is not None: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + self._tps = 0 + self._hub_connected = False + + async def _handle(self, message: str) -> None: + payload = json.loads(message) + if not isinstance(payload, dict): + return + raw_type = _get(payload, "responseType") + data = _get(payload, "data") + kind = LiveResponseType.parse(raw_type) + + if kind is None: + self._log.debug("Ignoring unknown live control response %r", raw_type) + elif kind is LiveResponseType.PING: + # The gateway closes the connection on a request without data, so always echo something. + await self._send("Pong", data if isinstance(data, dict) else {}) + elif kind is LiveResponseType.LATENCY_ANNOUNCE: + if isinstance(data, dict): + self._latency_ms = int(_get(data, "ownLatency", 0)) + self._hub_latency_ms = int(_get(data, "deviceLatency", 0)) + self._emit(self.on_latency.emit, self._latency_ms, self._hub_latency_ms) + elif kind is LiveResponseType.TPS: + if isinstance(data, dict): + self._tps = max(0, int(_get(data, "client", 0))) + self._emit(self.on_tps.emit, self._tps) + elif kind is LiveResponseType.DEVICE_CONNECTED: + self._hub_connected = True + self._emit(self.on_hub_connected.emit) + elif kind is LiveResponseType.DEVICE_NOT_CONNECTED: + self._hub_connected = False + self._emit(self.on_hub_not_connected.emit) + elif kind.is_rejection: + self._emit(self.on_rejected.emit, kind, data) + + # --- internals --------------------------------------------------------- + + @staticmethod + def _frame(shocker: UUID, control_type: ControlType, intensity: int) -> dict[str, Any]: + return {"shocker": str(shocker), "intensity": intensity, "type": control_type.value} + + async def _send(self, request_type: str, data: Any) -> None: + await self._send_text(json.dumps({"requestType": request_type, "data": data}, separators=(",", ":"))) + + async def _tick_loop(self) -> None: + loop = asyncio.get_running_loop() + next_tick = loop.time() + while True: + tps = self._tps + if tps <= 0: + # Nothing may be sent before the gateway announced its tick rate. + await asyncio.sleep(0.05) + next_tick = loop.time() + continue + + next_tick = max(next_tick + 1.0 / tps, loop.time()) + await asyncio.sleep(max(0.0, next_tick - loop.time())) + + now = loop.time() + frames = [] + for shocker, state in list(self._states.items()): + if state.active_until < now: + del self._states[shocker] + continue + frames.append(self._frame(shocker, state.type, state.intensity)) + if not frames: + continue + try: + await self._send("BulkFrame", frames) + except Exception as exc: + self._log.debug("Could not send frames: %s", exc) diff --git a/openshock/realtime/models.py b/openshock/realtime/models.py new file mode 100644 index 0000000..b7b8c46 --- /dev/null +++ b/openshock/realtime/models.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +from enum import IntEnum +from typing import Any +from uuid import UUID + +from ..models.common import ControlType, WireEnum, require_dt, require_uuid + + +def _get(data: dict[str, Any], key: str, default: Any = None) -> Any: + """Case-insensitive lookup: the live gateway sends PascalCase, SignalR camelCase.""" + if key in data: + return data[key] + lowered = key.lower() + for k, v in data.items(): + if k.lower() == lowered: + return v + return default + + +class HubUpdateType(WireEnum): + """What changed about a hub (``UserHubClient.on_hub_update``).""" + + CREATED = "Created" + UPDATED = "Updated" + SHOCKER_UPDATED = "ShockerUpdated" + DELETED = "Deleted" + PAIRED = "Paired" + + +class OtaUpdateProgressTask(WireEnum): + """Stage of a firmware update (``UserHubClient.on_ota_install_progress``).""" + + FETCHING_METADATA = "FetchingMetadata" + PREPARING_FOR_UPDATE = "PreparingForUpdate" + FLASHING_FILESYSTEM = "FlashingFilesystem" + VERIFYING_FILESYSTEM = "VerifyingFilesystem" + FLASHING_APPLICATION = "FlashingApplication" + MARKING_APPLICATION_BOOTABLE = "MarkingApplicationBootable" + REBOOTING = "Rebooting" + + +@dataclass +class HubOnlineState: + """Online state of a hub (``UserHubClient.on_hub_status``).""" + + device: UUID + online: bool + firmware_version: str | None = None + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> HubOnlineState: + return cls( + device=require_uuid(_get(data, "device")), + online=bool(_get(data, "online", False)), + firmware_version=_get(data, "firmwareVersion"), + ) + + +@dataclass +class BasicShockerInfo: + id: UUID + name: str + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> BasicShockerInfo: + return cls(id=require_uuid(_get(data, "id")), name=_get(data, "name", "")) + + +@dataclass +class HubControlLogSender: + """Who issued the commands of a live log event.""" + + id: UUID + name: str + image: str + custom_name: str | None = None + #: SignalR / HTTP connection the commands came from. + connection_id: str = "" + additional_items: dict[str, Any] = field(default_factory=dict) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> HubControlLogSender: + return cls( + id=require_uuid(_get(data, "id")), + name=_get(data, "name", ""), + image=_get(data, "image", ""), + custom_name=_get(data, "customName"), + connection_id=_get(data, "connectionId") or "", + additional_items=dict(_get(data, "additionalItems") or {}), + ) + + +@dataclass +class ControlLog: + """One executed command of a live log event.""" + + shocker: BasicShockerInfo + type: ControlType + intensity: int + duration: int + executed_at: datetime + live_control: bool = False + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ControlLog: + return cls( + shocker=BasicShockerInfo.from_dict(_get(data, "shocker")), + type=ControlType(_get(data, "type")), + intensity=int(_get(data, "intensity", 0)), + duration=int(_get(data, "duration", 0)), + executed_at=require_dt(_get(data, "executedAt")), + live_control=bool(_get(data, "liveControl", False)), + ) + + +class LiveResponseType(IntEnum): + """Message types the live control gateway sends.""" + + FRAME = 0 + TPS = 50 + DEVICE_NOT_CONNECTED = 100 + DEVICE_CONNECTED = 101 + SHOCKER_NOT_FOUND = 150 + SHOCKER_MISSING_LIVE_PERMISSION = 151 + SHOCKER_MISSING_PERMISSION = 152 + SHOCKER_PAUSED = 153 + SHOCKER_EXCLUSIVE = 154 + TOKEN_PAUSED = 155 + INVALID_DATA = 200 + REQUEST_TYPE_NOT_FOUND = 201 + PING = 1000 + LATENCY_ANNOUNCE = 1001 + + @classmethod + def parse(cls, value: Any) -> LiveResponseType | None: + """Parse a name (any casing) or number. Returns ``None`` for unknown values.""" + if isinstance(value, bool): + return None + if isinstance(value, int): + try: + return cls(value) + except ValueError: + return None + if isinstance(value, str): + if value.isdigit(): + return cls.parse(int(value)) + wanted = value.replace("_", "").lower() + for member in cls: + if member.name.replace("_", "").lower() == wanted: + return member + return None + + @property + def is_rejection(self) -> bool: + """True for responses that mean a frame or request was not accepted.""" + return 150 <= self.value < 1000 diff --git a/openshock/realtime/user_hub.py b/openshock/realtime/user_hub.py new file mode 100644 index 0000000..867b0c6 --- /dev/null +++ b/openshock/realtime/user_hub.py @@ -0,0 +1,206 @@ +from __future__ import annotations + +import logging +from collections.abc import Mapping, Sequence +from typing import Any +from uuid import UUID + +from .._core import DEFAULT_BASE_URL, build_user_agent +from ..models import Control +from ..models.common import require_uuid +from ._events import Event +from ._signalr import SignalRConnection +from ._transport import WEBSOCKETS_VERSION, RetryPolicy, StepRetryPolicy +from .models import ControlLog, HubControlLogSender, HubOnlineState, HubUpdateType, OtaUpdateProgressTask + +#: Reconnect immediately, then after 2s, 10s, and every 30s from there on. +USER_HUB_RETRY_POLICY = StepRetryPolicy((0, 2, 10, 30)) + + +def _ws_url(base_url: str, path: str) -> str: + base = base_url.rstrip("/") + if base.startswith("https://"): + base = "wss://" + base[len("https://") :] + elif base.startswith("http://"): + base = "ws://" + base[len("http://") :] + return base + path + + +class UserHubClient(SignalRConnection): + """ + Realtime connection to the OpenShock user hub (SignalR, ``/1/hubs/user``). + + Receives live events for your account (hub online state, executed commands, hub + changes, firmware update progress) and can send control commands over the same + connection:: + + async with UserHubClient(api_token="...", app_name="MyApp", app_version="1.0") as hub: + + @hub.on_log + async def on_log(sender, logs): + for log in logs: + print(sender.name, log.type, log.intensity, log.shocker.name) + + await hub.control([Control(id=shocker_id, type=ControlType.VIBRATE, intensity=30, duration=1000)]) + await hub.wait_closed() + + The connection reconnects by itself (see ``retry_policy``). A rejected or revoked + token ends the session instead: ``on_closed`` fires with the error and + ``wait_closed()`` raises it. + + Not to be confused with :class:`openshock.OpenShockHubClient`, the REST client a + hub *device* uses. + """ + + _name = "user-hub" + + def __init__( + self, + api_token: str | None = None, + *, + base_url: str = DEFAULT_BASE_URL, + app_name: str | None = None, + app_version: str | None = None, + headers: Mapping[str, str] | None = None, + retry_policy: RetryPolicy | None = None, + logger: logging.Logger | None = None, + ) -> None: + all_headers = dict(headers or {}) + if api_token is not None: + all_headers["OpenShockToken"] = api_token + if not any(k.lower() in ("openshocktoken", "cookie") for k in all_headers): + raise ValueError("You must provide `api_token` (or session credentials via `headers`).") + + super().__init__( + _ws_url(base_url, "/1/hubs/user"), + headers=all_headers, + user_agent=build_user_agent( + component="Hub", + app_name=app_name, + app_version=app_version, + libraries={"websockets": WEBSOCKETS_VERSION}, + ), + retry_policy=retry_policy or USER_HUB_RETRY_POLICY, + logger=logger, + ) + + self._connection_id: str | None = None + + #: ``(connection_id)`` — sent by the server right after (re)connecting. + self.on_welcome: Event[[str]] = Event("on_welcome") + #: ``(states)`` — hubs that came online or went offline. On connect you get every hub that is online. + self.on_hub_status: Event[[list[HubOnlineState]]] = Event("on_hub_status") + #: ``(sender, logs)`` — commands were executed on shockers you own. + self.on_log: Event[[HubControlLogSender, list[ControlLog]]] = Event("on_log") + #: ``(hub_id, update_type)`` — a hub or one of its shockers was created, changed or deleted. + self.on_hub_update: Event[[UUID, HubUpdateType]] = Event("on_hub_update") + #: ``(hub_id, update_id, version)`` + self.on_ota_install_started: Event[[UUID, int, str]] = Event("on_ota_install_started") + #: ``(hub_id, update_id, task, progress)`` — ``progress`` is 0.0 to 1.0 within ``task``. + self.on_ota_install_progress: Event[[UUID, int, OtaUpdateProgressTask, float]] = Event( + "on_ota_install_progress" + ) + #: ``(hub_id, update_id, fatal, message)`` + self.on_ota_install_failed: Event[[UUID, int, bool, str]] = Event("on_ota_install_failed") + #: ``(hub_id, update_id)`` + self.on_ota_rollback: Event[[UUID, int]] = Event("on_ota_rollback") + #: ``(hub_id, update_id)`` + self.on_ota_install_succeeded: Event[[UUID, int]] = Event("on_ota_install_succeeded") + + self._register("Welcome", self._recv_welcome) + self._register("DeviceStatus", self._recv_device_status) + self._register("Log", self._recv_log) + self._register("DeviceUpdate", self._recv_device_update) + self._register("OtaInstallStarted", self._recv_ota_started) + self._register("OtaInstallProgress", self._recv_ota_progress) + self._register("OtaInstallFailed", self._recv_ota_failed) + self._register("OtaRollback", self._recv_ota_rollback) + self._register("OtaInstallSucceeded", self._recv_ota_succeeded) + + @property + def connection_id(self) -> str | None: + """ + ID of the current connection, as announced by the server. Compare it with + ``sender.connection_id`` in ``on_log`` to recognise your own commands. + """ + return self._connection_id + + # --- client -> server -------------------------------------------------- + + async def control( + self, + controls: Sequence[Control | dict[str, Any]] | Control, + *, + custom_name: str | None = None, + ) -> None: + """ + Send control commands over the hub connection. + + Unlike the REST endpoint this does not report per-shocker rejections: commands + the server refuses (unknown shocker, paused, no permission) are dropped silently. + Use ``client.shockers.control()`` when you need that feedback. + """ + if isinstance(controls, Control): + controls = [controls] + if not controls: + raise ValueError("controls must be a non-empty sequence") + shocks = [c.to_signalr() if isinstance(c, Control) else c for c in controls] + await self.invoke("ControlV2", shocks, custom_name) + + async def set_captive_portal(self, hub_id: str | UUID, enabled: bool) -> None: + """Turn a hub's Wi-Fi setup portal on or off. Requires user-session auth; ignored for API tokens.""" + await self.invoke("CaptivePortal", str(hub_id), enabled) + + async def emergency_stop(self, hub_id: str | UUID) -> None: + """Trigger a hub's emergency stop. Requires user-session auth; ignored for API tokens.""" + await self.invoke("EmergencyStop", str(hub_id)) + + async def ota_install(self, hub_id: str | UUID, version: str) -> None: + """Start a firmware update to ``version``. Requires user-session auth; ignored for API tokens.""" + await self.invoke("OtaInstall", str(hub_id), version) + + async def reboot(self, hub_id: str | UUID) -> None: + """Reboot a hub. Requires user-session auth; ignored for API tokens.""" + await self.invoke("Reboot", str(hub_id)) + + # --- server -> client -------------------------------------------------- + + async def _after_close(self, error: BaseException | None) -> None: + self._connection_id = None + await super()._after_close(error) + + def _recv_welcome(self, args: list[Any]) -> None: + self._connection_id = str(args[0]) + self._emit(self.on_welcome.emit, self._connection_id) + + def _recv_device_status(self, args: list[Any]) -> None: + self._emit(self.on_hub_status.emit, [HubOnlineState.from_dict(s) for s in args[0] or []]) + + def _recv_log(self, args: list[Any]) -> None: + sender = HubControlLogSender.from_dict(args[0]) + logs = [ControlLog.from_dict(entry) for entry in args[1] or []] + self._emit(self.on_log.emit, sender, logs) + + def _recv_device_update(self, args: list[Any]) -> None: + self._emit(self.on_hub_update.emit, require_uuid(args[0]), HubUpdateType(args[1])) + + def _recv_ota_started(self, args: list[Any]) -> None: + self._emit(self.on_ota_install_started.emit, require_uuid(args[0]), int(args[1]), str(args[2])) + + def _recv_ota_progress(self, args: list[Any]) -> None: + self._emit( + self.on_ota_install_progress.emit, + require_uuid(args[0]), + int(args[1]), + OtaUpdateProgressTask(args[2]), + float(args[3]), + ) + + def _recv_ota_failed(self, args: list[Any]) -> None: + self._emit(self.on_ota_install_failed.emit, require_uuid(args[0]), int(args[1]), bool(args[2]), str(args[3])) + + def _recv_ota_rollback(self, args: list[Any]) -> None: + self._emit(self.on_ota_rollback.emit, require_uuid(args[0]), int(args[1])) + + def _recv_ota_succeeded(self, args: list[Any]) -> None: + self._emit(self.on_ota_install_succeeded.emit, require_uuid(args[0]), int(args[1])) diff --git a/openshock/resources/__init__.py b/openshock/resources/__init__.py index e69de29..97cbf7a 100644 --- a/openshock/resources/__init__.py +++ b/openshock/resources/__init__.py @@ -0,0 +1,18 @@ +"""Resource classes behind ``client.``. Exposed for type annotations.""" + +from .._async.resources.account import AsyncAccountResource as AsyncAccountResource +from .._async.resources.devices import AsyncDevicesResource as AsyncDevicesResource +from .._async.resources.hub import AsyncHubResource as AsyncHubResource +from .._async.resources.meta import AsyncMetaResource as AsyncMetaResource +from .._async.resources.sessions import AsyncSessionsResource as AsyncSessionsResource +from .._async.resources.shares import AsyncSharesResource as AsyncSharesResource +from .._async.resources.shockers import AsyncShockersResource as AsyncShockersResource +from .._async.resources.user_shares import AsyncUserSharesResource as AsyncUserSharesResource +from .._sync.resources.account import AccountResource as AccountResource +from .._sync.resources.devices import DevicesResource as DevicesResource +from .._sync.resources.hub import HubResource as HubResource +from .._sync.resources.meta import MetaResource as MetaResource +from .._sync.resources.sessions import SessionsResource as SessionsResource +from .._sync.resources.shares import SharesResource as SharesResource +from .._sync.resources.shockers import ShockersResource as ShockersResource +from .._sync.resources.user_shares import UserSharesResource as UserSharesResource diff --git a/openshock/resources/devices.py b/openshock/resources/devices.py deleted file mode 100644 index 0d0d65e..0000000 --- a/openshock/resources/devices.py +++ /dev/null @@ -1,65 +0,0 @@ -from __future__ import annotations - -import builtins -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..models import Device, DeviceWithToken, LcgInfo, OtaUpdate, PairCode, Shocker - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class DevicesResource: - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def list(self) -> builtins.list[Device]: - """GET /1/devices — List all devices for the authenticated user.""" - resp = self._client._request("GET", "/1/devices") - return [Device.from_dict(d) for d in (resp.get("data") or [])] - - def create(self, name: str) -> DeviceWithToken: - """POST /2/devices — Create a new device. Returns device with token.""" - resp = self._client._request("POST", "/2/devices", json={"name": name}) - return DeviceWithToken.from_dict(resp.get("data", resp)) - - def get(self, device_id: str | UUID) -> Device: - """GET /1/devices/{deviceId} — Get a device by ID.""" - resp = self._client._request("GET", f"/1/devices/{device_id}") - return Device.from_dict(resp.get("data", resp)) - - def edit(self, device_id: str | UUID, *, name: str) -> None: - """PATCH /1/devices/{deviceId} — Update a device's name.""" - self._client._request("PATCH", f"/1/devices/{device_id}", json={"name": name}) - - def delete(self, device_id: str | UUID) -> None: - """DELETE /1/devices/{deviceId} — Remove a device.""" - self._client._request("DELETE", f"/1/devices/{device_id}") - - def regenerate_token(self, device_id: str | UUID) -> str: - """PUT /1/devices/{deviceId} — Regenerate device token. Returns new token string.""" - resp: Any = self._client._request("PUT", f"/1/devices/{device_id}") - if isinstance(resp, dict): - return str(resp.get("data", "")) - return str(resp) - - def shockers(self, device_id: str | UUID) -> builtins.list[Shocker]: - """GET /1/devices/{deviceId}/shockers — Get all shockers for a device.""" - resp = self._client._request("GET", f"/1/devices/{device_id}/shockers") - return [Shocker.from_dict(s) for s in (resp.get("data") or [])] - - def pair_code(self, device_id: str | UUID) -> PairCode: - """GET /1/devices/{deviceId}/pair — Get the current pair code.""" - resp = self._client._request("GET", f"/1/devices/{device_id}/pair") - return PairCode.from_dict(resp.get("data", resp)) - - def lcg_info(self, device_id: str | UUID) -> LcgInfo: - """GET /1/devices/{deviceId}/lcg — Get LCG connection info.""" - resp = self._client._request("GET", f"/1/devices/{device_id}/lcg") - return LcgInfo.from_dict(resp.get("data", resp)) - - def ota_history(self, device_id: str | UUID) -> builtins.list[OtaUpdate]: - """GET /1/devices/{deviceId}/ota — Get OTA update history.""" - resp = self._client._request("GET", f"/1/devices/{device_id}/ota") - return [OtaUpdate.from_dict(o) for o in (resp.get("data") or [])] diff --git a/pyproject.toml b/pyproject.toml index 40da7f4..0fedc9e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openshock" -version = "0.1.0b1" +version = "0.2.0b1" description = "The official OpenShock Python SDK to integrate with an OpenShock backend easily" readme = "README.md" requires-python = ">=3.10" @@ -15,7 +15,7 @@ authors = [ dependencies = [ "httpx>=0.28.1", ] -keywords = ["openshock", "api", "iot"] +keywords = ["openshock", "api", "iot", "signalr", "asyncio"] classifiers = [ "Development Status :: 3 - Alpha", "Programming Language :: Python :: 3", @@ -23,6 +23,7 @@ classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Framework :: AsyncIO", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Typing :: Typed", @@ -35,9 +36,16 @@ Repository = "https://github.com/OpenShock/SDK.Python" Issues = "https://github.com/OpenShock/SDK.Python/issues" [project.optional-dependencies] +# SignalR user hub and live control (openshock.realtime) +realtime = [ + "websockets>=13.0", +] dev = [ + "openshock[realtime]", "pytest>=8.0", + "pytest-asyncio>=0.24", "pytest-cov", + "pytest-timeout", "mypy>=1.10", "ruff>=0.8", ] @@ -46,6 +54,8 @@ dev = [ [tool.ruff] target-version = "py310" line-length = 120 +# Generated from openshock/_async by scripts/unasync.py; formatting it would make it drift. +extend-exclude = ["openshock/_sync"] [tool.ruff.lint] select = ["E", "F", "W", "I", "UP", "B", "SIM"] @@ -68,3 +78,6 @@ disallow_untyped_defs = false # --- pytest --- [tool.pytest.ini_options] testpaths = ["tests"] +asyncio_mode = "auto" +timeout = 30 +asyncio_default_fixture_loop_scope = "function" diff --git a/scripts/unasync.py b/scripts/unasync.py new file mode 100644 index 0000000..fce11e0 --- /dev/null +++ b/scripts/unasync.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +""" +Generate the synchronous client (openshock/_sync) from the async one (openshock/_async). + +The async code is the single source of truth. Run this after editing anything under +openshock/_async: + + python scripts/unasync.py # rewrite openshock/_sync + python scripts/unasync.py --check # exit 1 if openshock/_sync is out of date (used in CI) +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SRC = ROOT / "openshock" / "_async" +DST = ROOT / "openshock" / "_sync" + +HEADER = "# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand.\n" + +# Applied in order, on whole words. +REPLACEMENTS: list[tuple[str, str]] = [ + (r"\basync def\b", "def"), + (r"\basync with\b", "with"), + (r"\basync for\b", "for"), + (r"\bawait ", ""), + (r"\bAsyncOpenShock(\w*)Client\b", r"OpenShock\1Client"), + (r"\b_AsyncBaseClient\b", "_BaseClient"), + (r"\bAsync(\w+)Resource\b", r"\1Resource"), + (r"\bhttpx\.AsyncClient\b", "httpx.Client"), + (r"\bhttpx\.AsyncBaseTransport\b", "httpx.BaseTransport"), + (r"\b__aenter__\b", "__enter__"), + (r"\b__aexit__\b", "__exit__"), + (r"\baclose\b", "close"), +] + + +def convert(source: str) -> str: + for pattern, repl in REPLACEMENTS: + source = re.sub(pattern, repl, source) + return HEADER + source if source.strip() else source + + +def main() -> int: + check = "--check" in sys.argv[1:] + stale: list[Path] = [] + expected: set[Path] = set() + + for src in sorted(SRC.rglob("*.py")): + dst = DST / src.relative_to(SRC) + expected.add(dst) + new = convert(src.read_text(encoding="utf-8")) + old = dst.read_text(encoding="utf-8") if dst.exists() else None + if new == old: + continue + stale.append(dst) + if not check: + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(new, encoding="utf-8") + + for dst in sorted(DST.rglob("*.py")) if DST.exists() else []: + if dst not in expected: + stale.append(dst) + if not check: + dst.unlink() + + if check and stale: + print("openshock/_sync is out of date. Run `python scripts/unasync.py`. Stale files:") + for path in stale: + print(f" {path.relative_to(ROOT)}") + return 1 + if not check: + print(f"unasync: {len(stale)} file(s) updated") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..79d74c3 --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,184 @@ +"""In-process fakes of the OpenShock SignalR user hub and live control gateway.""" + +from __future__ import annotations + +import asyncio +import http +import json +from typing import Any + +from websockets.asyncio.server import ServerConnection, serve +from websockets.exceptions import ConnectionClosed + +RS = "\x1e" +TOKEN = "good-token" + + +def _problem(connection: ServerConnection, status: int, type_: str) -> Any: + response = connection.respond( + http.HTTPStatus(status), json.dumps({"type": type_, "title": type_, "status": status}) + ) + response.headers["Content-Type"] = "application/problem+json" + return response + + +class _FakeServer: + def __init__(self) -> None: + self.connections: list[ServerConnection] = [] + self.requests: list[Any] = [] + self.connected = asyncio.Event() + self._server: Any = None + + async def __aenter__(self): + self._server = await serve(self._handler, "127.0.0.1", 0, process_request=self._process_request) + return self + + async def __aexit__(self, *exc: object) -> None: + self._server.close() + await self._server.wait_closed() + + @property + def port(self) -> int: + return int(next(iter(self._server.sockets)).getsockname()[1]) + + def _process_request(self, connection: ServerConnection, request: Any) -> Any: + self.requests.append(request) + if request.headers.get("OpenShockToken") != TOKEN: + return connection.respond(http.HTTPStatus.UNAUTHORIZED, "") + return None + + async def _handler(self, connection: ServerConnection) -> None: + raise NotImplementedError + + async def drop_connections(self) -> None: + """Abruptly close every open connection, as a network failure would.""" + self.connected.clear() + for connection in list(self.connections): + await connection.close(code=1011) + + +class FakeSignalRHub(_FakeServer): + """Speaks the SignalR JSON protocol. Records invocations and can push events.""" + + def __init__(self) -> None: + super().__init__() + self.invocations: list[dict[str, Any]] = [] + self.pings = 0 + self.fail_targets: set[str] = set() + self.handshake_error: str | None = None + + @property + def http_url(self) -> str: + return f"http://127.0.0.1:{self.port}" + + async def push(self, target: str, *arguments: Any) -> None: + message = json.dumps({"type": 1, "target": target, "arguments": list(arguments)}) + RS + for connection in list(self.connections): + await connection.send(message) + + async def send_close(self, error: str | None = None, allow_reconnect: bool = False) -> None: + message = json.dumps({"type": 7, "error": error, "allowReconnect": allow_reconnect}) + RS + for connection in list(self.connections): + await connection.send(message) + + async def _handler(self, connection: ServerConnection) -> None: + try: + handshake = json.loads(str(await connection.recv()).rstrip(RS)) + assert handshake == {"protocol": "json", "version": 1} + if self.handshake_error: + await connection.send(json.dumps({"error": self.handshake_error}) + RS) + return + index = len(self.requests) + # The real server may put the first invocation in the same frame as the handshake response. + welcome = json.dumps({"type": 1, "target": "Welcome", "arguments": [f"conn-{index}"]}) + await connection.send("{}" + RS + welcome + RS) + self.connections.append(connection) + self.connected.set() + async for raw in connection: + for part in str(raw).split(RS): + if part: + await self._on_message(connection, json.loads(part)) + except ConnectionClosed: + pass + finally: + if connection in self.connections: + self.connections.remove(connection) + + async def _on_message(self, connection: ServerConnection, message: dict[str, Any]) -> None: + if message["type"] == 6: + self.pings += 1 + return + if message["type"] != 1: + return + self.invocations.append(message) + invocation_id = message.get("invocationId") + if invocation_id is None: + return + completion: dict[str, Any] = {"type": 3, "invocationId": invocation_id} + if message["target"] in self.fail_targets: + completion["error"] = f"{message['target']} failed" + await connection.send(json.dumps(completion) + RS) + + +class FakeLiveGateway(_FakeServer): + """Speaks the live control protocol, answering in PascalCase like the real gateway.""" + + def __init__(self, *, tps: int = 10) -> None: + super().__init__() + self.tps = tps + self.received: list[dict[str, Any]] = [] + #: Problem types to answer the next connection attempts with, instead of accepting. + self.reject_with: list[tuple[int, str]] = [] + + @property + def ws_url(self) -> str: + return f"ws://127.0.0.1:{self.port}" + + def frames(self) -> list[list[dict[str, Any]]]: + return [m["data"] for m in self.received if m["requestType"] == "BulkFrame"] + + def _process_request(self, connection: ServerConnection, request: Any) -> Any: + rejected = super()._process_request(connection, request) + if rejected is not None: + return rejected + if self.reject_with: + status, type_ = self.reject_with.pop(0) + return _problem(connection, status, type_) + return None + + async def send(self, response_type: str, data: Any = None) -> None: + message = json.dumps({"ResponseType": response_type, "Data": data}) + for connection in list(self.connections): + await connection.send(message) + + async def _handler(self, connection: ServerConnection) -> None: + self.connections.append(connection) + try: + await connection.send(json.dumps({"ResponseType": "TPS", "Data": {"Client": self.tps}})) + await connection.send(json.dumps({"ResponseType": "DeviceConnected", "Data": None})) + self.connected.set() + async for raw in connection: + message = json.loads(raw) + # The real gateway force-closes on a request without data. + if message.get("data") is None: + await connection.close(code=1007, reason="Invalid json message received") + return + self.received.append(message) + if message["requestType"] == "Pong": + await connection.send( + json.dumps({"ResponseType": "LatencyAnnounce", "Data": {"DeviceLatency": 3, "OwnLatency": 12}}) + ) + except ConnectionClosed: + pass + finally: + if connection in self.connections: + self.connections.remove(connection) + + +async def eventually(predicate: Any, timeout: float = 3.0) -> None: + """Wait until ``predicate()`` is truthy.""" + deadline = asyncio.get_running_loop().time() + timeout + while not predicate(): + if asyncio.get_running_loop().time() > deadline: + raise AssertionError("condition was not met in time") + await asyncio.sleep(0.01) diff --git a/tests/test_client.py b/tests/test_client.py index 523db45..b2f92a8 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -57,3 +57,15 @@ def test_not_found_is_openshock_error(self): def test_api_error_is_openshock_error(self): assert issubclass(OpenShockApiError, OpenShockError) + + def test_status_errors_are_api_errors(self): + assert issubclass(OpenShockAuthError, OpenShockApiError) + assert issubclass(OpenShockNotFound, OpenShockApiError) + + +def test_resource_classes_are_importable(): + from openshock.resources import AsyncShockersResource, ShockersResource + + with OpenShockClient(api_token="test") as client: + assert isinstance(client.shockers, ShockersResource) + assert not isinstance(client.shockers, AsyncShockersResource) diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py new file mode 100644 index 0000000..d1c1e9b --- /dev/null +++ b/tests/test_endpoints.py @@ -0,0 +1,228 @@ +"""Every REST method, sync and async: hits the right route and parses a realistic response.""" + +from __future__ import annotations + +import inspect +import json +from typing import Any +from uuid import UUID + +import httpx +import pytest + +from openshock import ( + AsyncOpenShockClient, + AsyncOpenShockHubClient, + OpenShockClient, + OpenShockHubClient, + OtaUpdateStatus, + PauseReason, + ShareInviteShocker, + ShockerLimits, + ShockerPermissions, +) + +A = "11111111-1111-1111-1111-111111111111" +B = "22222222-2222-2222-2222-222222222222" +NOW = "2024-06-01T12:00:00Z" +PERMS = {"vibrate": True, "sound": True, "shock": True, "live": False} +LIMITS = {"intensity": 50, "duration": 3000} +USER = {"id": A, "name": "user", "image": "https://img"} +SHOCKER = {"id": B, "rfId": 1, "model": "CaiXianlin", "name": "s", "isPaused": False, "createdOn": NOW} +TOKEN = {"id": A, "name": "t", "createdOn": NOW, "validUntil": None, "lastUsed": NOW, "permissions": ["shockers.use"]} +SESSION = {"id": A, "ip": "::1", "userAgent": "ua", "created": NOW, "expires": NOW, "lastUsed": None} +LOG = { + "id": A, + "createdOn": NOW, + "type": "Shock", + "controlledBy": {**USER, "customName": None}, + "intensity": 1, + "duration": 300, + "liveControl": False, +} +SHARE_ITEM = {"id": B, "name": "s", "createdOn": NOW, "permissions": PERMS, "limits": LIMITS, "paused": 0} +USER_SHARE = {**USER, "shares": [SHARE_ITEM]} +INVITE = { + "id": A, + "createdAt": NOW, + "owner": USER, + "sharedWith": USER, + "shockers": [{"id": B, "name": "s", "permissions": PERMS, "limits": LIMITS}], +} +PUBLIC_SHARE = { + "id": A, + "name": "p", + "createdOn": NOW, + "expiresOn": None, + "author": USER, + "devices": [{"id": A, "name": "d", "shockers": [{"id": B, "name": "s", "permissions": PERMS, "limits": LIMITS}]}], +} +P = ShockerPermissions(vibrate=True, sound=True, shock=False) +L = ShockerLimits(intensity=10, duration=1000) + + +def data(value: Any) -> dict[str, Any]: + return {"message": "", "data": value} + + +# (resource.method, args, kwargs, HTTP method, path, response body, check(result)) +USER_CASES: list[tuple[str, tuple, dict, str, str, Any, Any]] = [ + ("meta.backend_info", (), {}, "GET", "/1", data({ + "version": "1", "commit": "c", "currentTime": NOW, "frontendUrl": "f", "shortLinkUrl": "s", + "turnstileSiteKey": "k", "isUserAuthenticated": True, "oAuthProviders": ["discord"], + }), lambda r: r.version == "1"), + ("meta.online_stats", (), {}, "GET", "/1/public/stats", + data({"devicesOnline": 4}), lambda r: r.devices_online == 4), + ("account.user_self", (), {}, "GET", "/1/users/self", + data({**USER, "email": "e", "roles": ["Admin"], "rank": "Admin"}), lambda r: r.roles == ["Admin"]), + ("account.token_self", (), {}, "GET", "/1/tokens/self", TOKEN, lambda r: r.name == "t"), + ("account.list_tokens", (), {}, "GET", "/1/tokens", [TOKEN], lambda r: len(r) == 1), + ("account.get_token", (A,), {}, "GET", f"/1/tokens/{A}", TOKEN, lambda r: r.id == UUID(A)), + ("account.edit_token", (A,), {"name": "n"}, "PATCH", f"/1/tokens/{A}", None, lambda r: r is None), + ("account.revoke_token", (A,), {}, "DELETE", f"/1/tokens/{A}", None, lambda r: r is None), + ("devices.list", (), {}, "GET", "/1/devices", + data([{"id": A, "name": "d", "createdOn": NOW}]), lambda r: r[0].name == "d"), + ("devices.edit", (A,), {"name": "n"}, "PATCH", f"/1/devices/{A}", None, lambda r: r is None), + ("devices.delete", (A,), {}, "DELETE", f"/1/devices/{A}", None, lambda r: r is None), + ("devices.regenerate_token", (A,), {}, "PUT", f"/1/devices/{A}", "newtoken", lambda r: r == "newtoken"), + ("devices.shockers", (A,), {}, "GET", f"/1/devices/{A}/shockers", data([SHOCKER]), lambda r: r[0].rf_id == 1), + ("devices.lcg_info", (A,), {}, "GET", f"/1/devices/{A}/lcg", + data({"gateway": "gw", "country": "DE"}), lambda r: r.gateway == "gw"), + ("devices.ota_history", (A,), {}, "GET", f"/1/devices/{A}/ota", + data([{"id": 1, "startedAt": NOW, "status": "Finished", "version": "1.0.0", "message": None}]), + lambda r: r[0].status is OtaUpdateStatus.FINISHED), + ("shockers.get", (B,), {}, "GET", f"/1/shockers/{B}", + data({**SHOCKER, "device": A, "permissions": PERMS, "limits": LIMITS}), lambda r: r.device == UUID(A)), + ("shockers.register", (), {"name": "s", "rf_id": 1, "device": A, "model": "caixianlin"}, + "POST", "/1/shockers", data(B), lambda r: r == UUID(B)), + ("shockers.edit", (B,), {"name": "n", "rf_id": 2, "device": A, "model": "PetTrainer"}, + "PATCH", f"/1/shockers/{B}", None, lambda r: r is None), + ("shockers.logs", (B,), {"limit": 5}, "GET", f"/1/shockers/{B}/logs", data([LOG]), lambda r: r[0].type == "Shock"), + ("shockers.all_logs", (), {}, "GET", "/1/shockers/logs", + data([{**LOG, "hubId": A, "hubName": "h", "shockerId": B, "shockerName": "s"}]), + lambda r: r[0].hub_name == "h" and r[0].shocker_id == UUID(B)), + ("shockers.get_shares", (B,), {}, "GET", f"/1/shockers/{B}/shares", + data([{"sharedWith": USER, "createdOn": NOW, "permissions": PERMS, "limits": LIMITS, "paused": False}]), + lambda r: r[0].shared_with.name == "user"), + ("shockers.create_share_code", (B,), {"permissions": P, "limits": L}, + "POST", f"/1/shockers/{B}/shares", data(A), lambda r: r == UUID(A)), + ("shockers.list_share_codes", (B,), {}, "GET", f"/1/shockers/{B}/shareCodes", + data([{"id": A, "createdOn": NOW}]), lambda r: r[0].id == UUID(A)), + ("shockers.update_share", (B, A), {"permissions": P, "limits": L}, + "PATCH", f"/1/shockers/{B}/shares/{A}", None, lambda r: r is None), + ("shockers.remove_share", (B, A), {}, "DELETE", f"/1/shockers/{B}/shares/{A}", None, lambda r: r is None), + ("shockers.pause_share", (B, A, True), {}, "POST", f"/1/shockers/{B}/shares/{A}/pause", + data(True), lambda r: r is True), + ("shares.list_public", (), {}, "GET", "/1/shares/links", + data([{"id": A, "name": "p", "createdOn": NOW, "expiresOn": None}]), lambda r: r[0].name == "p"), + ("shares.create_public", ("p",), {"expires_on": NOW}, "POST", "/1/shares/links", data(A), lambda r: r == UUID(A)), + ("shares.delete_public", (A,), {}, "DELETE", f"/1/shares/links/{A}", data(None), lambda r: r is None), + ("shares.public_get", (A,), {}, "GET", f"/1/public/shares/links/{A}", + data(PUBLIC_SHARE), lambda r: r.devices[0].shockers[0].paused is PauseReason.NONE), + ("shares.add_shocker", (A, B), {}, "POST", f"/1/shares/links/{A}/{B}", data(None), lambda r: r is None), + ("shares.edit_shocker", (A, B), {"permissions": P, "limits": L, "cooldown": 5}, + "PATCH", f"/1/shares/links/{A}/{B}", data(None), lambda r: r is None), + ("shares.remove_shocker", (A, B), {}, "DELETE", f"/1/shares/links/{A}/{B}", data(None), lambda r: r is None), + ("shares.pause_shocker", (A, B, True), {}, "POST", f"/1/shares/links/{A}/{B}/pause", + data(4), lambda r: r is PauseReason.PUBLIC_SHARE), + ("shares.link_code", (A,), {}, "POST", f"/1/shares/code/{A}", data(None), lambda r: r is None), + ("shares.delete_code", (A,), {}, "DELETE", f"/1/shares/code/{A}", data(None), lambda r: r is None), + ("sessions.list", (), {}, "GET", "/1/sessions", [SESSION], lambda r: r[0].ip == "::1"), + ("sessions.get_current", (), {}, "GET", "/1/sessions/self", SESSION, lambda r: r.user_agent == "ua"), + ("sessions.delete", (A,), {}, "DELETE", f"/1/sessions/{A}", None, lambda r: r is None), + ("user_shares.get", (), {}, "GET", "/2/shares/user", + {"outgoing": [USER_SHARE], "incoming": []}, lambda r: r.outgoing[0].shares[0].limits.intensity == 50), + ("user_shares.create_invite", ([ShareInviteShocker(permissions=P, limits=L, id=UUID(B))],), {"user": A}, + "POST", "/2/shares/user/invites", A, lambda r: r == UUID(A)), + ("user_shares.list_outgoing_invites", (), {}, "GET", "/2/shares/user/invites/outgoing", + [INVITE], lambda r: r[0].owner.name == "user"), + ("user_shares.list_incoming_invites", (), {}, "GET", "/2/shares/user/invites/incoming", + [INVITE], lambda r: r[0].shockers[0].id == UUID(B)), + ("user_shares.accept_invite", (A,), {}, "POST", f"/2/shares/user/invites/incoming/{A}", + USER_SHARE, lambda r: r.name == "user"), + ("user_shares.delete_outgoing_invite", (A,), {}, "DELETE", f"/2/shares/user/invites/outgoing/{A}", + None, lambda r: r is None), + ("user_shares.deny_incoming_invite", (A,), {}, "DELETE", f"/2/shares/user/invites/incoming/{A}", + None, lambda r: r is None), + ("user_shares.bulk_pause_shockers", (A, [B], True), {}, "POST", f"/2/shares/user/{A}/shockers/pause", + {"affectedRecords": 1, "pauseStates": {B: 2}}, + lambda r: r.affected_records == 1 and r.pause_states[UUID(B)] is PauseReason.USER_SHARE), + ("user_shares.bulk_remove_shockers", (A, [B]), {}, "DELETE", f"/2/shares/user/{A}/shockers", + {"affectedRecords": 3}, lambda r: r == 3), + ("user_shares.bulk_update_shockers", (A, [B]), {"permissions": P, "limits": L}, + "PATCH", f"/2/shares/user/{A}/shockers", None, lambda r: r is None), +] # fmt: skip + +HUB_CASES: list[tuple[str, tuple, dict, str, str, Any, Any]] = [ + ("hub.self_info", (), {}, "GET", "/1/device/self", + data({"id": A, "name": "d", "shockers": [{"id": B, "rfId": 1, "model": "CaiXianlin"}]}), + lambda r: r.shockers[0].id == UUID(B)), + ("hub.assign_lcg", (), {"version": 2}, "GET", "/2/device/assignLCG", + {"host": "gw", "port": 443, "path": "/2/ws/hub", "country": "DE"}, lambda r: r.host == "gw"), + ("hub.pair", ("123456",), {}, "GET", "/1/device/pair/123456", data("devicetoken"), lambda r: r == "devicetoken"), + ("meta.online_stats", (), {}, "GET", "/1/public/stats", + data({"devicesOnline": 4}), lambda r: r.devices_online == 4), +] # fmt: skip + + +def _transport(seen: list[httpx.Request], body: Any) -> httpx.MockTransport: + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + if body is None: + return httpx.Response(200) + return httpx.Response(200, content=json.dumps(body), headers={"Content-Type": "application/json"}) + + return httpx.MockTransport(handler) + + +def _method(client: Any, name: str) -> Any: + resource, method = name.split(".") + return getattr(getattr(client, resource), method) + + +CASES = [(OpenShockClient, AsyncOpenShockClient, "api_token", c) for c in USER_CASES] + [ + (OpenShockHubClient, AsyncOpenShockHubClient, "hub_token", c) for c in HUB_CASES +] +IDS = [c[3][0] for c in CASES] + + +@pytest.mark.parametrize(("sync_cls", "async_cls", "token_arg", "case"), CASES, ids=IDS) +async def test_endpoint(sync_cls, async_cls, token_arg, case): + name, args, kwargs, http_method, path, body, check = case + + seen: list[httpx.Request] = [] + with sync_cls(**{token_arg: "tok"}, transport=_transport(seen, body)) as client: + assert check(_method(client, name)(*args, **kwargs)), "sync result" + assert (seen[0].method, seen[0].url.path) == (http_method, path) + + seen_async: list[httpx.Request] = [] + async with async_cls(**{token_arg: "tok"}, transport=_transport(seen_async, body)) as aclient: + assert check(await _method(aclient, name)(*args, **kwargs)), "async result" + assert (seen_async[0].method, seen_async[0].url.path) == (http_method, path) + assert seen_async[0].content == seen[0].content + + +def test_every_public_method_is_covered(): + """Fails when a resource method is added without a case above (or in test_rest.py).""" + covered = {c[0] for c in USER_CASES + HUB_CASES} | { + "shockers.list_own", + "shockers.list_shared", + "shockers.control", + "shockers.pause", + "shockers.delete", + "devices.gateway", + "devices.create", + "devices.get", + "devices.pair_code", + "account.create_token", + } + actual = set() + for client in (OpenShockClient(api_token="t"), OpenShockHubClient(hub_token="t")): + for resource_name, resource in vars(client).items(): + if resource_name.startswith("_"): + continue + for method_name, _ in inspect.getmembers(resource, inspect.ismethod): + if not method_name.startswith("_"): + actual.add(f"{resource_name}.{method_name}") + client.close() + assert actual - covered == set() diff --git a/tests/test_enums.py b/tests/test_enums.py new file mode 100644 index 0000000..d5fd04d --- /dev/null +++ b/tests/test_enums.py @@ -0,0 +1,63 @@ +"""Wire enums: string compatibility, integer wire form and forward compatibility.""" + +import json + +import pytest + +from openshock import Control, ControlType, PauseReason, PermissionType, ShockerModelType +from openshock.models.common import parse_pause_reason +from openshock.realtime.models import HubUpdateType, LiveResponseType + + +def test_members_equal_their_wire_string(): + assert ControlType.SHOCK == "Shock" + assert str(ControlType.SHOCK) == "Shock" + assert f"{ControlType.SHOCK}" == "Shock" + assert json.dumps({"type": ControlType.SHOCK}) == '{"type": "Shock"}' + + +def test_lookup_is_case_insensitive_and_accepts_integers(): + assert ControlType("vibrate") is ControlType.VIBRATE + assert ControlType("VIBRATE") is ControlType.VIBRATE + assert ControlType(0) is ControlType.STOP + assert ControlType(3) is ControlType.SOUND + assert ControlType("2") is ControlType.VIBRATE + assert HubUpdateType(4) is HubUpdateType.PAIRED + assert ShockerModelType("Petrainer998DR") is ShockerModelType.PETRAINER_998DR + + +def test_to_int_matches_backend_values(): + assert [t.to_int() for t in ControlType] == [0, 1, 2, 3] + assert PermissionType.PUBLICSHARES_EDIT.to_int() == 8 + + +def test_unknown_values_do_not_raise(): + value = PermissionType("future.permission") + assert value == "future.permission" + assert not value.is_known + assert PermissionType.SHOCKERS_USE.is_known + assert ControlType(99) == "99" + with pytest.raises(ValueError): + value.to_int() + + +def test_control_wire_forms(): + control = Control(id="abc", type="vibrate", intensity=10, duration=500) + assert control.to_dict()["type"] == "Vibrate" + assert control.to_signalr()["type"] == 2 + + +def test_pause_reason_parsing(): + assert parse_pause_reason(None) is PauseReason.NONE + assert parse_pause_reason(3) == PauseReason.SHOCKER | PauseReason.USER_SHARE + assert parse_pause_reason("5") == PauseReason.SHOCKER | PauseReason.PUBLIC_SHARE + assert parse_pause_reason("Shocker, UserShare") == PauseReason.SHOCKER | PauseReason.USER_SHARE + + +def test_live_response_type_parsing(): + assert LiveResponseType.parse("TPS") is LiveResponseType.TPS + assert LiveResponseType.parse("DeviceConnected") is LiveResponseType.DEVICE_CONNECTED + assert LiveResponseType.parse(1000) is LiveResponseType.PING + assert LiveResponseType.parse("Nonsense") is None + assert LiveResponseType.SHOCKER_PAUSED.is_rejection + assert not LiveResponseType.PING.is_rejection diff --git a/tests/test_live_control.py b/tests/test_live_control.py new file mode 100644 index 0000000..eb1c797 --- /dev/null +++ b/tests/test_live_control.py @@ -0,0 +1,251 @@ +"""LiveControlClient against a fake gateway: gateway lookup, ticking, ping/pong, retries.""" + +import asyncio +from uuid import UUID + +import httpx +import pytest + +from openshock import AsyncOpenShockClient, ControlType, HubGateway, HubNotFound, OpenShockAuthError +from openshock.realtime import ConnectionState, LiveControlClient, LiveResponseType, StepRetryPolicy + +from .fakes import TOKEN, FakeLiveGateway, eventually + +HUB = "11111111-1111-1111-1111-111111111111" +SHOCKER = "22222222-2222-2222-2222-222222222222" +OTHER = "44444444-4444-4444-4444-444444444444" + +FAST = StepRetryPolicy((0, 0.01)) + + +def make(server: FakeLiveGateway, token: str = TOKEN, **kwargs) -> LiveControlClient: + kwargs.setdefault("retry_policy", FAST) + kwargs.setdefault("gateway", server.ws_url) + return LiveControlClient(HUB, api_token=token, **kwargs) + + +async def test_connects_and_learns_tps(): + async with FakeLiveGateway(tps=8) as server: + live = make(server, tps=8, app_name="Tests", app_version="1.0") + events: list[str] = [] + live.on_hub_connected(lambda: events.append("hub")) + live.on_tps(lambda tps: events.append(f"tps:{tps}")) + + async with live: + await live.wait_connected(3) + await eventually(lambda: len(events) == 2) + assert live.tps == 8 + assert live.hub_connected + assert live.state is ConnectionState.CONNECTED + + request = server.requests[0] + assert request.path == f"/1/ws/live/{HUB}?tps=8" + assert request.headers["User-Agent"].startswith("OpenShock.SDK.Python.Live/") + + assert events == ["tps:8", "hub"] + assert live.tps == 0 and not live.hub_connected + + +async def test_frames_are_sent_each_tick_and_expire(): + async with FakeLiveGateway(tps=10) as server, make(server) as live: + await eventually(lambda: live.tps == 10) + live.intake_frame(SHOCKER, ControlType.VIBRATE, 40, hold_for=0.35) + live.intake_frame(OTHER, "shock", 5, hold_for=0.35) + await asyncio.sleep(0.8) + + frames = server.frames() + # ~3 ticks fit in the hold window at 10 TPS; allow for scheduling jitter. + assert 2 <= len(frames) <= 5 + assert frames[0] == [ + {"shocker": SHOCKER, "intensity": 40, "type": "Vibrate"}, + {"shocker": OTHER, "intensity": 5, "type": "Shock"}, + ] + # Nothing more is sent once the frames expired. + count = len(frames) + await asyncio.sleep(0.3) + assert len(server.frames()) == count + + +async def test_latest_value_wins_and_release_stops(): + async with FakeLiveGateway(tps=10) as server, make(server) as live: + await eventually(lambda: live.tps == 10) + live.intake_frame(SHOCKER, ControlType.VIBRATE, 10, hold_for=5) + live.intake_frame(SHOCKER, ControlType.VIBRATE, 20, hold_for=5) + await eventually(lambda: server.frames()) + assert server.frames()[0] == [{"shocker": SHOCKER, "intensity": 20, "type": "Vibrate"}] + + live.release(SHOCKER) + await asyncio.sleep(0.15) + count = len(server.frames()) + await asyncio.sleep(0.3) + assert len(server.frames()) == count + + +async def test_send_frame_is_immediate(): + async with FakeLiveGateway() as server, make(server) as live: + await live.wait_connected(3) + await live.send_frame(SHOCKER, ControlType.SOUND, 7) + await eventually(lambda: server.received) + assert server.received[0] == { + "requestType": "Frame", + "data": {"shocker": SHOCKER, "intensity": 7, "type": "Sound"}, + } + + +async def test_ping_is_answered_and_latency_reported(): + async with FakeLiveGateway() as server: + live = make(server) + latencies: list[tuple[int, int]] = [] + live.on_latency(lambda own, hub: latencies.append((own, hub))) + async with live: + await live.wait_connected(3) + await server.send("Ping", {"Timestamp": 123456}) + await eventually(lambda: latencies) + assert server.received[0] == {"requestType": "Pong", "data": {"Timestamp": 123456}} + assert latencies == [(12, 3)] + assert live.latency_ms == 12 and live.hub_latency_ms == 3 + + # A ping without data must still get a pong carrying data, or the gateway closes us. + await server.send("Ping", None) + await eventually(lambda: len(latencies) == 2) + assert live.is_connected + + +async def test_rejections_and_hub_state_events(): + async with FakeLiveGateway() as server: + live = make(server) + rejected: list[tuple[LiveResponseType, object]] = [] + hub_events: list[str] = [] + live.on_rejected(lambda kind, data: rejected.append((kind, data))) + live.on_hub_not_connected(lambda: hub_events.append("down")) + live.on_hub_connected(lambda: hub_events.append("up")) + async with live: + await eventually(lambda: hub_events == ["up"]) + await server.send("ShockerPaused") + await server.send("ShockerExclusive", "2024-06-01T12:00:00Z") + await server.send("SomethingFromTheFuture", {"x": 1}) + await server.send("DeviceNotConnected") + await eventually(lambda: hub_events == ["up", "down"]) + assert not live.hub_connected + await server.send("DeviceConnected") + await eventually(lambda: hub_events == ["up", "down", "up"]) + + assert rejected == [ + (LiveResponseType.SHOCKER_PAUSED, None), + (LiveResponseType.SHOCKER_EXCLUSIVE, "2024-06-01T12:00:00Z"), + ] + + +async def test_waits_for_an_offline_hub(): + async with FakeLiveGateway() as server: + server.reject_with = [ + (404, "Websocket.LiveControl.HubNotConnected"), + (412, "Websocket.LiveControl.HubLifetimeBusy"), + ] + live = make(server) + reconnecting: list[BaseException | None] = [] + live.on_reconnecting(reconnecting.append) + + await live.start() # does not raise: an offline hub is a reason to wait, not an error + assert live.state is not ConnectionState.CONNECTED + await live.wait_connected(3) + assert len(server.requests) == 3 + await eventually(lambda: reconnecting) + await live.stop() + + +async def test_unknown_hub_and_bad_token_are_fatal(): + async with FakeLiveGateway() as server: + server.reject_with = [(404, "Websocket.LiveControl.HubNotFound")] + with pytest.raises(HubNotFound): + await make(server).start() + with pytest.raises(OpenShockAuthError): + await make(server, token="wrong").start() + + +async def test_reconnects_and_resumes_sending(): + async with FakeLiveGateway(tps=10) as server, make(server) as live: + await eventually(lambda: live.tps == 10) + await server.drop_connections() + await eventually(lambda: len(server.requests) == 2 and live.tps == 10) + live.intake_frame(SHOCKER, ControlType.VIBRATE, 15, hold_for=1) + await eventually(lambda: server.frames()) + + +async def test_gateway_is_resolved_on_every_attempt(): + async with FakeLiveGateway() as server: + calls = 0 + + async def resolver() -> str: + nonlocal calls + calls += 1 + return server.ws_url + + async with make(server, gateway=None, gateway_resolver=resolver) as live: + await live.wait_connected(3) + await server.drop_connections() + await eventually(lambda: calls == 2) + await live.wait_connected(3) + assert live.gateway == server.ws_url + + +async def test_gateway_lookup_through_the_rest_api(): + gateway = {"host": "gw.example", "port": 8443, "pathPrefix": "/lcg/", "country": "DE"} + lookups: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + lookups.append(request) + return httpx.Response(200, json=gateway) + + client = AsyncOpenShockClient(api_token=TOKEN, transport=httpx.MockTransport(handler)) + live = LiveControlClient(HUB, client=client) + resolved = await live._resolve_gateway() + assert isinstance(resolved, HubGateway) + assert lookups[0].url.path == f"/2/devices/{HUB}/lcg" + assert live._url_for(resolved) == f"wss://gw.example:8443/lcg/1/ws/live/{HUB}" + assert live._headers["OpenShockToken"] == TOKEN + await client.aclose() + + +async def test_hub_offline_at_lookup_is_retried(): + async with FakeLiveGateway() as server: + answers = iter([404, 404, 200]) + + def handler(request: httpx.Request) -> httpx.Response: + if next(answers) == 404: + return httpx.Response( + 404, json={"type": "Device.NotOnline", "title": "Hub is not online", "status": 404} + ) + return httpx.Response(200, json={"host": "unused", "port": 443, "pathPrefix": "", "country": "DE"}) + + client = AsyncOpenShockClient(api_token=TOKEN, transport=httpx.MockTransport(handler)) + live = LiveControlClient(HUB, client=client, retry_policy=FAST) + # Point the socket at the fake while keeping the real REST lookup in the loop. + live._url_for = lambda gateway: f"{server.ws_url}/1/ws/live/{HUB}" # type: ignore[method-assign] + async with live: + await live.wait_connected(3) + await client.aclose() + + +def test_argument_validation(): + with pytest.raises(ValueError, match="not both"): + LiveControlClient(HUB, api_token="a", client=AsyncOpenShockClient(api_token="b")) + with pytest.raises(ValueError, match="tps"): + LiveControlClient(HUB, api_token="a", tps=50) + with pytest.raises(ValueError): + LiveControlClient(HUB) + with pytest.raises(ValueError): + LiveControlClient(HUB, headers={"Cookie": "openShockSession=abc"}) + assert ( + LiveControlClient(UUID(HUB), api_token="a", gateway="gw.example") + ._url_for("gw.example") + .startswith("wss://gw.example/1/ws/live/") + ) + + +async def test_intake_frame_validates(): + live = LiveControlClient(HUB, api_token="a", gateway="gw.example") + with pytest.raises(ValueError): + live.intake_frame(SHOCKER, ControlType.SHOCK, 101) + with pytest.raises(ValueError): + live.intake_frame(SHOCKER, "Zap", 10) diff --git a/tests/test_rest.py b/tests/test_rest.py new file mode 100644 index 0000000..929efed --- /dev/null +++ b/tests/test_rest.py @@ -0,0 +1,323 @@ +"""REST client behaviour against a mocked transport: requests sent, responses parsed, errors mapped.""" + +import json +from uuid import UUID + +import httpx +import pytest + +from openshock import ( + AsyncOpenShockClient, + Control, + ControlType, + HubOffline, + OpenShockApiError, + OpenShockAuthError, + OpenShockClient, + OpenShockNotFound, + OpenShockRateLimited, + PermissionType, + ShockerModelType, + ShockerNoPermission, + ShockerNotFoundOrNoAccess, + ShockerPaused, + TokenPermissionMissing, +) + +HUB = "11111111-1111-1111-1111-111111111111" +SHOCKER = "22222222-2222-2222-2222-222222222222" +USER = "33333333-3333-3333-3333-333333333333" + +OWN_SHOCKERS = { + "message": "", + "data": [ + { + "id": HUB, + "name": "My Hub", + "createdOn": "2024-06-01T12:00:00.1234567Z", + "shockers": [ + { + "id": SHOCKER, + "rfId": 1234, + "model": "CaiXianlin", + "name": "Leg", + "isPaused": False, + "createdOn": "2024-06-01T12:00:00Z", + "permissions": {"vibrate": True, "sound": True, "shock": False, "live": True}, + "limits": {"intensity": 50, "duration": None}, + } + ], + } + ], +} + + +def problem(type_: str, status: int, **extra): + body = {"type": type_, "title": "Nope", "status": status, "requestId": "req-1", **extra} + return httpx.Response(status, json=body, headers={"Content-Type": "application/problem+json"}) + + +class Recorder: + """Mock transport handler that records requests and answers from a route table.""" + + def __init__(self, routes): + self.routes = routes + self.requests: list[httpx.Request] = [] + + def __call__(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + response = self.routes[(request.method, request.url.path)] + return response(request) if callable(response) else response + + @property + def last(self) -> httpx.Request: + return self.requests[-1] + + def last_json(self): + return json.loads(self.last.content) + + +def sync_client(routes, **kwargs): + recorder = Recorder(routes) + return OpenShockClient(api_token="tok", transport=httpx.MockTransport(recorder), **kwargs), recorder + + +def async_client(routes, **kwargs): + recorder = Recorder(routes) + return AsyncOpenShockClient(api_token="tok", transport=httpx.MockTransport(recorder), **kwargs), recorder + + +class TestRequests: + def test_auth_and_user_agent_headers(self): + client, rec = sync_client( + {("GET", "/1/shockers/own"): httpx.Response(200, json=OWN_SHOCKERS)}, + app_name="MyApp", + app_version="1.2.3", + ) + client.shockers.list_own() + assert rec.last.headers["OpenShockToken"] == "tok" + ua = rec.last.headers["User-Agent"] + assert ua.startswith("OpenShock.SDK.Python/") + assert "MyApp 1.2.3" in ua + assert "httpx" in ua + + def test_list_own_is_typed(self): + client, _ = sync_client({("GET", "/1/shockers/own"): httpx.Response(200, json=OWN_SHOCKERS)}) + hubs = client.shockers.list_own() + assert len(hubs) == 1 + assert hubs[0].id == UUID(HUB) + assert hubs[0].created_on.microsecond == 123456 + shocker = hubs[0].shockers[0] + assert shocker.id == UUID(SHOCKER) + assert shocker.model is ShockerModelType.CAIXIANLIN + assert shocker.permissions is not None and shocker.permissions.live + assert shocker.limits is not None and shocker.limits.intensity == 50 + + def test_list_shared_is_typed(self): + payload = { + "data": [ + { + "id": USER, + "name": "Owner", + "image": "https://img", + "devices": [ + { + "id": HUB, + "name": "Their Hub", + "shockers": [ + { + "id": SHOCKER, + "name": "Arm", + "isPaused": True, + "permissions": {"vibrate": True, "sound": False, "shock": False}, + "limits": {"intensity": None, "duration": 5000}, + } + ], + } + ], + } + ] + } + client, _ = sync_client({("GET", "/1/shockers/shared"): httpx.Response(200, json=payload)}) + owners = client.shockers.list_shared() + shocker = owners[0].devices[0].shockers[0] + assert owners[0].name == "Owner" + assert shocker.is_paused + assert shocker.limits.duration == 5000 + + def test_control_body(self): + client, rec = sync_client({("POST", "/2/shockers/control"): httpx.Response(200, json={"message": "ok"})}) + result = client.shockers.control( + [ + Control(id=SHOCKER, type=ControlType.VIBRATE, intensity=25, duration=1000), + Control(id=SHOCKER, type="shock", intensity=5, duration=300, exclusive=True), + ], + custom_name="Bot", + ) + assert result is None + assert rec.last_json() == { + "shocks": [ + {"id": SHOCKER, "type": "Vibrate", "intensity": 25, "duration": 1000, "exclusive": False}, + {"id": SHOCKER, "type": "Shock", "intensity": 5, "duration": 300, "exclusive": True}, + ], + "customName": "Bot", + } + + def test_control_accepts_single_control_and_rejects_empty(self): + client, rec = sync_client({("POST", "/2/shockers/control"): httpx.Response(200, json={})}) + client.shockers.control(Control(id=SHOCKER, type="Sound", intensity=1, duration=300)) + assert len(rec.last_json()["shocks"]) == 1 + with pytest.raises(ValueError): + client.shockers.control([]) + + def test_pause_returns_state(self): + client, rec = sync_client( + {("POST", f"/1/shockers/{SHOCKER}/pause"): httpx.Response(200, json={"message": "", "data": True})} + ) + assert client.shockers.pause(SHOCKER, True) is True + assert rec.last_json() == {"pause": True} + + def test_gateway_v2(self): + client, _ = sync_client( + { + ("GET", f"/2/devices/{HUB}/lcg"): httpx.Response( + 200, json={"host": "de1-gateway.openshock.app", "port": 443, "pathPrefix": "", "country": "DE"} + ) + } + ) + gateway = client.devices.gateway(HUB) + assert gateway.ws_url == "wss://de1-gateway.openshock.app" + assert gateway.country == "DE" + + def test_create_device_returns_uuid_from_plain_text(self): + client, rec = sync_client({("POST", "/2/devices"): httpx.Response(201, text=HUB)}) + assert client.devices.create("New hub") == UUID(HUB) + assert rec.last_json() == {"name": "New hub"} + + def test_create_device_returns_uuid_from_json_string(self): + client, _ = sync_client({("POST", "/2/devices"): httpx.Response(201, json=HUB)}) + assert client.devices.create("New hub") == UUID(HUB) + + def test_get_device_token_optional(self): + data = {"id": HUB, "name": "Hub", "createdOn": "2024-06-01T12:00:00Z", "token": None} + client, _ = sync_client({("GET", f"/1/devices/{HUB}"): httpx.Response(200, json={"data": data})}) + assert client.devices.get(HUB).token is None + + def test_pair_code_is_string(self): + client, _ = sync_client({("GET", f"/1/devices/{HUB}/pair"): httpx.Response(200, json={"data": "123456"})}) + assert client.devices.pair_code(HUB) == "123456" + + def test_create_token(self): + created = { + "id": USER, + "name": "bot", + "token": "secret", + "createdAt": "2024-06-01T12:00:00Z", + "validUntil": None, + "lastUsed": "2024-06-01T12:00:00Z", + "permissions": ["shockers.use", "something.new"], + } + client, rec = sync_client({("POST", "/1/tokens"): httpx.Response(200, json=created)}) + token = client.account.create_token("bot", [PermissionType.SHOCKERS_USE, "shockers.pause"]) + assert token.token == "secret" + assert token.permissions[0] is PermissionType.SHOCKERS_USE + assert token.permissions[1] == "something.new" and not token.permissions[1].is_known + assert rec.last_json() == {"name": "bot", "permissions": ["shockers.use", "shockers.pause"]} + + def test_empty_body_is_ok(self): + client, _ = sync_client({("DELETE", f"/1/shockers/{SHOCKER}"): httpx.Response(200)}) + assert client.shockers.delete(SHOCKER) is None + + +class TestErrors: + @pytest.mark.parametrize( + ("type_", "status", "expected"), + [ + ("Shocker.Control.NotFound", 404, ShockerNotFoundOrNoAccess), + ("Shocker.Control.Paused", 412, ShockerPaused), + ("Shocker.Control.NoPermission", 403, ShockerNoPermission), + ], + ) + def test_control_problems(self, type_, status, expected): + client, _ = sync_client({("POST", "/2/shockers/control"): problem(type_, status, shockerId=SHOCKER)}) + with pytest.raises(expected) as info: + client.shockers.control([Control(id=SHOCKER, type="Shock", intensity=1, duration=300)]) + err = info.value + assert err.shocker_id == UUID(SHOCKER) + assert err.status_code == status + assert err.problem_type == type_ + assert err.problem is not None and err.problem.request_id == "req-1" + assert isinstance(err, OpenShockApiError) + + def test_specific_errors_keep_their_generic_base(self): + assert issubclass(ShockerNotFoundOrNoAccess, OpenShockNotFound) + assert issubclass(ShockerNoPermission, OpenShockAuthError) + assert issubclass(HubOffline, OpenShockNotFound) + + def test_hub_offline(self): + client, _ = sync_client({("GET", f"/2/devices/{HUB}/lcg"): problem("Device.NotOnline", 404)}) + with pytest.raises(HubOffline): + client.devices.gateway(HUB) + + def test_token_permission_missing(self): + client, _ = sync_client( + { + ("GET", "/1/devices"): problem( + "Authorization.Token.PermissionMissing", + 403, + requiredPermission="devices.edit", + grantedPermissions=["shockers.use"], + ) + } + ) + with pytest.raises(TokenPermissionMissing) as info: + client.devices.list() + assert info.value.required_permission == "devices.edit" + assert info.value.granted_permissions == ["shockers.use"] + + def test_status_fallbacks(self): + client, _ = sync_client( + { + ("GET", "/1/users/self"): httpx.Response(401, text=""), + ("GET", "/1/devices"): httpx.Response(404, text="gone"), + ("GET", "/1/tokens"): httpx.Response(429, text="slow down", headers={"Retry-After": "7"}), + ("GET", "/1"): httpx.Response(500, text="boom"), + } + ) + with pytest.raises(OpenShockAuthError): + client.account.user_self() + with pytest.raises(OpenShockNotFound): + client.devices.list() + with pytest.raises(OpenShockRateLimited) as info: + client.account.list_tokens() + assert info.value.retry_after == 7 + with pytest.raises(OpenShockApiError) as generic: + client.meta.backend_info() + assert generic.value.status_code == 500 + assert "boom" in str(generic.value) + + +class TestAsyncClient: + async def test_async_matches_sync(self): + client, rec = async_client({("GET", "/1/shockers/own"): httpx.Response(200, json=OWN_SHOCKERS)}) + async with client: + hubs = await client.shockers.list_own() + assert hubs[0].shockers[0].name == "Leg" + assert rec.last.headers["OpenShockToken"] == "tok" + + async def test_async_errors(self): + client, _ = async_client( + {("POST", "/2/shockers/control"): problem("Shocker.Control.Paused", 412, shockerId=SHOCKER)} + ) + async with client: + with pytest.raises(ShockerPaused): + await client.shockers.control([Control(id=SHOCKER, type="Shock", intensity=1, duration=300)]) + + def test_sync_and_async_expose_the_same_api(self): + sync, _ = sync_client({}) + asyn, _ = async_client({}) + for resource in ("meta", "account", "devices", "shockers", "shares", "sessions", "user_shares"): + sync_methods = {m for m in dir(getattr(sync, resource)) if not m.startswith("_")} + async_methods = {m for m in dir(getattr(asyn, resource)) if not m.startswith("_")} + assert sync_methods == async_methods, resource + sync.close() diff --git a/tests/test_user_hub.py b/tests/test_user_hub.py new file mode 100644 index 0000000..b26ca2e --- /dev/null +++ b/tests/test_user_hub.py @@ -0,0 +1,290 @@ +"""UserHubClient against a fake SignalR hub: handshake, events, invocations, reconnects.""" + +import asyncio +from uuid import UUID + +import pytest + +from openshock import Control, ControlType, HubInvocationError, OpenShockAuthError, OpenShockConnectionError +from openshock.realtime import ConnectionState, HubUpdateType, OtaUpdateProgressTask, StepRetryPolicy, UserHubClient + +from .fakes import TOKEN, FakeSignalRHub, eventually + +HUB = "11111111-1111-1111-1111-111111111111" +SHOCKER = "22222222-2222-2222-2222-222222222222" +USER = "33333333-3333-3333-3333-333333333333" + +FAST = StepRetryPolicy((0, 0.01)) + + +def make(server: FakeSignalRHub, token: str = TOKEN, **kwargs) -> UserHubClient: + kwargs.setdefault("retry_policy", FAST) + return UserHubClient(token, base_url=server.http_url, **kwargs) + + +async def test_connects_and_receives_welcome(): + async with FakeSignalRHub() as server: + hub = make(server, app_name="Tests", app_version="1.0") + welcomes: list[str] = [] + connected: list[bool] = [] + hub.on_welcome(welcomes.append) + hub.on_connected(lambda: connected.append(True)) + + async with hub: + assert hub.state is ConnectionState.CONNECTED + await eventually(lambda: welcomes) + assert hub.connection_id == welcomes[0] == "conn-1" + assert connected == [True] + + request = server.requests[0] + assert request.path == "/1/hubs/user" + assert request.headers["User-Agent"].startswith("OpenShock.SDK.Python.Hub/") + assert "Tests 1.0" in request.headers["User-Agent"] + + assert hub.state is ConnectionState.DISCONNECTED + + +async def test_typed_events(): + async with FakeSignalRHub() as server: + hub = make(server) + got: dict[str, tuple] = {} + hub.on_hub_status(lambda states: got.__setitem__("status", (states,))) + hub.on_hub_update(lambda hub_id, kind: got.__setitem__("update", (hub_id, kind))) + hub.on_ota_install_progress(lambda *args: got.__setitem__("ota", args)) + + @hub.on_log + async def on_log(sender, logs): + got["log"] = (sender, logs) + + async with hub: + await server.push("DeviceStatus", [{"device": HUB, "online": True, "firmwareVersion": "1.4.0"}]) + await server.push( + "Log", + { + "id": USER, + "name": "Someone", + "image": "https://img", + "customName": "Bot", + "connectionId": "abc", + "additionalItems": {"k": "v"}, + }, + [ + { + "shocker": {"id": SHOCKER, "name": "Leg"}, + "type": 2, + "intensity": 30, + "duration": 1000, + "executedAt": "2024-06-01T12:00:00.1234567Z", + "liveControl": True, + } + ], + ) + await server.push("DeviceUpdate", HUB, 2) + await server.push("OtaInstallProgress", HUB, 7, 4, 0.5) + await eventually(lambda: len(got) == 4) + + (states,) = got["status"] + assert states[0].device == UUID(HUB) and states[0].online and states[0].firmware_version == "1.4.0" + + sender, logs = got["log"] + assert sender.custom_name == "Bot" and sender.connection_id == "abc" and sender.additional_items == {"k": "v"} + assert logs[0].type is ControlType.VIBRATE + assert logs[0].shocker.name == "Leg" and logs[0].live_control + + assert got["update"] == (UUID(HUB), HubUpdateType.SHOCKER_UPDATED) + assert got["ota"] == (UUID(HUB), 7, OtaUpdateProgressTask.FLASHING_APPLICATION, 0.5) + + +async def test_raw_events_for_unknown_methods(): + async with FakeSignalRHub() as server: + hub = make(server) + seen: list[tuple] = [] + unsubscribe = hub.on("BrandNewEvent", lambda *args: seen.append(args)) + async with hub: + await server.push("BrandNewEvent", 1, "two") + await eventually(lambda: seen) + unsubscribe() + await server.push("BrandNewEvent", 3) + await server.push("DeviceUpdate", HUB, 0) + await asyncio.sleep(0.05) + assert seen == [(1, "two")] + + +async def test_control_sends_integers_and_waits_for_completion(): + async with FakeSignalRHub() as server: + async with make(server) as hub: + await hub.control( + [Control(id=SHOCKER, type=ControlType.SHOCK, intensity=10, duration=300, exclusive=True)], + custom_name="Bot", + ) + await hub.reboot(HUB) + + control, reboot = server.invocations + assert control["target"] == "ControlV2" + assert control["arguments"] == [ + [{"id": SHOCKER, "type": 1, "intensity": 10, "duration": 300, "exclusive": True}], + "Bot", + ] + assert reboot["target"] == "Reboot" and reboot["arguments"] == [HUB] + + +async def test_hub_error_is_raised(): + async with FakeSignalRHub() as server: + server.fail_targets.add("EmergencyStop") + async with make(server) as hub: + with pytest.raises(HubInvocationError, match="EmergencyStop failed"): + await hub.emergency_stop(HUB) + + +async def test_bad_token_fails_start(): + async with FakeSignalRHub() as server: + hub = make(server, token="wrong") + with pytest.raises(OpenShockAuthError): + await hub.start() + assert hub.state is ConnectionState.DISCONNECTED + + +async def test_handshake_error_fails_start(): + async with FakeSignalRHub() as server: + server.handshake_error = "Unsupported protocol" + with pytest.raises(OpenShockConnectionError, match="Unsupported protocol"): + await make(server).start() + + +async def test_unreachable_server_fails_start(): + hub = UserHubClient(TOKEN, base_url="http://127.0.0.1:1") + with pytest.raises(OpenShockConnectionError): + await hub.start() + + +async def test_reconnects_after_connection_loss(): + async with FakeSignalRHub() as server: + hub = make(server) + events: list[str] = [] + hub.on_connected(lambda: events.append("connected")) + hub.on_reconnecting(lambda error: events.append("reconnecting")) + hub.on_reconnected(lambda: events.append("reconnected")) + hub.on_closed(lambda error: events.append(f"closed:{error}")) + + async with hub: + await eventually(lambda: hub.connection_id == "conn-1") + await server.drop_connections() + await eventually(lambda: "reconnected" in events) + await eventually(lambda: hub.connection_id == "conn-2") + assert hub.state is ConnectionState.CONNECTED + # The new connection is fully usable. + await hub.control(Control(id=SHOCKER, type="Vibrate", intensity=1, duration=300)) + + assert events == ["connected", "reconnecting", "reconnected", "closed:None"] + + +async def test_pending_invocation_fails_when_connection_drops(): + async with FakeSignalRHub() as server, make(server) as hub: + original = server._on_message + + async def swallow(connection, message): + if message.get("target") == "Reboot": + await server.drop_connections() + return + await original(connection, message) + + server._on_message = swallow # type: ignore[method-assign] + with pytest.raises(OpenShockConnectionError): + await hub.reboot(HUB) + + +async def test_revoked_token_ends_the_session(): + async with FakeSignalRHub() as server: + hub = make(server) + closed: list[BaseException | None] = [] + hub.on_closed(closed.append) + await hub.start() + hub._headers["OpenShockToken"] = "revoked" # the next reconnect is refused + await server.drop_connections() + with pytest.raises(OpenShockAuthError): + await asyncio.wait_for(hub.wait_closed(), 3) + await eventually(lambda: closed) + assert isinstance(closed[0], OpenShockAuthError) + assert hub.state is ConnectionState.DISCONNECTED + await hub.stop() + + +async def test_server_close_without_reconnect_ends_the_session(): + async with FakeSignalRHub() as server: + hub = make(server) + await hub.start() + await server.send_close("Server shutting down", allow_reconnect=False) + with pytest.raises(OpenShockConnectionError, match="Server shutting down"): + await asyncio.wait_for(hub.wait_closed(), 3) + await hub.stop() + + +async def test_server_close_with_reconnect_reconnects(): + async with FakeSignalRHub() as server, make(server) as hub: + await eventually(lambda: hub.connection_id == "conn-1") + await server.send_close(None, allow_reconnect=True) + await eventually(lambda: hub.connection_id == "conn-2") + + +async def test_handler_may_stop_the_client(): + async with FakeSignalRHub() as server: + hub = make(server) + + @hub.on_welcome + async def stop_on_welcome(_connection_id: str) -> None: + await hub.stop() + + await hub.start() + await asyncio.wait_for(hub.wait_closed(), 3) + assert hub.state is ConnectionState.DISCONNECTED + + +async def test_failing_handler_does_not_break_the_connection(): + async with FakeSignalRHub() as server: + hub = make(server) + seen: list[UUID] = [] + + def boom(hub_id: UUID, kind: HubUpdateType) -> None: + raise RuntimeError("handler bug") + + hub.on_hub_update(boom) + hub.on_hub_update(lambda hub_id, kind: seen.append(hub_id)) + async with hub: + await server.push("DeviceUpdate", HUB, 0) + await server.push("DeviceUpdate", "not-a-uuid", 0) # unparseable: logged and skipped + await server.push("DeviceUpdate", HUB, 1) + await eventually(lambda: len(seen) == 2) + assert hub.is_connected + + +async def test_requires_credentials(): + with pytest.raises(ValueError): + UserHubClient() + UserHubClient(headers={"Cookie": "openShockSession=abc"}) + + +async def test_unparseable_rejection_is_still_reported_as_auth_error(): + """Production sits behind a proxy whose 401 to an upgrade request has a truncated chunked body.""" + + async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + request = (await reader.readuntil(b"\r\n\r\n")).decode().lower() + if "upgrade: websocket" in request: + writer.write(b"HTTP/1.1 401 Unauthorized\r\nTransfer-Encoding: chunked\r\n\r\n") + else: + body = b'{"type":"Authentication.CookieMissingOrInvalid","title":"Unauthorized","status":401}' + writer.write( + b"HTTP/1.1 401 Unauthorized\r\nContent-Type: application/problem+json\r\n" + b"Connection: close\r\nContent-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body + ) + await writer.drain() + writer.close() + + server = await asyncio.start_server(handle, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + try: + with pytest.raises(OpenShockAuthError) as info: + await UserHubClient("bad", base_url=f"http://127.0.0.1:{port}").start() + assert info.value.problem_type == "Authentication.CookieMissingOrInvalid" + finally: + server.close() + await server.wait_closed() From 5e58df756937220f07e2e021f9891d434390af7b Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 14:44:31 +0100 Subject: [PATCH 2/9] docs: document pure-Python install --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 605062a..f2289a6 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,23 @@ pip install openshock # REST client only pip install "openshock[realtime]" # + SignalR user hub and live control ``` +### Pure-Python install + +The base install is pure Python. The `realtime` extra pulls in `websockets`, whose wheels +include an optional C accelerator. To install without any compiled code, build it from +source with the extension switched off (no compiler needed): + +```bash +BUILD_EXTENSION=no pip install --no-binary websockets "openshock[realtime]" +``` + +On Windows PowerShell: + +```powershell +$env:BUILD_EXTENSION = "no" +pip install --no-binary websockets "openshock[realtime]" +``` + ## Quick start ```python From 7324989b16a95bf4c6252511bf6c36f4029891e7 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 15:23:23 +0100 Subject: [PATCH 3/9] feat!: generate the REST client from the OpenAPI document Replace the hand-written REST resources and models with a client generated by openapi-python-client from a committed snapshot of the backend's OpenAPI document (scripts/generate.py, checked in CI). BREAKING: REST calls now go through openshock.rest.api.*, Python 3.10 is no longer supported, and httpx is replaced by httpx2. --- .github/workflows/ci.yml | 8 +- README.md | 151 +- examples/README.md | 4 +- examples/async_control/README.md | 2 +- examples/async_control/main.py | 31 +- examples/live_control/main.py | 14 +- examples/rest_quickstart/README.md | 2 +- examples/rest_quickstart/main.py | 19 +- openapi/generator-config.yaml | 6 + openapi/openapi.json | 11651 ++++++++++++++++ openshock/__init__.py | 63 +- openshock/_async/__init__.py | 0 openshock/_async/client.py | 191 - openshock/_async/resources/__init__.py | 0 openshock/_async/resources/account.py | 77 - openshock/_async/resources/devices.py | 80 - openshock/_async/resources/hub.py | 34 - openshock/_async/resources/meta.py | 24 - openshock/_async/resources/sessions.py | 32 - openshock/_async/resources/shares.py | 119 - openshock/_async/resources/shockers.py | 225 - openshock/_async/resources/user_shares.py | 123 - openshock/_core.py | 89 +- openshock/_sync/__init__.py | 0 openshock/_sync/client.py | 192 - openshock/_sync/resources/__init__.py | 0 openshock/_sync/resources/account.py | 78 - openshock/_sync/resources/devices.py | 81 - openshock/_sync/resources/hub.py | 35 - openshock/_sync/resources/meta.py | 25 - openshock/_sync/resources/sessions.py | 33 - openshock/_sync/resources/shares.py | 120 - openshock/_sync/resources/shockers.py | 226 - openshock/_sync/resources/user_shares.py | 124 - openshock/auth.py | 44 - openshock/client.py | 159 +- openshock/exceptions.py | 77 +- openshock/models/__init__.py | 48 - openshock/models/account.py | 81 - openshock/models/common.py | 186 - openshock/models/device.py | 179 - openshock/models/meta.py | 79 - openshock/models/session.py | 37 - openshock/models/share.py | 199 - openshock/models/shocker.py | 287 - openshock/realtime/__init__.py | 1 + openshock/realtime/_transport.py | 15 +- openshock/realtime/_wire.py | 81 + openshock/realtime/live_control.py | 55 +- openshock/realtime/models.py | 8 +- openshock/realtime/user_hub.py | 22 +- openshock/resources/__init__.py | 18 - openshock/rest/__init__.py | 9 + openshock/rest/api/__init__.py | 2 + openshock/rest/api/account/__init__.py | 2 + .../rest/api/account/account_activate.py | 165 + .../api/account/account_check_username.py | 159 + .../rest/api/account/account_email_verify.py | 170 + .../account/account_email_verify_legacy.py | 170 + .../rest/api/account/account_login_v2.py | 172 + openshock/rest/api/account/account_logout.py | 80 + .../account_password_reset_check_valid.py | 177 + .../account_password_reset_complete.py | 198 + .../account_password_reset_initiate_v2.py | 165 + .../api/account/account_resend_activation.py | 154 + .../rest/api/account/account_sign_up_v2.py | 174 + .../authenticated_account_change_email.py | 189 + .../authenticated_account_change_password.py | 170 + .../authenticated_account_change_username.py | 175 + .../authenticated_account_deactivate.py | 133 + .../authenticated_account_get_audit_log.py | 226 + .../account/authenticated_account_get_self.py | 125 + ...ticated_account_list_o_auth_connections.py | 134 + ...icated_account_remove_o_auth_connection.py | 158 + openshock/rest/api/admin/__init__.py | 2 + .../admin_add_email_provider_blacklist.py | 102 + .../api/admin/admin_add_username_blacklist.py | 102 + openshock/rest/api/admin/admin_add_webhook.py | 167 + .../admin/admin_bulk_cancel_email_outbox.py | 177 + .../admin/admin_bulk_delete_email_outbox.py | 173 + .../admin/admin_bulk_requeue_email_outbox.py | 177 + .../api/admin/admin_cancel_email_outbox.py | 172 + .../rest/api/admin/admin_configuration_add.py | 174 + .../api/admin/admin_configuration_delete.py | 169 + .../api/admin/admin_configuration_list.py | 138 + .../api/admin/admin_configuration_update.py | 191 + .../admin/admin_create_automation_token.py | 161 + .../rest/api/admin/admin_deactivate_user.py | 127 + .../rest/api/admin/admin_delete_api_token.py | 103 + .../admin/admin_delete_automation_token.py | 168 + .../api/admin/admin_delete_email_outbox.py | 167 + openshock/rest/api/admin/admin_delete_user.py | 118 + .../api/admin/admin_get_admin_audit_log.py | 263 + .../rest/api/admin/admin_get_email_outbox.py | 218 + .../api/admin/admin_get_email_outbox_stats.py | 133 + .../api/admin/admin_get_online_devices.py | 135 + .../api/admin/admin_get_online_gateways.py | 138 + .../rest/api/admin/admin_get_user_by_id.py | 167 + openshock/rest/api/admin/admin_get_users.py | 210 + .../api/admin/admin_list_automation_tokens.py | 134 + .../admin_list_email_provider_blacklist.py | 162 + .../admin/admin_list_username_blacklist.py | 162 + .../rest/api/admin/admin_list_webhooks.py | 138 + openshock/rest/api/admin/admin_modify_user.py | 121 + .../api/admin/admin_patch_automation_token.py | 184 + .../rest/api/admin/admin_reactivate_user.py | 118 + .../admin_remove_email_provider_blacklist.py | 155 + .../admin/admin_remove_username_blacklist.py | 155 + .../rest/api/admin/admin_remove_webhook.py | 163 + .../api/admin/admin_requeue_email_outbox.py | 172 + .../admin/admin_rotate_automation_token.py | 163 + .../rest/api/admin/admin_send_test_email.py | 191 + .../rest/api/admin/admin_set_user_email.py | 184 + .../rest/api/admin/admin_set_user_name.py | 192 + .../rest/api/admin/admin_set_user_password.py | 192 + openshock/rest/api/api_tokens/__init__.py | 2 + .../api_tokens/token_delete_delete_token.py | 167 + .../api/api_tokens/tokens_create_token_v2.py | 161 + .../api/api_tokens/tokens_edit_token_v2.py | 182 + .../api_tokens/tokens_get_token_by_id_v2.py | 163 + .../api/api_tokens/tokens_list_tokens_v2.py | 132 + .../api/api_tokens/tokens_report_tokens.py | 104 + .../tokens_self_get_self_token_v2.py | 125 + .../api/api_tokens/tokens_set_token_paused.py | 184 + openshock/rest/api/hub_endpoints/__init__.py | 2 + .../device_get_live_control_gateway_v2.py | 172 + .../rest/api/hub_endpoints/device_get_self.py | 129 + .../rest/api/hub_endpoints/device_pair.py | 162 + openshock/rest/api/hub_management/__init__.py | 2 + .../devices_create_device_v2.py | 157 + .../api/hub_management/devices_edit_device.py | 182 + .../devices_get_device_by_id.py | 163 + ...evices_get_live_control_gateway_info_v2.py | 167 + .../hub_management/devices_get_pair_code.py | 163 + .../hub_management/devices_get_shockers.py | 163 + .../hub_management/devices_list_devices.py | 129 + .../devices_ota_get_ota_update_history.py | 165 + .../devices_regenerate_device_token.py | 165 + .../hub_management/devices_remove_device.py | 161 + openshock/rest/api/integrations/__init__.py | 2 + .../integrations_get_control_stat_changes.py | 195 + openshock/rest/api/meta/__init__.py | 2 + .../public_get_online_devices_statistics.py | 129 + .../rest/api/meta/version_get_backend_info.py | 129 + .../api/public_shocker_shares/__init__.py | 2 + .../public_get_public_share.py | 163 + .../share_links_add_shocker.py | 182 + .../share_links_create_public_share.py | 161 + .../share_links_delete_public_share.py | 163 + .../share_links_edit_shocker.py | 200 + .../public_shocker_shares/share_links_list.py | 131 + .../share_links_pause_shocker.py | 202 + .../share_links_remove_shocker.py | 181 + openshock/rest/api/sessions/__init__.py | 2 + .../api/sessions/sessions_delete_session.py | 157 + .../api/sessions/sessions_get_self_session.py | 127 + .../api/sessions/sessions_list_sessions.py | 130 + openshock/rest/api/shocker_shares/__init__.py | 2 + .../shares_delete_share_code.py | 163 + .../shocker_shares/shares_link_share_code.py | 172 + openshock/rest/api/shockers/__init__.py | 2 + .../rest/api/shockers/shocker_edit_shocker.py | 184 + .../shockers/shocker_get_all_shocker_logs.py | 249 + .../api/shockers/shocker_get_shocker_by_id.py | 163 + .../api/shockers/shocker_get_shocker_logs.py | 199 + .../api/shockers/shocker_get_user_shares.py | 163 + .../shockers/shocker_list_shared_shockers.py | 131 + .../api/shockers/shocker_list_shockers.py | 131 + .../api/shockers/shocker_pause_shocker.py | 184 + .../api/shockers/shocker_register_shocker.py | 172 + .../api/shockers/shocker_remove_shocker.py | 163 + .../rest/api/shockers/shocker_send_control.py | 177 + .../shocker_shocker_share_code_create.py | 184 + .../shocker_shocker_share_code_list.py | 163 + .../shocker_shocker_share_code_pause.py | 198 + .../shocker_shocker_share_code_update.py | 196 + .../shockers/shocker_shocker_share_remove.py | 175 + .../rest/api/user_shocker_shares/__init__.py | 2 + ...r_shares_bulk_pause_user_share_shockers.py | 174 + ..._shares_bulk_remove_user_share_shockers.py | 176 + ..._shares_bulk_user_share_shockers_update.py | 182 + .../user_shares_create_share_invite.py | 168 + .../user_shares_delete_outgoing_invite.py | 157 + .../user_shares_deny_incoming_invite.py | 157 + .../user_shares_get_incoming_invites_list.py | 130 + .../user_shares_get_outgoing_invites_list.py | 130 + .../user_shares_get_shares_by_users.py | 121 + .../user_shares_redeem_invite.py | 163 + openshock/rest/api/users/__init__.py | 2 + openshock/rest/api/users/users_get_by_name.py | 158 + openshock/rest/api/users/users_get_self.py | 129 + .../api/users/users_get_self_control_stats.py | 204 + openshock/rest/client.py | 269 + openshock/rest/errors.py | 17 + openshock/rest/models/__init__.py | 394 + .../add_email_provider_blacklist_dto.py | 62 + .../rest/models/add_username_blacklist_dto.py | 72 + openshock/rest/models/add_webhook_dto.py | 70 + .../models/admin_online_device_response.py | 216 + .../models/admin_online_gateway_response.py | 146 + openshock/rest/models/admin_user_view.py | 324 + .../rest/models/admin_user_view_api_token.py | 156 + .../models/admin_user_view_email_change.py | 105 + openshock/rest/models/admin_user_view_hub.py | 102 + .../models/admin_user_view_name_change.py | 79 + .../models/admin_user_view_password_reset.py | 97 + .../rest/models/admin_user_view_shocker.py | 80 + ...admin_user_view_user_activation_request.py | 71 + .../admin_user_view_user_deactivation.py | 102 + .../rest/models/admin_user_view_user_ref.py | 71 + openshock/rest/models/admin_users_view.py | 304 + openshock/rest/models/audit_action.py | 26 + .../rest/models/audit_log_entry_response.py | 432 + ...t_metadata_account_deactivated_metadata.py | 81 + ...metadata_account_deactivated_metadata_t.py | 9 + ...dit_metadata_api_token_created_metadata.py | 98 + ...t_metadata_api_token_created_metadata_t.py | 9 + ...dit_metadata_api_token_deleted_metadata.py | 90 + ...t_metadata_api_token_deleted_metadata_t.py | 9 + ...adata_automation_token_created_metadata.py | 120 + ...ata_automation_token_created_metadata_t.py | 9 + ...adata_automation_token_deleted_metadata.py | 99 + ...ata_automation_token_deleted_metadata_t.py | 9 + ...adata_automation_token_rotated_metadata.py | 90 + ...ata_automation_token_rotated_metadata_t.py | 9 + ...adata_automation_token_updated_metadata.py | 121 + ...ata_automation_token_updated_metadata_t.py | 9 + ...metadata_automation_token_used_metadata.py | 100 + ...tadata_automation_token_used_metadata_t.py | 9 + ...etadata_email_change_requested_metadata.py | 81 + ...adata_email_change_requested_metadata_t.py | 9 + .../audit_metadata_email_changed_metadata.py | 89 + ...audit_metadata_email_changed_metadata_t.py | 9 + .../models/audit_metadata_login_metadata.py | 82 + .../models/audit_metadata_login_metadata_t.py | 9 + ...udit_metadata_o_auth_connected_metadata.py | 81 + ...it_metadata_o_auth_connected_metadata_t.py | 9 + ...t_metadata_o_auth_disconnected_metadata.py | 81 + ...metadata_o_auth_disconnected_metadata_t.py | 9 + ...udit_metadata_username_changed_metadata.py | 89 + ...it_metadata_username_changed_metadata_t.py | 9 + openshock/rest/models/automation_token_dto.py | 197 + .../rest/models/automation_token_type.py | 11 + .../rest/models/backend_info_response.py | 135 + openshock/rest/models/basic_user_info.py | 79 + ...bulk_user_share_shockers_update_request.py | 95 + openshock/rest/models/change_email_request.py | 70 + .../rest/models/change_password_request.py | 70 + .../rest/models/change_username_request.py | 62 + .../models/configuration_add_item_request.py | 91 + .../rest/models/configuration_item_dto.py | 106 + .../configuration_update_item_request.py | 110 + .../rest/models/configuration_value_type.py | 13 + openshock/rest/models/control.py | 99 + openshock/rest/models/control_limit_mode.py | 10 + .../rest/models/control_log_sender_light.py | 93 + openshock/rest/models/control_request.py | 98 + .../models/control_stat_changes_request.py | 105 + .../models/control_stat_changes_response.py | 85 + openshock/rest/models/control_stat_totals.py | 105 + .../rest/models/control_stats_response.py | 78 + openshock/rest/models/control_type.py | 12 + .../models/create_automation_token_dto.py | 112 + openshock/rest/models/create_share_request.py | 109 + .../rest/models/create_token_request_v2.py | 127 + .../models/created_automation_token_dto.py | 166 + openshock/rest/models/daily_control_stats.py | 85 + openshock/rest/models/device_response.py | 80 + openshock/rest/models/device_self_response.py | 93 + .../models/device_with_shockers_response.py | 102 + .../rest/models/device_with_token_response.py | 95 + .../rest/models/duration_limit_settings.py | 90 + .../rest/models/edit_token_request_v2.py | 95 + .../rest/models/email_outbox_bulk_request.py | 72 + .../models/email_outbox_bulk_result_dto.py | 72 + .../rest/models/email_outbox_message_dto.py | 226 + .../email_outbox_message_dto_payload.py | 46 + .../rest/models/email_outbox_stats_dto.py | 103 + .../models/email_provider_blacklist_dto.py | 80 + openshock/rest/models/email_status.py | 13 + openshock/rest/models/email_type.py | 12 + openshock/rest/models/given_control_stats.py | 94 + openshock/rest/models/hub_create_request.py | 62 + openshock/rest/models/hub_edit_request.py | 62 + .../rest/models/intensity_limit_settings.py | 80 + openshock/rest/models/lcg_node_response_v2.py | 86 + openshock/rest/models/lcg_response_v2.py | 87 + ...f_array_of_admin_online_device_response.py | 84 + ...ta_response_of_array_of_device_response.py | 84 + ..._array_of_device_with_shockers_response.py | 84 + ...acy_data_response_of_array_of_log_entry.py | 84 + ...e_of_array_of_own_public_share_response.py | 84 + ...onse_of_array_of_owner_shocker_response.py | 84 + ...ta_response_of_array_of_share_code_info.py | 84 + ...cy_data_response_of_array_of_share_info.py | 84 + ...a_response_of_array_of_shocker_response.py | 84 + ..._data_response_of_backend_info_response.py | 76 + ...y_data_response_of_device_self_response.py | 76 + ..._response_of_device_with_token_response.py | 76 + .../models/legacy_data_response_of_guid.py | 71 + ...e_of_i_read_only_collection_of_ota_item.py | 84 + ...a_response_of_legacy_user_self_response.py | 77 + .../legacy_data_response_of_pause_reason.py | 78 + ..._data_response_of_public_share_response.py | 76 + ...cy_data_response_of_shocker_with_device.py | 76 + .../legacy_data_response_of_stats_response.py | 76 + .../models/legacy_data_response_ofboolean.py | 70 + .../models/legacy_data_response_ofstring.py | 70 + .../rest/models/legacy_empty_response.py | 73 + .../rest/models/legacy_user_self_response.py | 122 + openshock/rest/models/log_entry.py | 120 + openshock/rest/models/log_entry_with_hub.py | 152 + .../rest/models/login_session_response.py | 203 + openshock/rest/models/login_v2.py | 78 + openshock/rest/models/login_v2_ok_response.py | 113 + openshock/rest/models/match_type_enum.py | 10 + openshock/rest/models/minimal_shocker.py | 81 + openshock/rest/models/new_shocker.py | 89 + .../rest/models/o_auth_connection_response.py | 93 + openshock/rest/models/open_shock_problem.py | 194 + openshock/rest/models/ota_item.py | 103 + openshock/rest/models/ota_update_status.py | 13 + .../rest/models/own_public_share_response.py | 112 + .../rest/models/owner_shocker_response.py | 101 + ...aged_result_of_audit_log_entry_response.py | 112 + .../paged_result_of_log_entry_with_hub.py | 112 + .../models/paginated_of_admin_users_view.py | 100 + .../paginated_of_email_outbox_message_dto.py | 100 + .../rest/models/password_hashing_algorithm.py | 11 + .../models/password_reset_process_data.py | 62 + .../rest/models/password_reset_request_v2.py | 70 + .../rest/models/patch_automation_token_dto.py | 154 + openshock/rest/models/pause_request.py | 62 + .../pause_user_share_shockers_request.py | 79 + .../pause_user_share_shockers_response.py | 76 + ...er_share_shockers_response_pause_states.py | 46 + openshock/rest/models/permission_type.py | 17 + openshock/rest/models/problem_details.py | 154 + openshock/rest/models/public_share_create.py | 95 + openshock/rest/models/public_share_device.py | 93 + .../rest/models/public_share_edit_shocker.py | 100 + .../rest/models/public_share_response.py | 149 + openshock/rest/models/public_share_shocker.py | 111 + .../rest/models/received_control_stats.py | 130 + .../models/remove_user_shares_response.py | 62 + .../rest/models/report_tokens_request.py | 70 + openshock/rest/models/role_type.py | 12 + openshock/rest/models/send_test_email_dto.py | 98 + .../rest/models/set_token_paused_request.py | 62 + .../models/set_user_email_request_body.py | 62 + .../rest/models/set_user_name_request_body.py | 62 + .../models/set_user_password_request_body.py | 62 + openshock/rest/models/share_code_info.py | 72 + openshock/rest/models/share_info.py | 105 + .../rest/models/share_invite_base_details.py | 131 + openshock/rest/models/shared_device.py | 93 + openshock/rest/models/shared_shocker.py | 103 + .../rest/models/shocker_control_settings.py | 87 + .../rest/models/shocker_control_stats.py | 117 + openshock/rest/models/shocker_limits.py | 83 + openshock/rest/models/shocker_model_type.py | 12 + .../rest/models/shocker_perm_limit_pair.py | 78 + .../models/shocker_perm_limit_pair_with_id.py | 97 + ...hocker_perm_limit_pair_with_id_and_name.py | 105 + openshock/rest/models/shocker_permissions.py | 89 + openshock/rest/models/shocker_response.py | 106 + openshock/rest/models/shocker_with_device.py | 114 + openshock/rest/models/sign_up_v2.py | 86 + openshock/rest/models/sort_direction.py | 10 + openshock/rest/models/stats_response.py | 62 + .../rest/models/token_created_response_v2.py | 171 + .../rest/models/token_paused_response.py | 62 + openshock/rest/models/token_response_v2.py | 163 + .../rest/models/user_control_stat_totals.py | 102 + openshock/rest/models/user_control_stats.py | 132 + .../rest/models/user_name_blacklist_dto.py | 90 + openshock/rest/models/user_patch_dto.py | 94 + openshock/rest/models/user_self_response.py | 113 + openshock/rest/models/user_share_info.py | 120 + .../rest/models/username_availability.py | 11 + .../rest/models/username_check_response.py | 103 + openshock/rest/models/username_error.py | 72 + openshock/rest/models/username_error_type.py | 14 + openshock/rest/models/v2_user_shares.py | 92 + .../rest/models/v2_user_shares_list_item.py | 101 + openshock/rest/models/webhook_dto.py | 88 + openshock/rest/types.py | 55 + pyproject.toml | 28 +- scripts/generate.py | 136 + scripts/unasync.py | 81 - tests/test_client.py | 298 +- tests/test_endpoints.py | 228 - tests/test_enums.py | 63 - tests/test_generated.py | 70 + tests/test_live_control.py | 29 +- tests/test_models.py | 247 - tests/test_rest.py | 323 - tests/test_user_hub.py | 7 +- 398 files changed, 50354 insertions(+), 4291 deletions(-) create mode 100644 openapi/generator-config.yaml create mode 100644 openapi/openapi.json delete mode 100644 openshock/_async/__init__.py delete mode 100644 openshock/_async/client.py delete mode 100644 openshock/_async/resources/__init__.py delete mode 100644 openshock/_async/resources/account.py delete mode 100644 openshock/_async/resources/devices.py delete mode 100644 openshock/_async/resources/hub.py delete mode 100644 openshock/_async/resources/meta.py delete mode 100644 openshock/_async/resources/sessions.py delete mode 100644 openshock/_async/resources/shares.py delete mode 100644 openshock/_async/resources/shockers.py delete mode 100644 openshock/_async/resources/user_shares.py delete mode 100644 openshock/_sync/__init__.py delete mode 100644 openshock/_sync/client.py delete mode 100644 openshock/_sync/resources/__init__.py delete mode 100644 openshock/_sync/resources/account.py delete mode 100644 openshock/_sync/resources/devices.py delete mode 100644 openshock/_sync/resources/hub.py delete mode 100644 openshock/_sync/resources/meta.py delete mode 100644 openshock/_sync/resources/sessions.py delete mode 100644 openshock/_sync/resources/shares.py delete mode 100644 openshock/_sync/resources/shockers.py delete mode 100644 openshock/_sync/resources/user_shares.py delete mode 100644 openshock/auth.py delete mode 100644 openshock/models/__init__.py delete mode 100644 openshock/models/account.py delete mode 100644 openshock/models/common.py delete mode 100644 openshock/models/device.py delete mode 100644 openshock/models/meta.py delete mode 100644 openshock/models/session.py delete mode 100644 openshock/models/share.py delete mode 100644 openshock/models/shocker.py create mode 100644 openshock/realtime/_wire.py delete mode 100644 openshock/resources/__init__.py create mode 100644 openshock/rest/__init__.py create mode 100644 openshock/rest/api/__init__.py create mode 100644 openshock/rest/api/account/__init__.py create mode 100644 openshock/rest/api/account/account_activate.py create mode 100644 openshock/rest/api/account/account_check_username.py create mode 100644 openshock/rest/api/account/account_email_verify.py create mode 100644 openshock/rest/api/account/account_email_verify_legacy.py create mode 100644 openshock/rest/api/account/account_login_v2.py create mode 100644 openshock/rest/api/account/account_logout.py create mode 100644 openshock/rest/api/account/account_password_reset_check_valid.py create mode 100644 openshock/rest/api/account/account_password_reset_complete.py create mode 100644 openshock/rest/api/account/account_password_reset_initiate_v2.py create mode 100644 openshock/rest/api/account/account_resend_activation.py create mode 100644 openshock/rest/api/account/account_sign_up_v2.py create mode 100644 openshock/rest/api/account/authenticated_account_change_email.py create mode 100644 openshock/rest/api/account/authenticated_account_change_password.py create mode 100644 openshock/rest/api/account/authenticated_account_change_username.py create mode 100644 openshock/rest/api/account/authenticated_account_deactivate.py create mode 100644 openshock/rest/api/account/authenticated_account_get_audit_log.py create mode 100644 openshock/rest/api/account/authenticated_account_get_self.py create mode 100644 openshock/rest/api/account/authenticated_account_list_o_auth_connections.py create mode 100644 openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py create mode 100644 openshock/rest/api/admin/__init__.py create mode 100644 openshock/rest/api/admin/admin_add_email_provider_blacklist.py create mode 100644 openshock/rest/api/admin/admin_add_username_blacklist.py create mode 100644 openshock/rest/api/admin/admin_add_webhook.py create mode 100644 openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_bulk_delete_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_cancel_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_configuration_add.py create mode 100644 openshock/rest/api/admin/admin_configuration_delete.py create mode 100644 openshock/rest/api/admin/admin_configuration_list.py create mode 100644 openshock/rest/api/admin/admin_configuration_update.py create mode 100644 openshock/rest/api/admin/admin_create_automation_token.py create mode 100644 openshock/rest/api/admin/admin_deactivate_user.py create mode 100644 openshock/rest/api/admin/admin_delete_api_token.py create mode 100644 openshock/rest/api/admin/admin_delete_automation_token.py create mode 100644 openshock/rest/api/admin/admin_delete_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_delete_user.py create mode 100644 openshock/rest/api/admin/admin_get_admin_audit_log.py create mode 100644 openshock/rest/api/admin/admin_get_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_get_email_outbox_stats.py create mode 100644 openshock/rest/api/admin/admin_get_online_devices.py create mode 100644 openshock/rest/api/admin/admin_get_online_gateways.py create mode 100644 openshock/rest/api/admin/admin_get_user_by_id.py create mode 100644 openshock/rest/api/admin/admin_get_users.py create mode 100644 openshock/rest/api/admin/admin_list_automation_tokens.py create mode 100644 openshock/rest/api/admin/admin_list_email_provider_blacklist.py create mode 100644 openshock/rest/api/admin/admin_list_username_blacklist.py create mode 100644 openshock/rest/api/admin/admin_list_webhooks.py create mode 100644 openshock/rest/api/admin/admin_modify_user.py create mode 100644 openshock/rest/api/admin/admin_patch_automation_token.py create mode 100644 openshock/rest/api/admin/admin_reactivate_user.py create mode 100644 openshock/rest/api/admin/admin_remove_email_provider_blacklist.py create mode 100644 openshock/rest/api/admin/admin_remove_username_blacklist.py create mode 100644 openshock/rest/api/admin/admin_remove_webhook.py create mode 100644 openshock/rest/api/admin/admin_requeue_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_rotate_automation_token.py create mode 100644 openshock/rest/api/admin/admin_send_test_email.py create mode 100644 openshock/rest/api/admin/admin_set_user_email.py create mode 100644 openshock/rest/api/admin/admin_set_user_name.py create mode 100644 openshock/rest/api/admin/admin_set_user_password.py create mode 100644 openshock/rest/api/api_tokens/__init__.py create mode 100644 openshock/rest/api/api_tokens/token_delete_delete_token.py create mode 100644 openshock/rest/api/api_tokens/tokens_create_token_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_edit_token_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_list_tokens_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_report_tokens.py create mode 100644 openshock/rest/api/api_tokens/tokens_self_get_self_token_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_set_token_paused.py create mode 100644 openshock/rest/api/hub_endpoints/__init__.py create mode 100644 openshock/rest/api/hub_endpoints/device_get_live_control_gateway_v2.py create mode 100644 openshock/rest/api/hub_endpoints/device_get_self.py create mode 100644 openshock/rest/api/hub_endpoints/device_pair.py create mode 100644 openshock/rest/api/hub_management/__init__.py create mode 100644 openshock/rest/api/hub_management/devices_create_device_v2.py create mode 100644 openshock/rest/api/hub_management/devices_edit_device.py create mode 100644 openshock/rest/api/hub_management/devices_get_device_by_id.py create mode 100644 openshock/rest/api/hub_management/devices_get_live_control_gateway_info_v2.py create mode 100644 openshock/rest/api/hub_management/devices_get_pair_code.py create mode 100644 openshock/rest/api/hub_management/devices_get_shockers.py create mode 100644 openshock/rest/api/hub_management/devices_list_devices.py create mode 100644 openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py create mode 100644 openshock/rest/api/hub_management/devices_regenerate_device_token.py create mode 100644 openshock/rest/api/hub_management/devices_remove_device.py create mode 100644 openshock/rest/api/integrations/__init__.py create mode 100644 openshock/rest/api/integrations/integrations_get_control_stat_changes.py create mode 100644 openshock/rest/api/meta/__init__.py create mode 100644 openshock/rest/api/meta/public_get_online_devices_statistics.py create mode 100644 openshock/rest/api/meta/version_get_backend_info.py create mode 100644 openshock/rest/api/public_shocker_shares/__init__.py create mode 100644 openshock/rest/api/public_shocker_shares/public_get_public_share.py create mode 100644 openshock/rest/api/public_shocker_shares/share_links_add_shocker.py create mode 100644 openshock/rest/api/public_shocker_shares/share_links_create_public_share.py create mode 100644 openshock/rest/api/public_shocker_shares/share_links_delete_public_share.py create mode 100644 openshock/rest/api/public_shocker_shares/share_links_edit_shocker.py create mode 100644 openshock/rest/api/public_shocker_shares/share_links_list.py create mode 100644 openshock/rest/api/public_shocker_shares/share_links_pause_shocker.py create mode 100644 openshock/rest/api/public_shocker_shares/share_links_remove_shocker.py create mode 100644 openshock/rest/api/sessions/__init__.py create mode 100644 openshock/rest/api/sessions/sessions_delete_session.py create mode 100644 openshock/rest/api/sessions/sessions_get_self_session.py create mode 100644 openshock/rest/api/sessions/sessions_list_sessions.py create mode 100644 openshock/rest/api/shocker_shares/__init__.py create mode 100644 openshock/rest/api/shocker_shares/shares_delete_share_code.py create mode 100644 openshock/rest/api/shocker_shares/shares_link_share_code.py create mode 100644 openshock/rest/api/shockers/__init__.py create mode 100644 openshock/rest/api/shockers/shocker_edit_shocker.py create mode 100644 openshock/rest/api/shockers/shocker_get_all_shocker_logs.py create mode 100644 openshock/rest/api/shockers/shocker_get_shocker_by_id.py create mode 100644 openshock/rest/api/shockers/shocker_get_shocker_logs.py create mode 100644 openshock/rest/api/shockers/shocker_get_user_shares.py create mode 100644 openshock/rest/api/shockers/shocker_list_shared_shockers.py create mode 100644 openshock/rest/api/shockers/shocker_list_shockers.py create mode 100644 openshock/rest/api/shockers/shocker_pause_shocker.py create mode 100644 openshock/rest/api/shockers/shocker_register_shocker.py create mode 100644 openshock/rest/api/shockers/shocker_remove_shocker.py create mode 100644 openshock/rest/api/shockers/shocker_send_control.py create mode 100644 openshock/rest/api/shockers/shocker_shocker_share_code_create.py create mode 100644 openshock/rest/api/shockers/shocker_shocker_share_code_list.py create mode 100644 openshock/rest/api/shockers/shocker_shocker_share_code_pause.py create mode 100644 openshock/rest/api/shockers/shocker_shocker_share_code_update.py create mode 100644 openshock/rest/api/shockers/shocker_shocker_share_remove.py create mode 100644 openshock/rest/api/user_shocker_shares/__init__.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_bulk_pause_user_share_shockers.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_bulk_remove_user_share_shockers.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_bulk_user_share_shockers_update.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_create_share_invite.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_delete_outgoing_invite.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_deny_incoming_invite.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_get_incoming_invites_list.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_get_outgoing_invites_list.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_get_shares_by_users.py create mode 100644 openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py create mode 100644 openshock/rest/api/users/__init__.py create mode 100644 openshock/rest/api/users/users_get_by_name.py create mode 100644 openshock/rest/api/users/users_get_self.py create mode 100644 openshock/rest/api/users/users_get_self_control_stats.py create mode 100644 openshock/rest/client.py create mode 100644 openshock/rest/errors.py create mode 100644 openshock/rest/models/__init__.py create mode 100644 openshock/rest/models/add_email_provider_blacklist_dto.py create mode 100644 openshock/rest/models/add_username_blacklist_dto.py create mode 100644 openshock/rest/models/add_webhook_dto.py create mode 100644 openshock/rest/models/admin_online_device_response.py create mode 100644 openshock/rest/models/admin_online_gateway_response.py create mode 100644 openshock/rest/models/admin_user_view.py create mode 100644 openshock/rest/models/admin_user_view_api_token.py create mode 100644 openshock/rest/models/admin_user_view_email_change.py create mode 100644 openshock/rest/models/admin_user_view_hub.py create mode 100644 openshock/rest/models/admin_user_view_name_change.py create mode 100644 openshock/rest/models/admin_user_view_password_reset.py create mode 100644 openshock/rest/models/admin_user_view_shocker.py create mode 100644 openshock/rest/models/admin_user_view_user_activation_request.py create mode 100644 openshock/rest/models/admin_user_view_user_deactivation.py create mode 100644 openshock/rest/models/admin_user_view_user_ref.py create mode 100644 openshock/rest/models/admin_users_view.py create mode 100644 openshock/rest/models/audit_action.py create mode 100644 openshock/rest/models/audit_log_entry_response.py create mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata.py create mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata.py create mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata.py create mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata.py create mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata.py create mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_login_metadata.py create mode 100644 openshock/rest/models/audit_metadata_login_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata.py create mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata_t.py create mode 100644 openshock/rest/models/automation_token_dto.py create mode 100644 openshock/rest/models/automation_token_type.py create mode 100644 openshock/rest/models/backend_info_response.py create mode 100644 openshock/rest/models/basic_user_info.py create mode 100644 openshock/rest/models/bulk_user_share_shockers_update_request.py create mode 100644 openshock/rest/models/change_email_request.py create mode 100644 openshock/rest/models/change_password_request.py create mode 100644 openshock/rest/models/change_username_request.py create mode 100644 openshock/rest/models/configuration_add_item_request.py create mode 100644 openshock/rest/models/configuration_item_dto.py create mode 100644 openshock/rest/models/configuration_update_item_request.py create mode 100644 openshock/rest/models/configuration_value_type.py create mode 100644 openshock/rest/models/control.py create mode 100644 openshock/rest/models/control_limit_mode.py create mode 100644 openshock/rest/models/control_log_sender_light.py create mode 100644 openshock/rest/models/control_request.py create mode 100644 openshock/rest/models/control_stat_changes_request.py create mode 100644 openshock/rest/models/control_stat_changes_response.py create mode 100644 openshock/rest/models/control_stat_totals.py create mode 100644 openshock/rest/models/control_stats_response.py create mode 100644 openshock/rest/models/control_type.py create mode 100644 openshock/rest/models/create_automation_token_dto.py create mode 100644 openshock/rest/models/create_share_request.py create mode 100644 openshock/rest/models/create_token_request_v2.py create mode 100644 openshock/rest/models/created_automation_token_dto.py create mode 100644 openshock/rest/models/daily_control_stats.py create mode 100644 openshock/rest/models/device_response.py create mode 100644 openshock/rest/models/device_self_response.py create mode 100644 openshock/rest/models/device_with_shockers_response.py create mode 100644 openshock/rest/models/device_with_token_response.py create mode 100644 openshock/rest/models/duration_limit_settings.py create mode 100644 openshock/rest/models/edit_token_request_v2.py create mode 100644 openshock/rest/models/email_outbox_bulk_request.py create mode 100644 openshock/rest/models/email_outbox_bulk_result_dto.py create mode 100644 openshock/rest/models/email_outbox_message_dto.py create mode 100644 openshock/rest/models/email_outbox_message_dto_payload.py create mode 100644 openshock/rest/models/email_outbox_stats_dto.py create mode 100644 openshock/rest/models/email_provider_blacklist_dto.py create mode 100644 openshock/rest/models/email_status.py create mode 100644 openshock/rest/models/email_type.py create mode 100644 openshock/rest/models/given_control_stats.py create mode 100644 openshock/rest/models/hub_create_request.py create mode 100644 openshock/rest/models/hub_edit_request.py create mode 100644 openshock/rest/models/intensity_limit_settings.py create mode 100644 openshock/rest/models/lcg_node_response_v2.py create mode 100644 openshock/rest/models/lcg_response_v2.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_device_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_device_with_shockers_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_log_entry.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_own_public_share_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_owner_shocker_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_share_code_info.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_share_info.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_shocker_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_backend_info_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_device_self_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_device_with_token_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_guid.py create mode 100644 openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py create mode 100644 openshock/rest/models/legacy_data_response_of_legacy_user_self_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_pause_reason.py create mode 100644 openshock/rest/models/legacy_data_response_of_public_share_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_shocker_with_device.py create mode 100644 openshock/rest/models/legacy_data_response_of_stats_response.py create mode 100644 openshock/rest/models/legacy_data_response_ofboolean.py create mode 100644 openshock/rest/models/legacy_data_response_ofstring.py create mode 100644 openshock/rest/models/legacy_empty_response.py create mode 100644 openshock/rest/models/legacy_user_self_response.py create mode 100644 openshock/rest/models/log_entry.py create mode 100644 openshock/rest/models/log_entry_with_hub.py create mode 100644 openshock/rest/models/login_session_response.py create mode 100644 openshock/rest/models/login_v2.py create mode 100644 openshock/rest/models/login_v2_ok_response.py create mode 100644 openshock/rest/models/match_type_enum.py create mode 100644 openshock/rest/models/minimal_shocker.py create mode 100644 openshock/rest/models/new_shocker.py create mode 100644 openshock/rest/models/o_auth_connection_response.py create mode 100644 openshock/rest/models/open_shock_problem.py create mode 100644 openshock/rest/models/ota_item.py create mode 100644 openshock/rest/models/ota_update_status.py create mode 100644 openshock/rest/models/own_public_share_response.py create mode 100644 openshock/rest/models/owner_shocker_response.py create mode 100644 openshock/rest/models/paged_result_of_audit_log_entry_response.py create mode 100644 openshock/rest/models/paged_result_of_log_entry_with_hub.py create mode 100644 openshock/rest/models/paginated_of_admin_users_view.py create mode 100644 openshock/rest/models/paginated_of_email_outbox_message_dto.py create mode 100644 openshock/rest/models/password_hashing_algorithm.py create mode 100644 openshock/rest/models/password_reset_process_data.py create mode 100644 openshock/rest/models/password_reset_request_v2.py create mode 100644 openshock/rest/models/patch_automation_token_dto.py create mode 100644 openshock/rest/models/pause_request.py create mode 100644 openshock/rest/models/pause_user_share_shockers_request.py create mode 100644 openshock/rest/models/pause_user_share_shockers_response.py create mode 100644 openshock/rest/models/pause_user_share_shockers_response_pause_states.py create mode 100644 openshock/rest/models/permission_type.py create mode 100644 openshock/rest/models/problem_details.py create mode 100644 openshock/rest/models/public_share_create.py create mode 100644 openshock/rest/models/public_share_device.py create mode 100644 openshock/rest/models/public_share_edit_shocker.py create mode 100644 openshock/rest/models/public_share_response.py create mode 100644 openshock/rest/models/public_share_shocker.py create mode 100644 openshock/rest/models/received_control_stats.py create mode 100644 openshock/rest/models/remove_user_shares_response.py create mode 100644 openshock/rest/models/report_tokens_request.py create mode 100644 openshock/rest/models/role_type.py create mode 100644 openshock/rest/models/send_test_email_dto.py create mode 100644 openshock/rest/models/set_token_paused_request.py create mode 100644 openshock/rest/models/set_user_email_request_body.py create mode 100644 openshock/rest/models/set_user_name_request_body.py create mode 100644 openshock/rest/models/set_user_password_request_body.py create mode 100644 openshock/rest/models/share_code_info.py create mode 100644 openshock/rest/models/share_info.py create mode 100644 openshock/rest/models/share_invite_base_details.py create mode 100644 openshock/rest/models/shared_device.py create mode 100644 openshock/rest/models/shared_shocker.py create mode 100644 openshock/rest/models/shocker_control_settings.py create mode 100644 openshock/rest/models/shocker_control_stats.py create mode 100644 openshock/rest/models/shocker_limits.py create mode 100644 openshock/rest/models/shocker_model_type.py create mode 100644 openshock/rest/models/shocker_perm_limit_pair.py create mode 100644 openshock/rest/models/shocker_perm_limit_pair_with_id.py create mode 100644 openshock/rest/models/shocker_perm_limit_pair_with_id_and_name.py create mode 100644 openshock/rest/models/shocker_permissions.py create mode 100644 openshock/rest/models/shocker_response.py create mode 100644 openshock/rest/models/shocker_with_device.py create mode 100644 openshock/rest/models/sign_up_v2.py create mode 100644 openshock/rest/models/sort_direction.py create mode 100644 openshock/rest/models/stats_response.py create mode 100644 openshock/rest/models/token_created_response_v2.py create mode 100644 openshock/rest/models/token_paused_response.py create mode 100644 openshock/rest/models/token_response_v2.py create mode 100644 openshock/rest/models/user_control_stat_totals.py create mode 100644 openshock/rest/models/user_control_stats.py create mode 100644 openshock/rest/models/user_name_blacklist_dto.py create mode 100644 openshock/rest/models/user_patch_dto.py create mode 100644 openshock/rest/models/user_self_response.py create mode 100644 openshock/rest/models/user_share_info.py create mode 100644 openshock/rest/models/username_availability.py create mode 100644 openshock/rest/models/username_check_response.py create mode 100644 openshock/rest/models/username_error.py create mode 100644 openshock/rest/models/username_error_type.py create mode 100644 openshock/rest/models/v2_user_shares.py create mode 100644 openshock/rest/models/v2_user_shares_list_item.py create mode 100644 openshock/rest/models/webhook_dto.py create mode 100644 openshock/rest/types.py create mode 100644 scripts/generate.py delete mode 100644 scripts/unasync.py delete mode 100644 tests/test_endpoints.py delete mode 100644 tests/test_enums.py create mode 100644 tests/test_generated.py delete mode 100644 tests/test_models.py delete mode 100644 tests/test_rest.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 152bd86..aaf892f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,11 +13,11 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.13" - - run: pip install ruff + - run: pip install -e ".[codegen]" - run: ruff format --check . - run: ruff check . - - name: Check that the generated sync client is up to date - run: python scripts/unasync.py --check + - name: Check that the generated REST client is up to date + run: python scripts/generate.py --check typecheck: runs-on: ubuntu-latest @@ -33,7 +33,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.10", "3.11", "3.12", "3.13"] + python-version: ["3.11", "3.12", "3.13", "3.14"] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 diff --git a/README.md b/README.md index f2289a6..24f15ba 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,10 @@ The official OpenShock Python SDK to integrate with an OpenShock backend easily. -- **REST API** — typed client for the whole user API, sync and async +- **REST API** — every endpoint and model, generated from the backend's OpenAPI document, sync and async - **Realtime events** — SignalR user hub: hub online state, executed commands, firmware updates - **Live control** — stream intensity to shockers in real time -- Typed models and enums, typed errors, automatic reconnects, Python 3.10+ +- Typed models and enums, typed errors, automatic reconnects, Python 3.11+ ## Install @@ -39,18 +39,25 @@ pip install --no-binary websockets "openshock[realtime]" ## Quick start ```python -from openshock import Control, ControlType, OpenShockClient +from uuid import UUID -with OpenShockClient(api_token="your-api-token", app_name="MyApp", app_version="1.0.0") as client: +from openshock import OpenShockClient, unwrap +from openshock.rest.api.shockers import shocker_list_shockers, shocker_send_control +from openshock.rest.models import Control, ControlRequest, ControlType + +with OpenShockClient("your-api-token", app_name="MyApp", app_version="1.0.0") as client: # Your hubs and their shockers - for hub in client.shockers.list_own(): + for hub in unwrap(shocker_list_shockers.sync(client=client)).data: for shocker in hub.shockers: print(hub.name, shocker.name, shocker.id) # Vibrate at 50% for one second - client.shockers.control( - [Control(id="shocker-uuid", type=ControlType.VIBRATE, intensity=50, duration=1000)], - custom_name="MyApp", + shocker_send_control.sync( + client=client, + body=ControlRequest( + shocks=[Control(id=UUID("shocker-uuid"), type_=ControlType.VIBRATE, intensity=50, duration=1000)], + custom_name="MyApp", + ), ) ``` @@ -59,46 +66,70 @@ Create API tokens at [openshock.app](https://openshock.app) under Settings > API Please set `app_name` / `app_version`: they end up in the `User-Agent` header and let the OpenShock team tell integrations apart. -### Async +## The REST client -Every client has an async twin with the same resources and methods: +`openshock.rest` is generated from the backend's OpenAPI document with +[openapi-python-client](https://github.com/openapi-generators/openapi-python-client). Nothing +in it is written by hand, so it always covers the whole API. -```python -import asyncio -from openshock import AsyncOpenShockClient +- **Operations** live in `openshock.rest.api.`, one module per endpoint. The module name + is the endpoint's operation ID in snake case. +- **Models and enums** live in `openshock.rest.models`. +- **`OpenShockClient`** is the generated client with OpenShock's header name, base URL, + User-Agent and error handling filled in. Pass it to every operation as `client=`. +| Area (`openshock.rest.api.…`) | Covers | +|-------------------------------|--------| +| `shockers` | Shocker CRUD, control, pause, logs, share codes | +| `hub_management` | Hubs: list, create, edit, pair code, gateway lookup, OTA history | +| `user_shocker_shares`, `shocker_shares` | User-to-user shares and invites | +| `public_shocker_shares` | Public share links | +| `api_tokens` | API tokens | +| `users`, `account`, `sessions` | Profile, account settings, login sessions | +| `meta` | Backend version and public stats | +| `hub_endpoints` | What a hub device itself calls (see below) | +| `integrations`, `admin` | Integrations and admin endpoints | -async def main(): - async with AsyncOpenShockClient(api_token="your-api-token") as client: - stats = await client.meta.online_stats() - print(f"Devices online: {stats.devices_online}") +Each operation module offers the same functions: +| Function | Returns | +|----------|---------| +| `sync(...)` / `await asyncio(...)` | the parsed response model | +| `sync_detailed(...)` / `await asyncio_detailed(...)` | a `Response` with `status_code`, `headers`, `content` and `parsed` | -asyncio.run(main()) +Endpoints without a response body only have the `_detailed` pair. + +The same client serves both styles: + +```python +async with OpenShockClient("your-api-token") as client: + stats = unwrap(await public_get_online_devices_statistics.asyncio(client=client)).data + print(f"Devices online: {stats.devices_online}") ``` -## Resources +### `unwrap` + +Generated operations are typed as returning `Model | OpenShockProblem | None`. `unwrap()` +narrows that to `Model` for the type checker (and raises if it is handed a problem), so +`unwrap(op.sync(client=client)).data` type-checks without `isinstance` checks. Many older +endpoints wrap their payload as `{"message": ..., "data": ...}`, hence the `.data`. -| Resource | Description | Example | -|----------|-------------|---------| -| `client.meta` | Backend info and stats | `client.meta.backend_info()` | -| `client.account` | User info and API tokens | `client.account.user_self()` | -| `client.devices` | Hub (device) management | `client.devices.list()` | -| `client.shockers` | Shocker CRUD, control, logs | `client.shockers.control(...)` | -| `client.shares` | Public share links and codes | `client.shares.list_public()` | -| `client.user_shares` | User-to-user shares (V2) | `client.user_shares.get()` | -| `client.sessions` | Login session management | `client.sessions.list()` | +### Optional fields + +Fields the API may omit are typed `T | Unset` (`from openshock.rest.types import UNSET, Unset`). +Fields the backend adds after a release are not lost: every model keeps unknown fields and +exposes them with `model["fieldName"]`. ## Errors -Every non-2xx response raises a subclass of `OpenShockApiError`, which carries -`status_code` and, when the backend sent one, the parsed `problem` document. +With `OpenShockClient`, every non-2xx response raises a subclass of `OpenShockApiError`, +which carries `status_code` and, when the backend sent one, the parsed `problem` document. ```python from openshock import OpenShockApiError, ShockerNoPermission, ShockerNotFoundOrNoAccess, ShockerPaused try: - client.shockers.control([...]) + shocker_send_control.sync(client=client, body=request) except ShockerPaused as e: print("paused:", e.shocker_id) except (ShockerNotFoundOrNoAccess, ShockerNoPermission) as e: @@ -113,11 +144,14 @@ except OpenShockApiError as e: | `TokenPermissionMissing` | the API token lacks a permission (`.required_permission`) | | `ApiTokenPaused` | the API token is paused | | `OpenShockNotFound` | 404 | -| `HubNotFound`, `HubOffline` | hub lookups, e.g. `client.devices.gateway()` | +| `HubNotFound`, `HubOffline` | hub lookups, e.g. the gateway lookup | | `ShockerNotFoundOrNoAccess`, `ShockerPaused`, `ShockerNoPermission` | a control request was rejected (`.shocker_id`) | | `OpenShockRateLimited` | 429 (`.retry_after`) | | `OpenShockConnectionError` | a realtime connection failed for good | +Pass `raise_on_error=False` to get the generator's stock behaviour instead, where documented +problems are returned as `OpenShockProblem` objects. + ## Realtime: user hub `UserHubClient` connects to the SignalR user hub. It needs `openshock[realtime]` and asyncio. @@ -163,7 +197,8 @@ Handlers can be plain functions or coroutines. Subscribe with the decorator form above or with `hub.on_log.subscribe(handler)`, which returns an unsubscribe function. `hub.on("MethodName", handler)` subscribes to hub methods the SDK has no typed event for. -Commands can be sent over the same connection: `await hub.control([...], custom_name="MyApp")`. +Commands can be sent over the same connection, using the same `Control` model as the REST +API: `await hub.control([Control(...)], custom_name="MyApp")`. `set_captive_portal`, `emergency_stop`, `ota_install` and `reboot` exist too, but the backend only honours them for user-session connections, not API tokens. @@ -182,8 +217,8 @@ rate the gateway asks for, pings and reconnects. ```python import asyncio -from openshock import ControlType from openshock.realtime import LiveControlClient +from openshock.rest.models import ControlType async def main(): @@ -206,7 +241,7 @@ asyncio.run(main()) - Events: `on_hub_connected`, `on_hub_not_connected`, `on_tps`, `on_latency`, `on_rejected` (e.g. `SHOCKER_PAUSED`, `SHOCKER_MISSING_LIVE_PERMISSION`), plus the connection events above. - While the hub is offline the client keeps retrying in the background (0s, 5s, 10s, then every 30s). -- Pass `client=` to reuse an `AsyncOpenShockClient`, or `gateway=` to skip the lookup. +- Pass `client=` to reuse an `OpenShockClient`, or `gateway=` to skip the lookup. The shockers need the *live* permission for your account. @@ -215,28 +250,18 @@ The shockers need the *live* permission for your account. For the endpoints a hub itself calls, use `OpenShockHubClient` with a device token: ```python -from openshock import OpenShockHubClient +from openshock import OpenShockHubClient, unwrap +from openshock.rest.api.hub_endpoints import device_get_self -with OpenShockHubClient(hub_token="device-token") as hub: - lcg = hub.hub.assign_lcg() - print(f"Connect to {lcg.host}:{lcg.port}") -``` - -## Models and enums - -Responses are parsed into typed dataclasses (`Shocker`, `Device`, `Token`, `ShockerLog`, …). -Enums such as `ControlType`, `ShockerModelType` and `PermissionType` are string enums: - -```python -ControlType.SHOCK == "Shock" # True, plain strings keep working everywhere -ControlType("vibrate") # case-insensitive lookup -PermissionType("some.new.permission").is_known # False, unknown values never raise +with OpenShockHubClient("device-token") as hub: + me = unwrap(device_get_self.sync(client=hub)).data + print(me.name, len(me.shockers), "shockers") ``` ## Self-hosting ```python -client = OpenShockClient(api_token="your-token", base_url="https://api.your-instance.com") +client = OpenShockClient("your-token", base_url="https://api.your-instance.com") hub = UserHubClient("your-token", base_url="https://api.your-instance.com") ``` @@ -246,8 +271,8 @@ Standalone example programs live in [`examples/`](examples), one folder each: | Folder | Shows | |--------|-------| -| [`rest_quickstart`](examples/rest_quickstart) | Sync REST client: list hubs, shockers and shares | -| [`async_control`](examples/async_control) | Async REST client: send a command, handle typed errors | +| [`rest_quickstart`](examples/rest_quickstart) | REST, blocking: list hubs, shockers and shares | +| [`async_control`](examples/async_control) | REST, asyncio: send a command, handle typed errors | | [`realtime_events`](examples/realtime_events) | SignalR user hub: print live events for your account | | [`live_control`](examples/live_control) | Live control: stream intensity to a shocker | @@ -266,9 +291,23 @@ mypy openshock/ # type check pytest # test ``` -The sync client is generated from the async one. Edit code under `openshock/_async/`, -then run `python scripts/unasync.py` to regenerate `openshock/_sync/`. CI fails if the -two are out of step. +### Regenerating the REST client + +Everything under `openshock/rest/` is generated from `openapi/openapi.json`, a snapshot of +the backend's OpenAPI document. Never edit it by hand. + +```bash +python scripts/generate.py --update # download the latest spec, then regenerate +python scripts/generate.py # regenerate from the committed snapshot +python scripts/generate.py --check # what CI runs; fails if openshock/rest is out of date +``` + +The generator and formatter versions are pinned in the `codegen` extra because they decide +the output. The script fails rather than emit a partial client if the generator skips anything. + +Hand-written code is limited to what the OpenAPI document cannot describe: the preconfigured +clients (`openshock/client.py`), the error mapping (`openshock/exceptions.py`) and the +realtime clients (`openshock/realtime/`). ## License diff --git a/examples/README.md b/examples/README.md index bf28aec..3e2183e 100644 --- a/examples/README.md +++ b/examples/README.md @@ -4,8 +4,8 @@ Each folder is a small standalone program with its own `requirements.txt` and RE | Folder | Shows | Needs | |--------|-------|-------| -| [`rest_quickstart`](rest_quickstart) | Sync REST client: list hubs, shockers and shares | `openshock` | -| [`async_control`](async_control) | Async REST client: send a command, handle typed errors | `openshock` | +| [`rest_quickstart`](rest_quickstart) | REST, blocking: list hubs, shockers and shares | `openshock` | +| [`async_control`](async_control) | REST, asyncio: send a command, handle typed errors | `openshock` | | [`realtime_events`](realtime_events) | SignalR user hub: print live events for your account | `openshock[realtime]` | | [`live_control`](live_control) | Live control: stream intensity to a shocker | `openshock[realtime]` | diff --git a/examples/async_control/README.md b/examples/async_control/README.md index 4171a1d..4eb3ced 100644 --- a/examples/async_control/README.md +++ b/examples/async_control/README.md @@ -1,6 +1,6 @@ # Async control -Async client. Sends a single command to a shocker and handles each way the backend can refuse it (paused, no access, no permission). +Asyncio calls through the generated REST client. Sends a single command to a shocker and handles each way the backend can refuse it (paused, no access, no permission). ```bash pip install -r requirements.txt diff --git a/examples/async_control/main.py b/examples/async_control/main.py index 5d6a34e..5a76084 100644 --- a/examples/async_control/main.py +++ b/examples/async_control/main.py @@ -7,16 +7,11 @@ import asyncio import os import sys +from uuid import UUID -from openshock import ( - AsyncOpenShockClient, - Control, - ControlType, - OpenShockApiError, - ShockerNoPermission, - ShockerNotFoundOrNoAccess, - ShockerPaused, -) +from openshock import OpenShockApiError, OpenShockClient, ShockerNoPermission, ShockerNotFoundOrNoAccess, ShockerPaused +from openshock.rest.api.shockers import shocker_send_control +from openshock.rest.models import Control, ControlRequest, ControlType APP_NAME = "OpenShock.SDK.Python.Examples" APP_VERSION = "1.0.0" @@ -29,19 +24,19 @@ async def main() -> None: if len(sys.argv) < 2: sys.exit(__doc__) - shocker_id = sys.argv[1] - control_type = ControlType(sys.argv[2] if len(sys.argv) > 2 else "vibrate") + shocker_id = UUID(sys.argv[1]) + control_type = ControlType((sys.argv[2] if len(sys.argv) > 2 else "vibrate").capitalize()) intensity = int(sys.argv[3]) if len(sys.argv) > 3 else 25 duration = int(sys.argv[4]) if len(sys.argv) > 4 else 1000 - async with AsyncOpenShockClient( - api_token=API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION - ) as client: + request = ControlRequest( + shocks=[Control(id=shocker_id, type_=control_type, intensity=intensity, duration=duration)], + custom_name="SDK example", + ) + + async with OpenShockClient(API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION) as client: try: - await client.shockers.control( - [Control(id=shocker_id, type=control_type, intensity=intensity, duration=duration)], - custom_name="SDK example", - ) + await shocker_send_control.asyncio(client=client, body=request) except ShockerPaused: sys.exit("That shocker is paused.") except ShockerNotFoundOrNoAccess: diff --git a/examples/live_control/main.py b/examples/live_control/main.py index a4a2a44..2386be7 100644 --- a/examples/live_control/main.py +++ b/examples/live_control/main.py @@ -10,9 +10,12 @@ import math import os import sys +from uuid import UUID -from openshock import AsyncOpenShockClient, ControlType +from openshock import OpenShockClient, unwrap from openshock.realtime import LiveControlClient, LiveResponseType +from openshock.rest.api.shockers import shocker_get_shocker_by_id +from openshock.rest.models import ControlType APP_NAME = "OpenShock.SDK.Python.Examples" APP_VERSION = "1.0.0" @@ -28,14 +31,11 @@ async def main() -> None: if len(sys.argv) < 2: sys.exit(__doc__) - shocker_id = sys.argv[1] + shocker_id = UUID(sys.argv[1]) - async with AsyncOpenShockClient( - api_token=API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION - ) as client: + async with OpenShockClient(API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION) as client: # Live control connects per hub, so find the hub this shocker belongs to. - shocker = await client.shockers.get(shocker_id) - assert shocker.device is not None + shocker = unwrap(await shocker_get_shocker_by_id.asyncio(shocker_id, client=client)).data live = LiveControlClient(shocker.device, client=client, app_name=APP_NAME, app_version=APP_VERSION) live.on_latency(lambda own, hub: print(f"latency {own} ms")) diff --git a/examples/rest_quickstart/README.md b/examples/rest_quickstart/README.md index 16d8d42..4984284 100644 --- a/examples/rest_quickstart/README.md +++ b/examples/rest_quickstart/README.md @@ -1,6 +1,6 @@ # REST quickstart -Synchronous client. Prints the backend version, who you are, your hubs and shockers, and the shockers shared with you. +Blocking calls through the generated REST client. Prints the backend version, who you are, your hubs and shockers, and the shockers shared with you. ```bash pip install -r requirements.txt diff --git a/examples/rest_quickstart/main.py b/examples/rest_quickstart/main.py index 49649ba..ea6254a 100644 --- a/examples/rest_quickstart/main.py +++ b/examples/rest_quickstart/main.py @@ -3,7 +3,11 @@ import os import sys -from openshock import OpenShockClient +from openshock import OpenShockClient, unwrap +from openshock.rest.api.meta import version_get_backend_info +from openshock.rest.api.shockers import shocker_list_shared_shockers, shocker_list_shockers +from openshock.rest.api.users import users_get_self +from openshock.rest.types import Unset APP_NAME = "OpenShock.SDK.Python.Examples" APP_VERSION = "1.0.0" @@ -12,21 +16,22 @@ "Set OPENSHOCK_API_TOKEN to an API token from https://openshock.app (Settings > API Tokens)." ) -with OpenShockClient(api_token=API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION) as client: - info = client.meta.backend_info() - me = client.account.user_self() +with OpenShockClient(API_TOKEN, base_url=BASE_URL, app_name=APP_NAME, app_version=APP_VERSION) as client: + info = unwrap(version_get_backend_info.sync(client=client)).data + me = unwrap(users_get_self.sync(client=client)).data print(f"OpenShock {info.version}, signed in as {me.name}\n") print("Own:") - for hub in client.shockers.list_own(): + for hub in unwrap(shocker_list_shockers.sync(client=client)).data: print(f" {hub.name} ({hub.id})") for shocker in hub.shockers: paused = " [paused]" if shocker.is_paused else "" print(f" {shocker.name} {shocker.model} ({shocker.id}){paused}") print("\nShared with me:") - for owner in client.shockers.list_shared(): + for owner in unwrap(shocker_list_shared_shockers.sync(client=client)).data: for shared_hub in owner.devices: for shared in shared_hub.shockers: - limit = shared.limits.intensity if shared.limits.intensity is not None else 100 + intensity = shared.limits.intensity + limit = 100 if intensity is None or isinstance(intensity, Unset) else intensity print(f" {owner.name} / {shared_hub.name} / {shared.name} max {limit}% ({shared.id})") diff --git a/openapi/generator-config.yaml b/openapi/generator-config.yaml new file mode 100644 index 0000000..128cbdf --- /dev/null +++ b/openapi/generator-config.yaml @@ -0,0 +1,6 @@ +# Configuration for openapi-python-client. See scripts/generate.py. +# The hooks run inside the freshly generated package, outside this repository, so they +# carry their own settings instead of relying on pyproject.toml. +post_hooks: + - "ruff check . --isolated --line-length 120 --target-version py311 --select I,UP,F401,F811,W --fix-only --unsafe-fixes --quiet" + - "ruff format . --isolated --line-length 120 --target-version py311 --quiet" diff --git a/openapi/openapi.json b/openapi/openapi.json new file mode 100644 index 0000000..942d583 --- /dev/null +++ b/openapi/openapi.json @@ -0,0 +1,11651 @@ +{ + "openapi": "3.2.0", + "info": { + "title": "OpenShock.API", + "description": "Backend for the OpenShock solution, that enables controlling shock collars over the internet.", + "version": "1.0" + }, + "servers": [ + { + "url": "https://api.openshock.app" + }, + { + "url": "https://api.openshock.dev" + } + ], + "paths": { + "/1": { + "get": { + "tags": [ + "Meta" + ], + "summary": "Gets the version of the OpenShock backend.", + "operationId": "Version_GetBackendInfo", + "responses": { + "200": { + "description": "The version was successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfBackendInfoResponse" + } + } + } + } + } + } + }, + "/1/users/self": { + "get": { + "tags": [ + "Users" + ], + "summary": "Get the current user's information. Deprecated: use GET /1/account instead.", + "operationId": "Users_GetSelf", + "responses": { + "200": { + "description": "The user's information was successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfLegacyUserSelfResponse" + } + } + } + } + }, + "deprecated": true, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/users/self/control-stats": { + "get": { + "tags": [ + "Users" + ], + "summary": "Get control statistics for the current user, both for their own shockers and for controls they sent.", + "operationId": "Users_GetSelfControlStats", + "parameters": [ + { + "name": "tz", + "in": "query", + "description": "IANA time zone the daily breakdown and the date range are in, e.g. `Europe/Berlin`, defaults to UTC.", + "schema": { + "maxLength": 64, + "type": "string" + } + }, + { + "name": "from", + "in": "query", + "description": "First day to include (inclusive), defaults to all time.", + "schema": { + "type": "string", + "format": "date" + } + }, + { + "name": "to", + "in": "query", + "description": "Last day to include (inclusive), defaults to today.", + "schema": { + "type": "string", + "format": "date" + } + } + ], + "responses": { + "200": { + "description": "The statistics.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ControlStatsResponse" + } + } + } + }, + "400": { + "description": "Unknown time zone or invalid range.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/users/by-name/{username}": { + "get": { + "tags": [ + "Users" + ], + "operationId": "Users_GetByName", + "parameters": [ + { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/BasicUserInfo" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/BasicUserInfo" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/BasicUserInfo" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/tokens/{tokenId}": { + "delete": { + "tags": [ + "API Tokens" + ], + "summary": "Revoke a token", + "operationId": "TokenDelete_DeleteToken", + "parameters": [ + { + "name": "tokenId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully deleted token" + }, + "403": { + "description": "Api Token is not allowed to delete other Api Tokens", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "The token does not exist, or you do not have access to it", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/tokens/self": { + "get": { + "tags": [ + "API Tokens" + ], + "summary": "Gets information about the current token used to access this endpoint", + "operationId": "TokensSelf_GetSelfTokenV2", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/TokenResponseV2" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenResponseV2" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/TokenResponseV2" + } + } + } + } + }, + "security": [ + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:ApiToken" + ] + } + }, + "/1/tokens/report": { + "post": { + "tags": [ + "API Tokens" + ], + "summary": "Endpoint to delete potentially compromised api tokens", + "operationId": "Tokens_ReportTokens", + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportTokensRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ReportTokensRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The tokens were deleted if found" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/2/tokens": { + "get": { + "tags": [ + "API Tokens" + ], + "summary": "List all tokens for the current user", + "operationId": "Tokens_ListTokensV2", + "responses": { + "200": { + "description": "All tokens for the current user", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TokenResponseV2" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TokenResponseV2" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TokenResponseV2" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + }, + "post": { + "tags": [ + "API Tokens" + ], + "summary": "Create a new token", + "operationId": "Tokens_CreateTokenV2", + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateTokenRequestV2" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateTokenRequestV2" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The created token", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenCreatedResponseV2" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/2/tokens/{tokenId}": { + "get": { + "tags": [ + "API Tokens" + ], + "summary": "Get a token by id", + "operationId": "Tokens_GetTokenByIdV2", + "parameters": [ + { + "name": "tokenId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The token", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenResponseV2" + } + } + } + }, + "404": { + "description": "The token does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + }, + "patch": { + "tags": [ + "API Tokens" + ], + "summary": "Edit a token", + "operationId": "Tokens_EditTokenV2", + "parameters": [ + { + "name": "tokenId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EditTokenRequestV2" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/EditTokenRequestV2" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The edited token" + }, + "404": { + "description": "The token does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/2/tokens/{tokenId}/paused": { + "patch": { + "tags": [ + "API Tokens" + ], + "summary": "Set whether a token is paused. A paused token may not send shocker control messages.", + "operationId": "Tokens_SetTokenPaused", + "parameters": [ + { + "name": "tokenId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetTokenPausedRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SetTokenPausedRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The now-set paused state of the token.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenPausedResponse" + } + } + } + }, + "404": { + "description": "The token does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/shockers/{shockerId}": { + "patch": { + "tags": [ + "Shockers" + ], + "summary": "Edit a shocker", + "operationId": "Shocker_EditShocker", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewShocker" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/NewShocker" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully updated shocker", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Shocker does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "get": { + "tags": [ + "Shockers" + ], + "summary": "Get information about a shocker.", + "operationId": "Shocker_GetShockerById", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The shocker information was successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfShockerWithDevice" + } + } + } + }, + "404": { + "description": "The shocker does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "delete": { + "tags": [ + "Shockers" + ], + "summary": "Remove a shocker", + "operationId": "Shocker_RemoveShocker", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully deleted shocker", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Shocker does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/{shockerId}/logs": { + "get": { + "tags": [ + "Shockers" + ], + "summary": "Get the logs for a shocker", + "operationId": "Shocker_GetShockerLogs", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "offset", + "in": "query", + "description": "", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer", + "default": 0 + } + }, + { + "name": "limit", + "in": "query", + "description": "", + "schema": { + "maximum": 500, + "minimum": 1, + "type": "integer", + "default": 100 + } + } + ], + "responses": { + "200": { + "description": "The logs", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfLogEntry" + } + } + } + }, + "404": { + "description": "Shocker does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/logs": { + "get": { + "tags": [ + "Shockers" + ], + "summary": "Get a paged set of control logs across the caller's shockers.", + "operationId": "Shocker_GetAllShockerLogs", + "parameters": [ + { + "name": "page", + "in": "query", + "description": "1-based page index. Values below 1 are clamped to 1.", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + }, + { + "name": "pageSize", + "in": "query", + "description": "Number of items per page. Clamped to `[1, uint PaginationQuery.MaxPageSize]`.", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "description": "Optional free-text search term. Whitespace is trimmed; empty becomes null.\nEndpoints decide which fields the term is matched against.", + "schema": { + "type": "string" + } + }, + { + "name": "sort", + "in": "query", + "description": "Optional sort key. Endpoints register the allowed keys and translate them to\nthe underlying column(s). Unknown values fall back to the endpoint default.", + "schema": { + "type": "string" + } + }, + { + "name": "sortDir", + "in": "query", + "description": "Sort direction. Defaults to SortDirection.Desc when omitted, since list\nendpoints almost always want \"newest/highest first\" as the default.", + "schema": { + "$ref": "#/components/schemas/SortDirection" + } + }, + { + "name": "shockerIds", + "in": "query", + "description": "Optional shocker ID filter. When omitted or empty, logs for all of the caller's shockers are returned.", + "schema": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + } + ], + "responses": { + "200": { + "description": "A page of logs.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedResultOfLogEntryWithHub" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/shared": { + "get": { + "tags": [ + "Shockers" + ], + "summary": "List all shockers shared with the authenticated user.", + "operationId": "Shocker_ListSharedShockers", + "responses": { + "200": { + "description": "The shockers were successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfOwnerShockerResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/own": { + "get": { + "tags": [ + "Shockers" + ], + "summary": "List all shockers belonging to the authenticated user.", + "operationId": "Shocker_ListShockers", + "responses": { + "200": { + "description": "The shockers were successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfDeviceWithShockersResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/{shockerId}/pause": { + "post": { + "tags": [ + "Shockers" + ], + "summary": "Pause or unpause a shocker", + "operationId": "Shocker_PauseShocker", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PauseRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PauseRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully set pause state", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfboolean" + } + } + } + }, + "404": { + "description": "Shocker not found or does not belong to you", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers": { + "post": { + "tags": [ + "Shockers" + ], + "summary": "Register a shocker", + "operationId": "Shocker_RegisterShocker", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewShocker" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/NewShocker" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Successfully created shocker", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfGuid" + } + } + } + }, + "400": { + "description": "You can have a maximum of 11 Shockers per Device.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "404": { + "description": "Device does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shockers/control": { + "post": { + "tags": [ + "Shockers" + ], + "summary": "Send a control message to shockers", + "operationId": "Shocker_SendControl", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ControlRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ControlRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The control messages were successfully sent.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "412": { + "description": "Precondition Failed", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/{shockerId}/shares": { + "get": { + "tags": [ + "Shockers" + ], + "summary": "Get all user shares for a shocker", + "operationId": "Shocker_GetUserShares", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "Id of the shocker", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfShareInfo" + } + } + } + }, + "404": { + "description": "The shocker does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "post": { + "tags": [ + "Shockers" + ], + "summary": "Create a share code for a shocker", + "operationId": "Shocker_ShockerShareCodeCreate", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShockerPermLimitPair" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ShockerPermLimitPair" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The share code was successfully created.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfGuid" + } + } + } + }, + "404": { + "description": "Shocker does not exists or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/{shockerId}/shareCodes": { + "get": { + "tags": [ + "Shockers" + ], + "summary": "List all share codes for a shocker", + "operationId": "Shocker_ShockerShareCodeList", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfShareCodeInfo" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/{shockerId}/shares/{sharedWithUserId}": { + "delete": { + "tags": [ + "Shockers" + ], + "summary": "Remove a share for a shocker", + "operationId": "Shocker_ShockerShareRemove", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "sharedWithUserId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully removed share code" + }, + "404": { + "description": "Share does not exists or device/shocker does not belong to you nor is shared with you", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "patch": { + "tags": [ + "Shockers" + ], + "summary": "Update a share for a shocker", + "operationId": "Shocker_ShockerShareCodeUpdate", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "sharedWithUserId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShockerPermLimitPair" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ShockerPermLimitPair" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully updated share code" + }, + "404": { + "description": "The share code does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shockers/{shockerId}/shares/{sharedWithUserId}/pause": { + "post": { + "tags": [ + "Shockers" + ], + "summary": "Pause/Unpause a share code for a shocker", + "operationId": "Shocker_ShockerShareCodePause", + "parameters": [ + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "sharedWithUserId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PauseRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PauseRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully updated pause status share", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfboolean" + } + } + } + }, + "404": { + "description": "The share code does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shares/code/{shareCodeId}": { + "delete": { + "tags": [ + "Shocker Shares" + ], + "summary": "Delete a share code", + "operationId": "Shares_DeleteShareCode", + "parameters": [ + { + "name": "shareCodeId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Deleted share code", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Share code not found or does not belong to you", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + }, + "post": { + "tags": [ + "Shocker Shares" + ], + "summary": "Link a share code to your account", + "operationId": "Shares_LinkShareCode", + "parameters": [ + { + "name": "shareCodeId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Linked share code", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "400": { + "description": "You cannot link your own shocker code / You already have this shocker linked to your account", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "404": { + "description": "Share code not found or does not belong to you", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "500": { + "description": "Error while linking share code to your account" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/2/shares/user/invites": { + "post": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_CreateShareInvite", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateShareRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateShareRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "string", + "format": "uuid" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shares/user": { + "get": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_GetSharesByUsers", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/V2UserShares" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2UserShares" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/V2UserShares" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shares/user/invites/outgoing": { + "get": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_GetOutgoingInvitesList", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareInviteBaseDetails" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareInviteBaseDetails" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareInviteBaseDetails" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shares/user/invites/incoming": { + "get": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_GetIncomingInvitesList", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareInviteBaseDetails" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareInviteBaseDetails" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareInviteBaseDetails" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shares/user/invites/outgoing/{inviteId}": { + "delete": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_DeleteOutgoingInvite", + "parameters": [ + { + "name": "inviteId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shares/user/invites/incoming/{inviteId}": { + "delete": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_DenyIncomingInvite", + "parameters": [ + { + "name": "inviteId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "post": { + "tags": [ + "User Shocker Shares" + ], + "summary": "Accept a share request and share the shockers with the current user.", + "operationId": "UserShares_RedeemInvite", + "parameters": [ + { + "name": "inviteId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/V2UserSharesListItem" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2UserSharesListItem" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/V2UserSharesListItem" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shares/user/{userId}/shockers/pause": { + "post": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_BulkPauseUserShareShockers", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PauseUserShareShockersRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/PauseUserShareShockersRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PauseUserShareShockersRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/PauseUserShareShockersResponse" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/PauseUserShareShockersResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/PauseUserShareShockersResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/shares/user/{userId}/shockers": { + "delete": { + "tags": [ + "User Shocker Shares" + ], + "operationId": "UserShares_BulkRemoveUserShareShockers", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + }, + "text/json": { + "schema": { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + }, + "application/*+json": { + "schema": { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/RemoveUserSharesResponse" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/RemoveUserSharesResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/RemoveUserSharesResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "patch": { + "tags": [ + "User Shocker Shares" + ], + "summary": "Update user shares for a shocker", + "operationId": "UserShares_BulkUserShareShockersUpdate", + "parameters": [ + { + "name": "userId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BulkUserShareShockersUpdateRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/BulkUserShareShockersUpdateRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully updated share code" + }, + "404": { + "description": "The share code does not exist or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shares/links/{publicShareId}/{shockerId}": { + "post": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Add a shocker to a public share", + "operationId": "ShareLinks_AddShocker", + "parameters": [ + { + "name": "publicShareId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully added shocker", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Public share or shocker does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "Shocker already exists in public share", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "patch": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Edit a shocker in a public share", + "operationId": "ShareLinks_EditShocker", + "parameters": [ + { + "name": "publicShareId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicShareEditShocker" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PublicShareEditShocker" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully updated shocker", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Public share or shocker does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "400": { + "description": "Shocker does not exist in public share" + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "delete": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Remove a shocker from a public share", + "operationId": "ShareLinks_RemoveShocker", + "parameters": [ + { + "name": "publicShareId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully removed shocker", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Public share or shocker does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "400": { + "description": "Shocker does not exist in public share" + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shares/links": { + "post": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Create a new public share", + "operationId": "ShareLinks_CreatePublicShare", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicShareCreate" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PublicShareCreate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The created public share", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfGuid" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "get": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Get all public shares for the current user", + "operationId": "ShareLinks_List", + "responses": { + "200": { + "description": "All public shares for the current user", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfOwnPublicShareResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shares/links/{publicShareId}": { + "delete": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Deletes a public share", + "operationId": "ShareLinks_DeletePublicShare", + "parameters": [ + { + "name": "publicShareId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Deleted public share", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Public share not found or does not belong to you", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/shares/links/{publicShareId}/{shockerId}/pause": { + "post": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Pause a shocker in a public share", + "operationId": "ShareLinks_PauseShocker", + "parameters": [ + { + "name": "publicShareId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "shockerId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PauseRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PauseRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully updated paused state shocker", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfPauseReason" + } + } + } + }, + "404": { + "description": "Public share or shocker does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "400": { + "description": "Shocker does not exist in public share" + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/sessions/{sessionId}": { + "delete": { + "tags": [ + "Sessions" + ], + "operationId": "Sessions_DeleteSession", + "parameters": [ + { + "name": "sessionId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/sessions": { + "get": { + "tags": [ + "Sessions" + ], + "operationId": "Sessions_ListSessions", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LoginSessionResponse" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/sessions/self": { + "get": { + "tags": [ + "Sessions" + ], + "summary": "Gets information about the current token used to access this endpoint", + "operationId": "Sessions_GetSelfSession", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/LoginSessionResponse" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginSessionResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/LoginSessionResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/public/stats": { + "get": { + "tags": [ + "Meta" + ], + "summary": "Gets online devices statistics", + "operationId": "Public_GetOnlineDevicesStatistics", + "responses": { + "200": { + "description": "The statistics were successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfStatsResponse" + } + } + } + } + } + } + }, + "/1/public/shares/links/{publicShareId}": { + "get": { + "tags": [ + "Public Shocker Shares" + ], + "summary": "Gets information about a public share.", + "operationId": "Public_GetPublicShare", + "parameters": [ + { + "name": "publicShareId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The public share information was successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfPublicShareResponse" + } + } + } + }, + "404": { + "description": "The public share does not exist.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/1/integrations/control-stats/changes": { + "post": { + "tags": [ + "Integrations" + ], + "summary": "Lets a service holding many users keep their lifetime control stats in sync with a single call per tick.\nReturns the lifetime totals of every requested user whose stats changed since the given cursor.", + "description": "Requires an automation token granting `ControlStatsRead`. \"Changed since\" is answered from when each\ncontrol log was written, so late writes are still picked up. The lookback is widened by\nTimeSpan IntegrationsController.ChangeOverlap, so a user can be reported again although nothing changed.", + "operationId": "Integrations_GetControlStatChanges", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ControlStatChangesRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ControlStatChangesRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ControlStatChangesRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The changed users' totals and the cursor to pass next time.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ControlStatChangesResponse" + } + } + } + }, + "403": { + "description": "No automation token granting ControlStatsRead was presented.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/1/devices/{deviceId}/ota": { + "get": { + "tags": [ + "Hub Management" + ], + "summary": "Gets the OTA update history for a device", + "operationId": "DevicesOta_GetOtaUpdateHistory", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "description": "Id of the device", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfIReadOnlyCollectionOfOtaItem" + } + } + } + }, + "404": { + "description": "Could not find device or you do not have access to it", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/devices": { + "get": { + "tags": [ + "Hub Management" + ], + "summary": "Get all devices for the current user", + "operationId": "Devices_ListDevices", + "responses": { + "200": { + "description": "All devices for the current user", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfDeviceResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/devices/{deviceId}": { + "get": { + "tags": [ + "Hub Management" + ], + "summary": "Get a device by its id", + "operationId": "Devices_GetDeviceById", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The device", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfDeviceWithTokenResponse" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "patch": { + "tags": [ + "Hub Management" + ], + "summary": "Edit a device", + "operationId": "Devices_EditDevice", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HubEditRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/HubEditRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successfully updated device" + }, + "404": { + "description": "Device does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "put": { + "tags": [ + "Hub Management" + ], + "summary": "Regenerate a device token", + "operationId": "Devices_RegenerateDeviceToken", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "description": "The id of the device to regenerate the token for", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully regenerated device token", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Device does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "500": { + "description": "Failed to save regenerated token" + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + }, + "delete": { + "tags": [ + "Hub Management" + ], + "summary": "Remove a device from current user's account", + "operationId": "Devices_RemoveDevice", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "description": "The id of the device to delete", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully deleted device" + }, + "404": { + "description": "Device does not exist", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/devices": { + "post": { + "tags": [ + "Hub Management" + ], + "summary": "Create a new device for the current user", + "operationId": "Devices_CreateDeviceV2", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HubCreateRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/HubCreateRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Successfully created device", + "content": { + "text/plain": { + "schema": { + "type": "string", + "format": "uuid" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/devices/{deviceId}/pair": { + "get": { + "tags": [ + "Hub Management" + ], + "summary": "Get a pair code for a device", + "operationId": "Devices_GetPairCode", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "description": "", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The pair code", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfstring" + } + } + } + }, + "404": { + "description": "Device does not exist or does not belong to you", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/devices/{deviceId}/lcg": { + "get": { + "tags": [ + "Hub Management" + ], + "summary": "Gets the live control gateway a hub is connected to, including its public port and the full\nlive-control WebSocket path (honoring the gateway's configured path prefix).", + "operationId": "Devices_GetLiveControlGatewayInfoV2", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Successfully retrieved live control gateway info", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LcgResponseV2" + } + } + } + }, + "404": { + "description": "Device does not exist or is not online", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/devices/{deviceId}/shockers": { + "get": { + "tags": [ + "Hub Management" + ], + "summary": "Get all shockers for a device", + "operationId": "Devices_GetShockers", + "parameters": [ + { + "name": "deviceId", + "in": "path", + "description": "The device id", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "All shockers for the device", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfShockerResponse" + } + } + } + }, + "404": { + "description": "Device does not exists or you do not have access to it.", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/2/device/assignLCG": { + "get": { + "tags": [ + "Hub Endpoints" + ], + "summary": "Gets the best suited LCG node for the client", + "operationId": "Device_GetLiveControlGatewayV2", + "parameters": [ + { + "name": "version", + "in": "query", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successfully assigned LCG node", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LcgNodeResponseV2" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "503": { + "description": "Unable to find suitable LCG node", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "HubToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:HubToken" + ] + } + }, + "/1/device/self": { + "get": { + "tags": [ + "Hub Endpoints" + ], + "summary": "Gets information about the authenticated device.", + "operationId": "Device_GetSelf", + "responses": { + "200": { + "description": "The device information was successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfDeviceSelfResponse" + } + } + } + } + }, + "security": [ + { + "HubToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:HubToken" + ] + } + }, + "/1/device/pair/{pairCode}": { + "get": { + "tags": [ + "Hub Endpoints" + ], + "summary": "Pair a device with a pair code.", + "operationId": "Device_Pair", + "parameters": [ + { + "name": "pairCode", + "in": "path", + "description": "The pair code to pair with.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successfully assigned LCG node", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfstring" + } + } + } + }, + "404": { + "description": "No such pair code exists", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "HubToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:HubToken" + ] + } + }, + "/1/admin/automationTokens": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Creates an automation token. The secret is only returned once, in this response", + "operationId": "Admin_CreateAutomationToken", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateAutomationTokenDto" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateAutomationTokenDto" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/CreatedAutomationTokenDto" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedAutomationTokenDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreatedAutomationTokenDto" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "get": { + "tags": [ + "Admin" + ], + "summary": "Lists all automation tokens", + "operationId": "Admin_ListAutomationTokens", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AutomationTokenDto" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AutomationTokenDto" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AutomationTokenDto" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/automationTokens/{id}": { + "delete": { + "tags": [ + "Admin" + ], + "summary": "Deletes an automation token together with every account it created. Refused while any of those\naccounts holds a privileged role", + "operationId": "Admin_DeleteAutomationToken", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "patch": { + "tags": [ + "Admin" + ], + "summary": "Updates an automation token", + "operationId": "Admin_PatchAutomationToken", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PatchAutomationTokenDto" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PatchAutomationTokenDto" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/AutomationTokenDto" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationTokenDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/AutomationTokenDto" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/automationTokens/{id}/rotate": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Rotates the secret of an automation token. The new secret is only returned once, in this response", + "operationId": "Admin_RotateAutomationToken", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/CreatedAutomationTokenDto" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedAutomationTokenDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreatedAutomationTokenDto" + } + } + } + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/config": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Gets all configuration items", + "operationId": "Admin_ConfigurationList", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConfigurationItemDto" + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "post": { + "tags": [ + "Admin" + ], + "summary": "Adds a new configuration", + "operationId": "Admin_ConfigurationAdd", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigurationAddItemRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ConfigurationAddItemRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Configuration added" + }, + "400": { + "description": "Invalid name or value format", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "Already exists", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "put": { + "tags": [ + "Admin" + ], + "summary": "Updates an existing configuration", + "operationId": "Admin_ConfigurationUpdate", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigurationUpdateItemRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ConfigurationUpdateItemRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Configuration updated (or nothing to do)" + }, + "400": { + "description": "Invalid name or value format or type mismatch", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/config/{name}": { + "delete": { + "tags": [ + "Admin" + ], + "summary": "Deletes a configuration", + "operationId": "Admin_ConfigurationDelete", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Configuration deleted" + }, + "400": { + "description": "Invalid name format", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/users/{userId}/deactivate": { + "put": { + "tags": [ + "Admin" + ], + "summary": "Deactivates a user", + "operationId": "Admin_DeactivateUser", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "deleteLater", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "reason", + "in": "query", + "schema": { + "maxLength": 512, + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/apitokens/{tokenId}": { + "delete": { + "tags": [ + "Admin" + ], + "summary": "Deletes an API token", + "operationId": "Admin_DeleteApiToken", + "parameters": [ + { + "name": "tokenId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/users/{userId}": { + "delete": { + "tags": [ + "Admin" + ], + "summary": "Deletes a user", + "operationId": "Admin_DeleteUser", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "reason", + "in": "query", + "schema": { + "maxLength": 512, + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "get": { + "tags": [ + "Admin" + ], + "summary": "Gets a user by id", + "operationId": "Admin_GetUserById", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "User info", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminUserView" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "patch": { + "tags": [ + "Admin" + ], + "summary": "Edits a user", + "operationId": "Admin_ModifyUser", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserPatchDto" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UserPatchDto" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not found" + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox/bulk/requeue": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Requeues many email outbox messages at once. Each id is treated exactly like the single-message\nrequeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing\nids are skipped. Returns how many rows were actually requeued.", + "operationId": "Admin_BulkRequeueEmailOutbox", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Bulk requeue applied", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkResultDto" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox/bulk/cancel": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are\nnot pending (already sending or terminal) and missing ids are skipped. Returns how many rows were\nactually cancelled.", + "operationId": "Admin_BulkCancelEmailOutbox", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Bulk cancel applied", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkResultDto" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox/bulk/delete": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many\nrows were actually deleted.", + "operationId": "Admin_BulkDeleteEmailOutbox", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Bulk delete applied", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxBulkResultDto" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox/{id}/cancel": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only\npending messages can be cancelled; a message already being sent or in a terminal state cannot.", + "operationId": "Admin_CancelEmailOutbox", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Cancelled" + }, + "404": { + "description": "No such message", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "Message is not pending", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox/{id}": { + "delete": { + "tags": [ + "Admin" + ], + "summary": "Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds\nthe row gone and does nothing, so a delete never corrupts an in-flight send.", + "operationId": "Admin_DeleteEmailOutbox", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Deleted" + }, + "404": { + "description": "No such message", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Lists email outbox messages, paginated. Supports the same OData-style\n`$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`,\n`recipient ilike '%@example.com'`). Defaults to newest first.", + "operationId": "Admin_GetEmailOutbox", + "parameters": [ + { + "name": "$filter", + "in": "query", + "schema": { + "type": "string", + "default": "" + } + }, + { + "name": "$orderby", + "in": "query", + "schema": { + "type": "string", + "default": "" + } + }, + { + "name": "$offset", + "in": "query", + "schema": { + "maximum": 2147483647, + "minimum": 0, + "type": "integer", + "format": "int32", + "default": 0 + } + }, + { + "name": "$limit", + "in": "query", + "schema": { + "maximum": 1000, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 100 + } + } + ], + "responses": { + "200": { + "description": "Paginated email outbox messages", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaginatedOfEmailOutboxMessageDto" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox/{id}/requeue": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now,\nwith a fresh attempt budget, and nudges the delivery consumer to send it immediately.", + "operationId": "Admin_RequeueEmailOutbox", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Requeued" + }, + "404": { + "description": "No such message", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "Message is pending or currently being sent", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/outbox/stats": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Returns the number of email outbox messages in each delivery state.", + "operationId": "Admin_GetEmailOutboxStats", + "responses": { + "200": { + "description": "Per-status counts", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxStatsDto" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/email/test": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Enqueues a preview/test email of the chosen type to the chosen address. It flows through the\nnormal durable delivery pipeline - visible in the outbox listing - but is rendered with\nplaceholder data and a dummy link, so it touches no request row and mints no token.", + "operationId": "Admin_SendTestEmail", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SendTestEmailDto" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SendTestEmailDto" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Test email enqueued", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmailOutboxMessageDto" + } + } + } + }, + "400": { + "description": "Invalid recipient address", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/blacklist/emailProviders": { + "post": { + "tags": [ + "Admin" + ], + "operationId": "Admin_AddEmailProviderBlacklist", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddEmailProviderBlacklistDto" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/AddEmailProviderBlacklistDto" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "get": { + "tags": [ + "Admin" + ], + "operationId": "Admin_ListEmailProviderBlacklist", + "parameters": [ + { + "name": "match", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EmailProviderBlacklistDto" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EmailProviderBlacklistDto" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EmailProviderBlacklistDto" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/blacklist/emailProviders/{id}": { + "delete": { + "tags": [ + "Admin" + ], + "operationId": "Admin_RemoveEmailProviderBlacklist", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/audit-log": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Get audit log entries across all users. Optionally filter by subject user or actor.", + "operationId": "Admin_GetAdminAuditLog", + "parameters": [ + { + "name": "page", + "in": "query", + "description": "1-based page index. Values below 1 are clamped to 1.", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + }, + { + "name": "pageSize", + "in": "query", + "description": "Number of items per page. Clamped to `[1, uint PaginationQuery.MaxPageSize]`.", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "description": "Optional free-text search term. Whitespace is trimmed; empty becomes null.\nEndpoints decide which fields the term is matched against.", + "schema": { + "type": "string" + } + }, + { + "name": "sort", + "in": "query", + "description": "Optional sort key. Endpoints register the allowed keys and translate them to\nthe underlying column(s). Unknown values fall back to the endpoint default.", + "schema": { + "type": "string" + } + }, + { + "name": "sortDir", + "in": "query", + "description": "Sort direction. Defaults to SortDirection.Desc when omitted, since list\nendpoints almost always want \"newest/highest first\" as the default.", + "schema": { + "$ref": "#/components/schemas/SortDirection" + } + }, + { + "name": "userId", + "in": "query", + "description": "Optional: filter by the subject user (the account that was affected).", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "actorId", + "in": "query", + "description": "Optional: filter by the actor (who performed the action).", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "A page of audit log entries.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedResultOfAuditLogEntryResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/monitoring/onlineDevices": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Gets all online devices", + "operationId": "Admin_GetOnlineDevices", + "responses": { + "200": { + "description": "All online devices", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/monitoring/gateways": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Gets all online gateways", + "operationId": "Admin_GetOnlineGateways", + "responses": { + "200": { + "description": "All online gateways", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminOnlineGatewayResponse" + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/users": { + "get": { + "tags": [ + "Admin" + ], + "summary": "Gets all users, paginated", + "operationId": "Admin_GetUsers", + "parameters": [ + { + "name": "$filter", + "in": "query", + "schema": { + "type": "string", + "default": "" + } + }, + { + "name": "$orderby", + "in": "query", + "schema": { + "type": "string", + "default": "" + } + }, + { + "name": "$offset", + "in": "query", + "schema": { + "maximum": 2147483647, + "minimum": 0, + "type": "integer", + "format": "int32", + "default": 0 + } + }, + { + "name": "$limit", + "in": "query", + "schema": { + "maximum": 1000, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 100 + } + } + ], + "responses": { + "200": { + "description": "Paginated users", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaginatedOfAdminUsersView" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/users/{userId}/reactivate": { + "put": { + "tags": [ + "Admin" + ], + "summary": "Reactivates a user", + "operationId": "Admin_ReactivateUser", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "reason", + "in": "query", + "schema": { + "maxLength": 512, + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/users/{userId}/email": { + "put": { + "tags": [ + "Admin" + ], + "summary": "Sets a users email to the supplied value", + "operationId": "Admin_SetUserEmail", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetUserEmailRequestBody" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SetUserEmailRequestBody" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SetUserEmailRequestBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/users/{userId}/name": { + "put": { + "tags": [ + "Admin" + ], + "summary": "Sets a users name to the supplied value", + "operationId": "Admin_SetUserName", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetUserNameRequestBody" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SetUserNameRequestBody" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SetUserNameRequestBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "The target account is deactivated or not yet activated", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/users/{userId}/password": { + "put": { + "tags": [ + "Admin" + ], + "summary": "Sets a users password to the supplied value", + "operationId": "Admin_SetUserPassword", + "parameters": [ + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetUserPasswordRequestBody" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SetUserPasswordRequestBody" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SetUserPasswordRequestBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "The target account is deactivated or not yet activated", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/blacklist/usernames": { + "post": { + "tags": [ + "Admin" + ], + "operationId": "Admin_AddUsernameBlacklist", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddUsernameBlacklistDto" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/AddUsernameBlacklistDto" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "get": { + "tags": [ + "Admin" + ], + "operationId": "Admin_ListUsernameBlacklist", + "parameters": [ + { + "name": "match", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserNameBlacklistDto" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserNameBlacklistDto" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserNameBlacklistDto" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/blacklist/usernames/{id}": { + "delete": { + "tags": [ + "Admin" + ], + "operationId": "Admin_RemoveUsernameBlacklist", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/webhooks": { + "post": { + "tags": [ + "Admin" + ], + "summary": "Creates a webhook", + "operationId": "Admin_AddWebhook", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddWebhookDto" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/AddWebhookDto" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + }, + "get": { + "tags": [ + "Admin" + ], + "summary": "List webhooks", + "operationId": "Admin_ListWebhooks", + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WebhookDto" + } + } + }, + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WebhookDto" + } + } + }, + "text/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WebhookDto" + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/admin/webhooks/{id}": { + "delete": { + "tags": [ + "Admin" + ], + "summary": "Removes a webhook", + "operationId": "Admin_RemoveWebhook", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "404": { + "description": "Not Found", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "Unauthorized" + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie", + "Roles:Admin" + ] + } + }, + "/1/account/activate": { + "post": { + "tags": [ + "Account" + ], + "summary": "Activate account", + "operationId": "Account_Activate", + "parameters": [ + { + "name": "token", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/1/account/username/check": { + "post": { + "tags": [ + "Account" + ], + "summary": "Check if a username is available", + "operationId": "Account_CheckUsername", + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeUsernameRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangeUsernameRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/UsernameCheckResponse" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UsernameCheckResponse" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UsernameCheckResponse" + } + } + } + } + } + } + }, + "/2/account/login": { + "post": { + "tags": [ + "Account" + ], + "summary": "Authenticate a user", + "operationId": "Account_LoginV2", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginV2" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/LoginV2" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "User successfully logged in", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginV2OkResponse" + } + } + } + }, + "401": { + "description": "Invalid username or password", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/1/account/logout": { + "post": { + "tags": [ + "Account" + ], + "operationId": "Account_Logout", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/1/account/password-reset/{passwordResetId}/{secret}": { + "get": { + "tags": [ + "Account" + ], + "summary": "Check if a password reset is in progress", + "operationId": "Account_PasswordResetCheckValid", + "parameters": [ + { + "name": "passwordResetId", + "in": "path", + "description": "The id of the password reset", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "secret", + "in": "path", + "description": "The secret of the password reset", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Valid password reset process", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Password reset process not found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/1/account/password-reset/{passwordResetId}/{secret}/complete": { + "post": { + "tags": [ + "Account" + ], + "summary": "Complete a password reset process", + "operationId": "Account_PasswordResetComplete", + "parameters": [ + { + "name": "passwordResetId", + "in": "path", + "description": "The id of the password reset", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "secret", + "in": "path", + "description": "The secret of the password reset", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PasswordResetProcessData" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PasswordResetProcessData" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Password successfully changed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LegacyEmptyResponse" + } + } + } + }, + "404": { + "description": "Password reset process not found", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/2/account/password-reset": { + "post": { + "tags": [ + "Account" + ], + "summary": "Initiate a password reset", + "operationId": "Account_PasswordResetInitiateV2", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PasswordResetRequestV2" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PasswordResetRequestV2" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Password reset email sent if the email is associated to an registered account" + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/1/account/activate/resend": { + "post": { + "tags": [ + "Account" + ], + "summary": "Resend the account activation email for the account this browser just signed up", + "description": "Identifies the account by the activation-resend cookie set on signup, not by an email address,\nso it can only target an account created from this browser and can't be used to probe registered emails.", + "operationId": "Account_ResendActivation", + "responses": { + "200": { + "description": "Activation email enqueued" + }, + "400": { + "description": "No pending activation for this browser (missing/expired cookie, or already activated)", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "429": { + "description": "An activation email was sent too recently", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/2/account/signup": { + "post": { + "tags": [ + "Account" + ], + "summary": "Signs up a new user", + "operationId": "Account_SignUpV2", + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SignUpV2" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SignUpV2" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "User successfully signed up" + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "400": { + "description": "Username or email already exists" + } + } + } + }, + "/1/account/email-change/verify": { + "post": { + "tags": [ + "Account" + ], + "summary": "Verify a pending email change using the token from the verification email.", + "operationId": "Account_EmailVerify", + "parameters": [ + { + "name": "token", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Email change verified and applied" + }, + "400": { + "description": "Token is invalid, already used, or the request has expired", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "The new email address was claimed by another account before verification completed", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + } + } + }, + "/1/account/verify-email": { + "post": { + "tags": [ + "Account" + ], + "summary": "Verify a pending email change. Deprecated: use POST /email-change/verify instead.", + "operationId": "Account_EmailVerifyLegacy", + "parameters": [ + { + "name": "token", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Email change verified and applied" + }, + "400": { + "description": "Token is invalid, already used, or the request has expired", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "The new email address was claimed by another account before verification completed", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "deprecated": true + } + }, + "/1/account/email-change": { + "post": { + "tags": [ + "Account" + ], + "summary": "Initiate an email change for the current user. A verification link is sent to the new\naddress; the change is not applied until that link is opened.", + "operationId": "AuthenticatedAccount_ChangeEmail", + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeEmailRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangeEmailRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "429": { + "description": "Too Many Requests", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/account/password": { + "post": { + "tags": [ + "Account" + ], + "summary": "Change the password of the current user", + "operationId": "AuthenticatedAccount_ChangePassword", + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/account/username": { + "post": { + "tags": [ + "Account" + ], + "summary": "Change the username of the current user", + "operationId": "AuthenticatedAccount_ChangeUsername", + "requestBody": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeUsernameRequest" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangeUsernameRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/account": { + "delete": { + "tags": [ + "Account" + ], + "summary": "Deactivate currently logged in account", + "operationId": "AuthenticatedAccount_Deactivate", + "responses": { + "204": { + "description": "Done." + }, + "403": { + "description": "Forbidden", + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/OpenShockProblem" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + }, + "get": { + "tags": [ + "Account" + ], + "summary": "Get the current user's account information.", + "operationId": "AuthenticatedAccount_GetSelf", + "responses": { + "200": { + "description": "The account information was successfully retrieved.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserSelfResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + }, + { + "ApiToken": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie,ApiToken" + ] + } + }, + "/1/account/audit-log": { + "get": { + "tags": [ + "Account" + ], + "summary": "Get the audit log for the current user's account.", + "operationId": "AuthenticatedAccount_GetAuditLog", + "parameters": [ + { + "name": "page", + "in": "query", + "description": "1-based page index. Values below 1 are clamped to 1.", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + }, + { + "name": "pageSize", + "in": "query", + "description": "Number of items per page. Clamped to `[1, uint PaginationQuery.MaxPageSize]`.", + "schema": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "description": "Optional free-text search term. Whitespace is trimmed; empty becomes null.\nEndpoints decide which fields the term is matched against.", + "schema": { + "type": "string" + } + }, + { + "name": "sort", + "in": "query", + "description": "Optional sort key. Endpoints register the allowed keys and translate them to\nthe underlying column(s). Unknown values fall back to the endpoint default.", + "schema": { + "type": "string" + } + }, + { + "name": "sortDir", + "in": "query", + "description": "Sort direction. Defaults to SortDirection.Desc when omitted, since list\nendpoints almost always want \"newest/highest first\" as the default.", + "schema": { + "$ref": "#/components/schemas/SortDirection" + } + } + ], + "responses": { + "200": { + "description": "A page of audit log entries.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedResultOfAuditLogEntryResponse" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/account/connections/{provider}": { + "delete": { + "tags": [ + "Account" + ], + "summary": "Remove an existing OAuth connection for the current user.", + "operationId": "AuthenticatedAccount_RemoveOAuthConnection", + "parameters": [ + { + "name": "provider", + "in": "path", + "description": "Provider key (e.g. `discord`).", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Connection removed." + }, + "404": { + "description": "No connection found for this provider.", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + }, + "/1/account/connections": { + "get": { + "tags": [ + "Account" + ], + "summary": "List OAuth connections linked to the current user.", + "operationId": "AuthenticatedAccount_ListOAuthConnections", + "responses": { + "200": { + "description": "Returns the list of connections.", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OAuthConnectionResponse" + } + } + } + } + } + }, + "security": [ + { + "UserSessionCookie": [] + } + ], + "x-authorization": [ + "AuthenticationSchemes:UserSessionCookie" + ] + } + } + }, + "components": { + "schemas": { + "AddEmailProviderBlacklistDto": { + "required": [ + "domains" + ], + "type": "object", + "properties": { + "domains": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "AddUsernameBlacklistDto": { + "required": [ + "value", + "matchType" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "matchType": { + "$ref": "#/components/schemas/MatchTypeEnum" + } + } + }, + "AddWebhookDto": { + "required": [ + "name", + "url" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 0, + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + } + }, + "AdminOnlineDeviceResponse": { + "required": [ + "id", + "name", + "owner", + "firmwareVersion", + "gateway", + "connectedAt", + "userAgent", + "bootedAt", + "latencyMs", + "rssi", + "country", + "ip", + "asn", + "asnOrg" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "owner": { + "$ref": "#/components/schemas/BasicUserInfo" + }, + "firmwareVersion": { + "examples": [ + "1.0.0-dev+a16f2" + ], + "title": "SemVer", + "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$", + "type": "string" + }, + "gateway": { + "type": "string" + }, + "connectedAt": { + "type": "string", + "format": "date-time" + }, + "userAgent": { + "type": [ + "null", + "string" + ] + }, + "bootedAt": { + "type": "string", + "format": "date-time" + }, + "latencyMs": { + "maximum": 65535, + "minimum": 0, + "type": [ + "null", + "integer" + ], + "format": "int32" + }, + "rssi": { + "type": [ + "null", + "integer" + ], + "format": "int32" + }, + "country": { + "type": [ + "null", + "string" + ] + }, + "ip": { + "examples": [ + "127.0.0.1" + ], + "title": "IpAddress", + "type": [ + "null", + "string" + ], + "description": "An IPv4 or IPv6 address in its textual form." + }, + "asn": { + "type": [ + "null", + "integer" + ], + "format": "int64" + }, + "asnOrg": { + "type": [ + "null", + "string" + ] + } + } + }, + "AdminOnlineGatewayResponse": { + "required": [ + "id", + "host", + "port", + "pathPrefix", + "country", + "latitude", + "longitude", + "load", + "environment", + "connectedHubs" + ], + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "host": { + "type": "string" + }, + "port": { + "maximum": 65535, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "pathPrefix": { + "type": "string" + }, + "country": { + "type": "string" + }, + "latitude": { + "type": [ + "null", + "number" + ], + "format": "double" + }, + "longitude": { + "type": [ + "null", + "number" + ], + "format": "double" + }, + "load": { + "maximum": 255, + "minimum": 0, + "type": "integer", + "description": "Load the gateway advertises for hub assignment, in percent", + "format": "int32" + }, + "environment": { + "type": "string" + }, + "connectedHubs": { + "type": "integer", + "format": "int32" + } + } + }, + "AdminUserView": { + "required": [ + "id", + "name", + "email", + "passwordHashType", + "roles", + "createdAt", + "activatedAt", + "createdByAutomationTokenId", + "activationRequest", + "deactivation", + "hubs", + "apiTokens", + "usersNameChanges", + "usersEmailChanges", + "passwordResets", + "shockerControlLogsCount" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "email": { + "type": "string" + }, + "passwordHashType": { + "$ref": "#/components/schemas/PasswordHashingAlgorithm" + }, + "roles": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoleType" + } + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "activatedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "createdByAutomationTokenId": { + "type": [ + "null", + "string" + ], + "format": "uuid" + }, + "activationRequest": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/AdminUserView_UserActivationRequest" + } + ] + }, + "deactivation": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/AdminUserView_UserDeactivation" + } + ] + }, + "hubs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUserView_Hub" + } + }, + "apiTokens": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUserView_ApiToken" + } + }, + "usersNameChanges": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUserView_NameChange" + } + }, + "usersEmailChanges": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUserView_EmailChange" + } + }, + "passwordResets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUserView_PasswordReset" + } + }, + "shockerControlLogsCount": { + "type": "integer", + "format": "int32" + } + } + }, + "AdminUserView_ApiToken": { + "required": [ + "id", + "name", + "permissions", + "validUntil", + "lastUsed", + "createdAt", + "createdByIp" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionType" + } + }, + "validUntil": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "lastUsed": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "createdByIp": { + "examples": [ + "127.0.0.1" + ], + "title": "IpAddress", + "type": "string", + "description": "An IPv4 or IPv6 address in its textual form." + } + } + }, + "AdminUserView_EmailChange": { + "required": [ + "id", + "email", + "createdAt", + "usedAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "email": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "usedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + } + } + }, + "AdminUserView_Hub": { + "required": [ + "id", + "name", + "createdAt", + "shockers" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "shockers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUserView_Shocker" + } + } + } + }, + "AdminUserView_NameChange": { + "required": [ + "id", + "oldName", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "oldName": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + }, + "AdminUserView_PasswordReset": { + "required": [ + "id", + "createdAt", + "usedAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "usedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + } + } + }, + "AdminUserView_Shocker": { + "required": [ + "id", + "name", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + }, + "AdminUserView_UserActivationRequest": { + "required": [ + "emailSendAttempts", + "createdAt" + ], + "type": "object", + "properties": { + "emailSendAttempts": { + "type": "integer", + "format": "int32" + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + }, + "AdminUserView_UserDeactivation": { + "required": [ + "deactivatedBy", + "scheduledDeletionTime", + "deactivatedAt" + ], + "type": "object", + "properties": { + "deactivatedBy": { + "$ref": "#/components/schemas/AdminUserView_UserRef" + }, + "scheduledDeletionTime": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "deactivatedAt": { + "type": "string", + "format": "date-time" + } + } + }, + "AdminUserView_UserRef": { + "required": [ + "id", + "name" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + } + } + }, + "AdminUsersView": { + "required": [ + "id", + "name", + "email", + "passwordHashType", + "roles", + "createdAt", + "activatedAt", + "createdByAutomationTokenId", + "deactivatedAt", + "deactivatedByUserId", + "apiTokenCount", + "passwordResetCount", + "shockerUserShareCount", + "shockerPublicShareCount", + "emailChangeRequestCount", + "nameChangeRequestCount", + "deviceCount", + "shockerCount", + "shockerControlLogCount" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "email": { + "type": "string" + }, + "passwordHashType": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/PasswordHashingAlgorithm" + } + ] + }, + "roles": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoleType" + } + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "activatedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "createdByAutomationTokenId": { + "type": [ + "null", + "string" + ], + "format": "uuid" + }, + "deactivatedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "deactivatedByUserId": { + "type": [ + "null", + "string" + ], + "format": "uuid" + }, + "apiTokenCount": { + "type": "integer", + "format": "int32" + }, + "passwordResetCount": { + "type": "integer", + "format": "int32" + }, + "shockerUserShareCount": { + "type": "integer", + "format": "int32" + }, + "shockerPublicShareCount": { + "type": "integer", + "format": "int32" + }, + "emailChangeRequestCount": { + "type": "integer", + "format": "int32" + }, + "nameChangeRequestCount": { + "type": "integer", + "format": "int32" + }, + "deviceCount": { + "type": "integer", + "format": "int32" + }, + "shockerCount": { + "type": "integer", + "format": "int32" + }, + "shockerControlLogCount": { + "type": "integer", + "format": "int32" + } + } + }, + "AuditAction": { + "enum": [ + "Login", + "Logout", + "PasswordChanged", + "EmailChangeRequested", + "EmailChanged", + "UsernameChanged", + "ApiTokenCreated", + "ApiTokenDeleted", + "OAuthConnected", + "OAuthDisconnected", + "AccountDeactivated", + "AccountReactivated", + "AccountDeleted", + "AutomationTokenCreated", + "AutomationTokenUpdated", + "AutomationTokenRotated", + "AutomationTokenDeleted", + "AutomationTokenUsed" + ], + "type": "string" + }, + "AuditLogEntryResponse": { + "required": [ + "id", + "userId", + "actorId", + "action", + "reason", + "ipAddress", + "userAgent", + "metadata", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "userId": { + "type": "string", + "format": "uuid" + }, + "actorId": { + "type": [ + "null", + "string" + ], + "format": "uuid" + }, + "action": { + "$ref": "#/components/schemas/AuditAction" + }, + "reason": { + "type": [ + "null", + "string" + ] + }, + "ipAddress": { + "examples": [ + "127.0.0.1" + ], + "title": "IpAddress", + "type": [ + "null", + "string" + ], + "description": "An IPv4 or IPv6 address in its textual form." + }, + "userAgent": { + "type": [ + "null", + "string" + ] + }, + "metadata": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/AuditMetadata" + } + ] + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + }, + "AuditMetadata": { + "required": [ + "t" + ], + "type": "object", + "anyOf": [ + { + "$ref": "#/components/schemas/AuditMetadataLoginMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataUsernameChangedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataEmailChangeRequestedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataEmailChangedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataApiTokenCreatedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataApiTokenDeletedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataOAuthConnectedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataOAuthDisconnectedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataAccountDeactivatedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataAutomationTokenCreatedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataAutomationTokenUpdatedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataAutomationTokenRotatedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataAutomationTokenDeletedMetadata" + }, + { + "$ref": "#/components/schemas/AuditMetadataAutomationTokenUsedMetadata" + } + ], + "discriminator": { + "propertyName": "t", + "mapping": { + "login": "#/components/schemas/AuditMetadataLoginMetadata", + "usernameChanged": "#/components/schemas/AuditMetadataUsernameChangedMetadata", + "emailChangeRequested": "#/components/schemas/AuditMetadataEmailChangeRequestedMetadata", + "emailChanged": "#/components/schemas/AuditMetadataEmailChangedMetadata", + "apiTokenCreated": "#/components/schemas/AuditMetadataApiTokenCreatedMetadata", + "apiTokenDeleted": "#/components/schemas/AuditMetadataApiTokenDeletedMetadata", + "oauthConnected": "#/components/schemas/AuditMetadataOAuthConnectedMetadata", + "oauthDisconnected": "#/components/schemas/AuditMetadataOAuthDisconnectedMetadata", + "accountDeactivated": "#/components/schemas/AuditMetadataAccountDeactivatedMetadata", + "automationTokenCreated": "#/components/schemas/AuditMetadataAutomationTokenCreatedMetadata", + "automationTokenUpdated": "#/components/schemas/AuditMetadataAutomationTokenUpdatedMetadata", + "automationTokenRotated": "#/components/schemas/AuditMetadataAutomationTokenRotatedMetadata", + "automationTokenDeleted": "#/components/schemas/AuditMetadataAutomationTokenDeletedMetadata", + "automationTokenUsed": "#/components/schemas/AuditMetadataAutomationTokenUsedMetadata" + } + } + }, + "AuditMetadataAccountDeactivatedMetadata": { + "required": [ + "deleteLater" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "accountDeactivated" + ], + "type": "string" + }, + "deleteLater": { + "type": "boolean" + } + } + }, + "AuditMetadataApiTokenCreatedMetadata": { + "required": [ + "tokenId", + "name", + "permissions" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "apiTokenCreated" + ], + "type": "string" + }, + "tokenId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "AuditMetadataApiTokenDeletedMetadata": { + "required": [ + "tokenId", + "name" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "apiTokenDeleted" + ], + "type": "string" + }, + "tokenId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + } + } + }, + "AuditMetadataAutomationTokenCreatedMetadata": { + "required": [ + "tokenId", + "name", + "types", + "autoCleanupUsers", + "autoCleanupAfter" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "automationTokenCreated" + ], + "type": "string" + }, + "tokenId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "types": { + "type": "array", + "items": { + "type": "string" + } + }, + "autoCleanupUsers": { + "type": "boolean" + }, + "autoCleanupAfter": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": [ + "null", + "string" + ] + } + } + }, + "AuditMetadataAutomationTokenDeletedMetadata": { + "required": [ + "tokenId", + "name", + "deletedAccountCount" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "automationTokenDeleted" + ], + "type": "string" + }, + "tokenId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "deletedAccountCount": { + "type": "integer", + "format": "int32" + } + }, + "description": "The token was deleted together with the int AutomationTokenDeletedMetadata.DeletedAccountCount accounts it created." + }, + "AuditMetadataAutomationTokenRotatedMetadata": { + "required": [ + "tokenId", + "name" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "automationTokenRotated" + ], + "type": "string" + }, + "tokenId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + } + } + }, + "AuditMetadataAutomationTokenUpdatedMetadata": { + "required": [ + "tokenId", + "name", + "types", + "autoCleanupUsers", + "autoCleanupAfter" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "automationTokenUpdated" + ], + "type": "string" + }, + "tokenId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "types": { + "type": "array", + "items": { + "type": "string" + } + }, + "autoCleanupUsers": { + "type": "boolean" + }, + "autoCleanupAfter": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": [ + "null", + "string" + ] + } + }, + "description": "The token's settings after the update." + }, + "AuditMetadataAutomationTokenUsedMetadata": { + "required": [ + "tokenId", + "name", + "flow" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "automationTokenUsed" + ], + "type": "string" + }, + "tokenId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "flow": { + "type": "string" + } + }, + "description": "An automation token was used on this account. string AutomationTokenUsedMetadata.Flow is a `AutomationTokenFlow` name." + }, + "AuditMetadataEmailChangeRequestedMetadata": { + "required": [ + "newEmail" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "emailChangeRequested" + ], + "type": "string" + }, + "newEmail": { + "type": "string" + } + } + }, + "AuditMetadataEmailChangedMetadata": { + "required": [ + "old", + "new" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "emailChanged" + ], + "type": "string" + }, + "old": { + "type": "string" + }, + "new": { + "type": "string" + } + } + }, + "AuditMetadataLoginMetadata": { + "required": [ + "sessionId" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "login" + ], + "type": "string" + }, + "sessionId": { + "type": "string", + "format": "uuid" + } + } + }, + "AuditMetadataOAuthConnectedMetadata": { + "required": [ + "provider" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "oauthConnected" + ], + "type": "string" + }, + "provider": { + "type": "string" + } + } + }, + "AuditMetadataOAuthDisconnectedMetadata": { + "required": [ + "provider" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "oauthDisconnected" + ], + "type": "string" + }, + "provider": { + "type": "string" + } + } + }, + "AuditMetadataUsernameChangedMetadata": { + "required": [ + "old", + "new" + ], + "type": "object", + "properties": { + "t": { + "enum": [ + "usernameChanged" + ], + "type": "string" + }, + "old": { + "type": "string" + }, + "new": { + "type": "string" + } + } + }, + "AutomationTokenDto": { + "required": [ + "id", + "name", + "types", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AutomationTokenType" + } + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "lastUsedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "lastRotatedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "useCount": { + "type": "integer", + "format": "int64" + }, + "autoCleanupUsers": { + "type": "boolean" + }, + "autoCleanupAfter": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": [ + "null", + "string" + ] + } + } + }, + "AutomationTokenType": { + "enum": [ + "Turnstile", + "RateLimit", + "ControlStatsRead" + ], + "type": "string", + "description": "A protection that an automation token is allowed to switch off, or a service capability it grants." + }, + "BackendInfoResponse": { + "required": [ + "version", + "commit", + "currentTime", + "frontendUrl", + "shortLinkUrl", + "turnstileSiteKey", + "oAuthProviders", + "isMailEnabled", + "isUserAuthenticated" + ], + "type": "object", + "properties": { + "version": { + "type": "string" + }, + "commit": { + "type": "string" + }, + "currentTime": { + "type": "string", + "format": "date-time" + }, + "frontendUrl": { + "type": "string", + "format": "uri" + }, + "shortLinkUrl": { + "type": "string", + "format": "uri" + }, + "turnstileSiteKey": { + "type": [ + "null", + "string" + ] + }, + "oAuthProviders": { + "type": "array", + "items": { + "type": "string" + } + }, + "isMailEnabled": { + "type": "boolean", + "description": "False when the instance has no mail provider configured. Accounts are then activated on\ncreation, and no flow that relies on an emailed link (activation, password reset, email\nchange) can complete." + }, + "isUserAuthenticated": { + "type": "boolean" + } + } + }, + "BasicUserInfo": { + "required": [ + "id", + "name", + "image" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "image": { + "type": "string", + "format": "uri" + } + } + }, + "BulkUserShareShockersUpdateRequest": { + "required": [ + "shockers", + "permissions", + "limits" + ], + "type": "object", + "properties": { + "shockers": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + }, + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + } + } + }, + "ChangeEmailRequest": { + "required": [ + "currentPassword", + "email" + ], + "type": "object", + "properties": { + "currentPassword": { + "minLength": 1, + "type": "string" + }, + "email": { + "examples": [ + "user@example.com" + ], + "type": "string" + } + } + }, + "ChangePasswordRequest": { + "required": [ + "currentPassword", + "newPassword" + ], + "type": "object", + "properties": { + "currentPassword": { + "minLength": 1, + "type": "string" + }, + "newPassword": { + "examples": [ + "Password123!" + ], + "type": "string" + } + } + }, + "ChangeUsernameRequest": { + "required": [ + "username" + ], + "type": "object", + "properties": { + "username": { + "examples": [ + "String" + ], + "type": "string" + } + } + }, + "ConfigurationAddItemRequest": { + "required": [ + "name", + "description", + "type", + "value" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 0, + "type": "string", + "description": "The unique name of the configuration item.\nMust consist of uppercase letters and underscores only." + }, + "description": { + "maxLength": 255, + "minLength": 0, + "type": "string", + "description": "A human-readable description of the configuration item’s purpose." + }, + "type": { + "description": "The data type of the configuration value.", + "$ref": "#/components/schemas/ConfigurationValueType" + }, + "value": { + "maxLength": 4096, + "minLength": 0, + "type": "string", + "description": "The initial value for the configuration item, serialized as a string.\nMust conform to the format required by ConfigurationValueType ConfigurationAddItemRequest.Type." + } + }, + "description": "Request DTO for adding a new configuration item." + }, + "ConfigurationItemDto": { + "required": [ + "name", + "description", + "type", + "value", + "updatedAt", + "createdAt" + ], + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The unique name of the configuration item." + }, + "description": { + "type": "string", + "description": "A human-readable description of what this configuration item controls." + }, + "type": { + "description": "The data type of the configuration value.", + "$ref": "#/components/schemas/ConfigurationValueType" + }, + "value": { + "type": "string", + "description": "The current value of the configuration item, serialized as a string." + }, + "updatedAt": { + "type": "string", + "description": "The timestamp when the configuration was last updated.", + "format": "date-time" + }, + "createdAt": { + "type": "string", + "description": "The timestamp when the configuration was originally created.", + "format": "date-time" + } + }, + "description": "Data transfer object representing a configuration item." + }, + "ConfigurationUpdateItemRequest": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 0, + "type": "string", + "description": "The name of the configuration item to update.\nMust consist only of uppercase letters and underscores." + }, + "description": { + "maxLength": 255, + "minLength": 0, + "type": [ + "null", + "string" + ], + "description": "(Optional) New description for the configuration item." + }, + "value": { + "maxLength": 4096, + "minLength": 0, + "type": [ + "null", + "string" + ], + "description": "(Optional) New value for the configuration item.\nMust match the format expected by its existing ConfigurationValueType." + } + }, + "description": "Request DTO for updating a configuration item.\nEither string? ConfigurationUpdateItemRequest.Description or string? ConfigurationUpdateItemRequest.Value (or both) may be provided.\nIf both are null, no update action is performed." + }, + "ConfigurationValueType": { + "enum": [ + "String", + "Bool", + "Int", + "Float", + "Json" + ], + "type": "string" + }, + "Control": { + "required": [ + "id", + "type", + "intensity", + "duration" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "type": { + "$ref": "#/components/schemas/ControlType" + }, + "intensity": { + "maximum": 100, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "duration": { + "maximum": 65535, + "minimum": 300, + "type": "integer", + "format": "int32" + }, + "exclusive": { + "type": "boolean", + "description": "If true, overrides livecontrol" + } + } + }, + "ControlLimitMode": { + "enum": [ + "Clamp", + "Lerp" + ], + "type": "string", + "description": "Determines how a per-token min/max limit is applied to an incoming control value." + }, + "ControlLogSenderLight": { + "required": [ + "id", + "name", + "image", + "customName" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "image": { + "type": "string", + "format": "uri" + }, + "customName": { + "type": [ + "null", + "string" + ] + } + } + }, + "ControlRequest": { + "required": [ + "shocks" + ], + "type": "object", + "properties": { + "shocks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Control" + } + }, + "customName": { + "type": [ + "null", + "string" + ] + } + } + }, + "ControlStatChangesRequest": { + "required": [ + "userIds" + ], + "type": "object", + "properties": { + "since": { + "type": [ + "null", + "string" + ], + "description": "The cursor returned by the previous call, omit for an initial sync of every requested user.", + "format": "date-time" + }, + "userIds": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "description": "The users the caller is interested in, only these are ever reported." + } + } + }, + "ControlStatChangesResponse": { + "required": [ + "cursor", + "users" + ], + "type": "object", + "properties": { + "cursor": { + "type": "string", + "description": "Pass as `since` on the next call.", + "format": "date-time" + }, + "users": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserControlStatTotals" + } + } + } + }, + "ControlStatTotals": { + "required": [ + "type", + "live", + "count", + "durationMs", + "averageIntensity", + "maxIntensity" + ], + "type": "object", + "properties": { + "type": { + "$ref": "#/components/schemas/ControlType" + }, + "live": { + "type": "boolean" + }, + "count": { + "type": "integer", + "description": "Number of controls, for live control the number of continuous bursts.", + "format": "int64" + }, + "durationMs": { + "type": "integer", + "format": "int64" + }, + "averageIntensity": { + "type": "number", + "description": "Average intensity weighted by duration.", + "format": "double" + }, + "maxIntensity": { + "maximum": 255, + "minimum": 0, + "type": "integer", + "format": "int32" + } + }, + "description": "Aggregated activity of one control type, split by whether it was live control." + }, + "ControlStatsResponse": { + "required": [ + "received", + "given" + ], + "type": "object", + "properties": { + "received": { + "description": "Activity on shockers you own.", + "$ref": "#/components/schemas/ReceivedControlStats" + }, + "given": { + "description": "Activity you sent to shockers, your own included.", + "$ref": "#/components/schemas/GivenControlStats" + } + } + }, + "ControlType": { + "enum": [ + "Stop", + "Shock", + "Vibrate", + "Sound" + ], + "type": "string" + }, + "CreateAutomationTokenDto": { + "required": [ + "name", + "types" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + "types": { + "minItems": 1, + "type": "array", + "items": { + "$ref": "#/components/schemas/AutomationTokenType" + } + }, + "autoCleanupUsers": { + "type": "boolean", + "description": "Whether the automated accounts this token creates are deleted once TimeSpan? CreateAutomationTokenDto.AutoCleanupAfter has\npassed since they were created. Off by default; accounts the token didn't create are never deleted." + }, + "autoCleanupAfter": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": [ + "null", + "string" + ] + } + } + }, + "CreateShareRequest": { + "required": [ + "shockers" + ], + "type": "object", + "properties": { + "shockers": { + "maxItems": 128, + "type": "array", + "items": { + "$ref": "#/components/schemas/ShockerPermLimitPairWithId" + } + }, + "user": { + "type": [ + "null", + "string" + ], + "format": "uuid" + } + } + }, + "CreateTokenRequestV2": { + "required": [ + "name", + "permissions", + "shockerControl" + ], + "type": "object", + "properties": { + "validUntil": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "name": { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + "permissions": { + "maxItems": 256, + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionType" + } + }, + "shockerControl": { + "description": "Per-token shocker control configuration. When omitted, the permissive default is used.", + "$ref": "#/components/schemas/ShockerControlSettings" + } + } + }, + "CreatedAutomationTokenDto": { + "required": [ + "id", + "name", + "secret", + "types", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "secret": { + "type": "string" + }, + "types": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AutomationTokenType" + } + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "lastRotatedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "autoCleanupUsers": { + "type": "boolean" + }, + "autoCleanupAfter": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": [ + "null", + "string" + ] + } + } + }, + "DailyControlStats": { + "required": [ + "date", + "stats" + ], + "type": "object", + "properties": { + "date": { + "type": "string", + "description": "Day in the requested time zone.", + "format": "date" + }, + "stats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ControlStatTotals" + } + } + } + }, + "DeviceResponse": { + "required": [ + "id", + "name", + "createdOn" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + } + } + }, + "DeviceSelfResponse": { + "required": [ + "id", + "name", + "shockers" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "shockers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MinimalShocker" + } + } + } + }, + "DeviceWithShockersResponse": { + "required": [ + "shockers", + "id", + "name", + "createdOn" + ], + "type": "object", + "properties": { + "shockers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShockerResponse" + } + }, + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + } + } + }, + "DeviceWithTokenResponse": { + "required": [ + "token", + "id", + "name", + "createdOn" + ], + "type": "object", + "properties": { + "token": { + "type": [ + "null", + "string" + ] + }, + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + } + } + }, + "DurationLimitSettings": { + "required": [ + "min", + "max" + ], + "type": "object", + "properties": { + "min": { + "maximum": 65535, + "minimum": 300, + "type": "integer", + "format": "int32" + }, + "max": { + "maximum": 65535, + "minimum": 300, + "type": "integer", + "format": "int32" + }, + "mode": { + "$ref": "#/components/schemas/ControlLimitMode" + } + } + }, + "EditTokenRequestV2": { + "required": [ + "name", + "permissions", + "shockerControl" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + "permissions": { + "maxItems": 256, + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionType" + } + }, + "shockerControl": { + "description": "Per-token shocker control configuration. When omitted, the permissive default is used.", + "$ref": "#/components/schemas/ShockerControlSettings" + } + } + }, + "EmailOutboxBulkRequest": { + "required": [ + "ids" + ], + "type": "object", + "properties": { + "ids": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + }, + "description": "A set of email outbox message ids to apply a bulk requeue/cancel/delete to." + }, + "EmailOutboxBulkResultDto": { + "required": [ + "requested", + "affected" + ], + "type": "object", + "properties": { + "requested": { + "type": "integer", + "format": "int32" + }, + "affected": { + "type": "integer", + "format": "int32" + } + }, + "description": "Outcome of a bulk email outbox operation: how many ids were requested and how many rows were\nactually affected (rows that were missing or in an ineligible state are silently not counted)." + }, + "EmailOutboxMessageDto": { + "required": [ + "id", + "type", + "recipient", + "recipientName", + "payload", + "coalesceKey", + "status", + "attemptCount", + "nextAttemptAt", + "lastError", + "createdAt", + "sentAt", + "failedAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "type": { + "$ref": "#/components/schemas/EmailType" + }, + "recipient": { + "type": "string" + }, + "recipientName": { + "type": [ + "null", + "string" + ] + }, + "payload": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "coalesceKey": { + "type": [ + "null", + "string" + ] + }, + "status": { + "$ref": "#/components/schemas/EmailStatus" + }, + "attemptCount": { + "type": "integer", + "format": "int32" + }, + "nextAttemptAt": { + "type": "string", + "format": "date-time" + }, + "lastError": { + "type": [ + "null", + "string" + ] + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "sentAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "failedAt": { + "type": [ + "null", + "string" + ], + "format": "date-time" + } + }, + "description": "An EmailOutboxMessage as exposed to admins on the mail-queue page. Mirrors the row\nverbatim - the outbox stores no rendered body and no usable secret, so every field is safe to show." + }, + "EmailOutboxStatsDto": { + "required": [ + "pending", + "sending", + "sent", + "failed", + "skipped", + "total" + ], + "type": "object", + "properties": { + "pending": { + "type": "integer", + "format": "int64" + }, + "sending": { + "type": "integer", + "format": "int64" + }, + "sent": { + "type": "integer", + "format": "int64" + }, + "failed": { + "type": "integer", + "format": "int64" + }, + "skipped": { + "type": "integer", + "format": "int64" + }, + "total": { + "type": "integer", + "format": "int64" + } + }, + "description": "Count of email outbox rows in each delivery state, for the admin mail-queue overview tiles." + }, + "EmailProviderBlacklistDto": { + "required": [ + "id", + "domain", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "domain": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + }, + "EmailStatus": { + "enum": [ + "Pending", + "Sending", + "Sent", + "Failed", + "Skipped" + ], + "type": "string", + "description": "Delivery state of an email outbox message." + }, + "EmailType": { + "enum": [ + "AccountActivation", + "PasswordReset", + "EmailVerification", + "EmailChangeNotice" + ], + "type": "string", + "description": "The kind of email an outbox message represents. The outbox stores\nonly the intent to send one of these, never a rendered body or a usable secret, the\nconsumer maps the type to the matching template and (for token-bearing types) mints a fresh\nsecret at send time." + }, + "GivenControlStats": { + "required": [ + "totals", + "owners" + ], + "type": "object", + "properties": { + "totals": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ControlStatTotals" + } + }, + "owners": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserControlStats" + } + } + } + }, + "HubCreateRequest": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "type": "string" + } + } + }, + "HubEditRequest": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "type": "string" + } + } + }, + "IntensityLimitSettings": { + "required": [ + "min", + "max", + "mode" + ], + "type": "object", + "properties": { + "min": { + "maximum": 100, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "max": { + "maximum": 100, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "mode": { + "$ref": "#/components/schemas/ControlLimitMode" + } + } + }, + "LcgNodeResponseV2": { + "required": [ + "host", + "port", + "path", + "country" + ], + "type": "object", + "properties": { + "host": { + "type": "string" + }, + "port": { + "maximum": 65535, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "path": { + "type": "string" + }, + "country": { + "type": "string" + } + } + }, + "LcgResponseV2": { + "required": [ + "host", + "port", + "pathPrefix", + "country" + ], + "type": "object", + "properties": { + "host": { + "type": "string", + "description": "Public host of the gateway the hub is connected to." + }, + "port": { + "maximum": 65535, + "minimum": 0, + "type": "integer", + "description": "Public port to connect to (default 443).", + "format": "int32" + }, + "pathPrefix": { + "type": "string", + "description": "Base path prefix the gateway is served under, e.g. \"/gateway\" (empty for root). The client\nbuilds the full URL and appends the live-control route (`/1/ws/live/{hubId}`) itself." + }, + "country": { + "type": "string" + } + } + }, + "LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminOnlineDeviceResponse" + } + } + } + }, + "LegacyDataResponseOfArrayOfDeviceResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DeviceResponse" + } + } + } + }, + "LegacyDataResponseOfArrayOfDeviceWithShockersResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DeviceWithShockersResponse" + } + } + } + }, + "LegacyDataResponseOfArrayOfLogEntry": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LogEntry" + } + } + } + }, + "LegacyDataResponseOfArrayOfOwnPublicShareResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnPublicShareResponse" + } + } + } + }, + "LegacyDataResponseOfArrayOfOwnerShockerResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OwnerShockerResponse" + } + } + } + }, + "LegacyDataResponseOfArrayOfShareCodeInfo": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareCodeInfo" + } + } + } + }, + "LegacyDataResponseOfArrayOfShareInfo": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShareInfo" + } + } + } + }, + "LegacyDataResponseOfArrayOfShockerResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShockerResponse" + } + } + } + }, + "LegacyDataResponseOfBackendInfoResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "$ref": "#/components/schemas/BackendInfoResponse" + } + } + }, + "LegacyDataResponseOfDeviceSelfResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "$ref": "#/components/schemas/DeviceSelfResponse" + } + } + }, + "LegacyDataResponseOfDeviceWithTokenResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "$ref": "#/components/schemas/DeviceWithTokenResponse" + } + } + }, + "LegacyDataResponseOfGuid": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "string", + "format": "uuid" + } + } + }, + "LegacyDataResponseOfIReadOnlyCollectionOfOtaItem": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/OtaItem" + } + } + } + }, + "LegacyDataResponseOfLegacyUserSelfResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "$ref": "#/components/schemas/LegacyUserSelfResponse" + } + } + }, + "LegacyDataResponseOfPauseReason": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "examples": [ + 6 + ], + "title": "PauseReason", + "type": "integer", + "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." + } + } + }, + "LegacyDataResponseOfPublicShareResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "$ref": "#/components/schemas/PublicShareResponse" + } + } + }, + "LegacyDataResponseOfShockerWithDevice": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "$ref": "#/components/schemas/ShockerWithDevice" + } + } + }, + "LegacyDataResponseOfStatsResponse": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "$ref": "#/components/schemas/StatsResponse" + } + } + }, + "LegacyDataResponseOfboolean": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "boolean" + } + } + }, + "LegacyDataResponseOfstring": { + "required": [ + "data", + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string", + "default": "" + }, + "data": { + "type": "string" + } + } + }, + "LegacyEmptyResponse": { + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "data": {} + } + }, + "LegacyUserSelfResponse": { + "required": [ + "id", + "name", + "email", + "image", + "roles", + "rank", + "hasPassword" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "email": { + "type": "string" + }, + "image": { + "type": "string", + "format": "uri" + }, + "roles": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoleType" + } + }, + "rank": { + "type": "string" + }, + "hasPassword": { + "type": "boolean" + } + }, + "description": "Response shape of the deprecated GET /1/users/self, kept for API token clients that still read `rank`." + }, + "LogEntry": { + "required": [ + "id", + "createdOn", + "type", + "controlledBy", + "intensity", + "duration", + "liveControl" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "type": { + "$ref": "#/components/schemas/ControlType" + }, + "controlledBy": { + "$ref": "#/components/schemas/ControlLogSenderLight" + }, + "intensity": { + "maximum": 255, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "duration": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "liveControl": { + "type": "boolean" + } + } + }, + "LogEntryWithHub": { + "required": [ + "id", + "hubId", + "hubName", + "shockerId", + "shockerName", + "createdOn", + "type", + "controlledBy", + "intensity", + "duration", + "liveControl" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "hubId": { + "type": "string", + "format": "uuid" + }, + "hubName": { + "type": "string" + }, + "shockerId": { + "type": "string", + "format": "uuid" + }, + "shockerName": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "type": { + "$ref": "#/components/schemas/ControlType" + }, + "controlledBy": { + "$ref": "#/components/schemas/ControlLogSenderLight" + }, + "intensity": { + "maximum": 255, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "duration": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "liveControl": { + "type": "boolean" + } + } + }, + "LoginSessionResponse": { + "required": [ + "id", + "ip", + "userAgent", + "created", + "expires", + "lastUsed" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "ip": { + "examples": [ + "127.0.0.1" + ], + "title": "IpAddress", + "type": "string", + "description": "An IPv4 or IPv6 address in its textual form." + }, + "userAgent": { + "type": "string" + }, + "created": { + "type": "string", + "format": "date-time" + }, + "expires": { + "type": "string", + "format": "date-time" + }, + "lastUsed": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "asnOrg": { + "type": [ + "null", + "string" + ] + }, + "isVpn": { + "type": [ + "null", + "boolean" + ] + }, + "countryCode": { + "type": [ + "null", + "string" + ] + }, + "city": { + "type": [ + "null", + "string" + ] + } + } + }, + "LoginV2": { + "required": [ + "password", + "usernameOrEmail", + "turnstileResponse" + ], + "type": "object", + "properties": { + "password": { + "minLength": 1, + "type": "string" + }, + "usernameOrEmail": { + "minLength": 1, + "type": "string" + }, + "turnstileResponse": { + "maxLength": 2048, + "minLength": 0, + "type": "string" + } + } + }, + "LoginV2OkResponse": { + "required": [ + "accountId", + "accountName", + "accountEmail", + "isVerified", + "profileImage", + "accountRoles" + ], + "type": "object", + "properties": { + "accountId": { + "type": "string", + "format": "uuid" + }, + "accountName": { + "type": "string" + }, + "accountEmail": { + "type": "string" + }, + "isVerified": { + "type": "boolean" + }, + "profileImage": { + "type": "string", + "format": "uri" + }, + "accountRoles": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoleType" + } + } + } + }, + "MatchTypeEnum": { + "enum": [ + "Exact", + "Contains" + ], + "type": "string" + }, + "MinimalShocker": { + "required": [ + "id", + "rfId", + "model" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "rfId": { + "maximum": 65535, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "model": { + "$ref": "#/components/schemas/ShockerModelType" + } + } + }, + "NewShocker": { + "required": [ + "name", + "rfId", + "device", + "model" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + "rfId": { + "maximum": 65535, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "device": { + "type": "string", + "format": "uuid" + }, + "model": { + "$ref": "#/components/schemas/ShockerModelType" + } + } + }, + "OAuthConnectionResponse": { + "required": [ + "providerKey", + "externalId", + "displayName", + "linkedAt" + ], + "type": "object", + "properties": { + "providerKey": { + "type": "string" + }, + "externalId": { + "type": "string" + }, + "displayName": { + "type": [ + "null", + "string" + ] + }, + "linkedAt": { + "type": "string", + "format": "date-time" + } + } + }, + "OpenShockProblem": { + "required": [ + "type", + "title" + ], + "type": "object", + "properties": { + "type": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "status": { + "type": [ + "null", + "integer" + ], + "format": "int32" + }, + "detail": { + "type": [ + "null", + "string" + ] + }, + "instance": { + "type": [ + "null", + "string" + ] + }, + "message": { + "type": "string", + "deprecated": true + }, + "traceId": { + "type": [ + "null", + "string" + ], + "deprecated": true + }, + "requestId": { + "type": [ + "null", + "string" + ] + } + } + }, + "OtaItem": { + "required": [ + "id", + "startedAt", + "status", + "version", + "message" + ], + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "startedAt": { + "type": "string", + "format": "date-time" + }, + "status": { + "$ref": "#/components/schemas/OtaUpdateStatus" + }, + "version": { + "examples": [ + "1.0.0-dev+a16f2" + ], + "title": "SemVer", + "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$", + "type": "string" + }, + "message": { + "type": [ + "null", + "string" + ] + } + } + }, + "OtaUpdateStatus": { + "enum": [ + "Started", + "Running", + "Finished", + "Error", + "Timeout" + ], + "type": "string" + }, + "OwnPublicShareResponse": { + "required": [ + "id", + "name", + "createdOn" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "expiresOn": { + "type": [ + "null", + "string" + ], + "format": "date-time" + } + } + }, + "OwnerShockerResponse": { + "required": [ + "id", + "name", + "image", + "devices" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "image": { + "type": "string", + "format": "uri" + }, + "devices": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SharedDevice" + } + } + } + }, + "PagedResultOfAuditLogEntryResponse": { + "required": [ + "items", + "page", + "pageSize", + "totalCount" + ], + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AuditLogEntryResponse" + }, + "description": "Items on the current page." + }, + "page": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer", + "description": "1-based current page index." + }, + "pageSize": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer", + "description": "Page size used to produce this result." + }, + "totalCount": { + "type": "integer", + "description": "Total number of items across all pages matching the query.", + "format": "int32" + }, + "totalPages": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer", + "description": "Total number of pages. Always at least 1, even when `TotalCount` is zero." + } + }, + "description": "Page of results for a paginated list endpoint." + }, + "PagedResultOfLogEntryWithHub": { + "required": [ + "items", + "page", + "pageSize", + "totalCount" + ], + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LogEntryWithHub" + }, + "description": "Items on the current page." + }, + "page": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer", + "description": "1-based current page index." + }, + "pageSize": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer", + "description": "Page size used to produce this result." + }, + "totalCount": { + "type": "integer", + "description": "Total number of items across all pages matching the query.", + "format": "int32" + }, + "totalPages": { + "maximum": 4294967295, + "minimum": 0, + "type": "integer", + "description": "Total number of pages. Always at least 1, even when `TotalCount` is zero." + } + }, + "description": "Page of results for a paginated list endpoint." + }, + "PaginatedOfAdminUsersView": { + "required": [ + "offset", + "limit", + "total", + "data" + ], + "type": "object", + "properties": { + "offset": { + "type": "integer", + "format": "int32" + }, + "limit": { + "type": "integer", + "format": "int32" + }, + "total": { + "type": "integer", + "format": "int64" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUsersView" + } + } + } + }, + "PaginatedOfEmailOutboxMessageDto": { + "required": [ + "offset", + "limit", + "total", + "data" + ], + "type": "object", + "properties": { + "offset": { + "type": "integer", + "format": "int32" + }, + "limit": { + "type": "integer", + "format": "int32" + }, + "total": { + "type": "integer", + "format": "int64" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EmailOutboxMessageDto" + } + } + } + }, + "PasswordHashingAlgorithm": { + "enum": [ + "BCrypt", + "PBKDF2", + "Unknown" + ], + "type": "string" + }, + "PasswordResetProcessData": { + "required": [ + "password" + ], + "type": "object", + "properties": { + "password": { + "type": "string" + } + } + }, + "PasswordResetRequestV2": { + "required": [ + "email", + "turnstileResponse" + ], + "type": "object", + "properties": { + "email": { + "examples": [ + "user@example.com" + ], + "type": "string" + }, + "turnstileResponse": { + "maxLength": 2048, + "minLength": 0, + "type": "string" + } + } + }, + "PatchAutomationTokenDto": { + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "type": [ + "null", + "string" + ] + }, + "types": { + "minItems": 1, + "type": [ + "null", + "array" + ], + "items": { + "$ref": "#/components/schemas/AutomationTokenType" + } + }, + "autoCleanupUsers": { + "type": [ + "null", + "boolean" + ] + }, + "autoCleanupAfter": { + "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": [ + "null", + "string" + ] + } + } + }, + "PauseRequest": { + "required": [ + "pause" + ], + "type": "object", + "properties": { + "pause": { + "type": "boolean" + } + } + }, + "PauseUserShareShockersRequest": { + "required": [ + "shockers", + "pause" + ], + "type": "object", + "properties": { + "shockers": { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + }, + "pause": { + "type": "boolean" + } + } + }, + "PauseUserShareShockersResponse": { + "required": [ + "affectedRecords", + "pauseStates" + ], + "type": "object", + "properties": { + "affectedRecords": { + "type": "integer", + "format": "int32" + }, + "pauseStates": { + "type": "object", + "additionalProperties": { + "examples": [ + 6 + ], + "title": "PauseReason", + "type": "integer", + "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." + } + } + } + }, + "PermissionType": { + "enum": [ + "shockers.use", + "shockers.edit", + "shockers.pause", + "devices.edit", + "devices.auth", + "usershares.edit", + "usershares.pause", + "publicshares.pause", + "publicshares.edit" + ], + "type": "string" + }, + "ProblemDetails": { + "type": "object", + "properties": { + "type": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "status": { + "type": [ + "null", + "integer" + ], + "format": "int32" + }, + "detail": { + "type": [ + "null", + "string" + ] + }, + "instance": { + "type": [ + "null", + "string" + ] + } + } + }, + "PublicShareCreate": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + "expiresOn": { + "type": [ + "null", + "string" + ], + "format": "date-time" + } + } + }, + "PublicShareDevice": { + "required": [ + "id", + "name", + "shockers" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "shockers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PublicShareShocker" + } + } + } + }, + "PublicShareEditShocker": { + "required": [ + "permissions", + "limits" + ], + "type": "object", + "properties": { + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + }, + "cooldown": { + "maximum": 65535, + "minimum": 300, + "type": [ + "null", + "integer" + ], + "format": "int32" + } + } + }, + "PublicShareResponse": { + "required": [ + "id", + "name", + "createdOn", + "author" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "expiresOn": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "author": { + "$ref": "#/components/schemas/BasicUserInfo" + }, + "devices": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PublicShareDevice" + } + } + } + }, + "PublicShareShocker": { + "required": [ + "id", + "name", + "permissions", + "limits", + "paused" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + }, + "paused": { + "examples": [ + 6 + ], + "title": "PauseReason", + "type": "integer", + "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." + } + } + }, + "ReceivedControlStats": { + "required": [ + "totals", + "shockers", + "controllers", + "days" + ], + "type": "object", + "properties": { + "totals": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ControlStatTotals" + } + }, + "shockers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShockerControlStats" + } + }, + "controllers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserControlStats" + } + }, + "days": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DailyControlStats" + } + } + } + }, + "RemoveUserSharesResponse": { + "required": [ + "affectedRecords" + ], + "type": "object", + "properties": { + "affectedRecords": { + "type": "integer", + "format": "int32" + } + } + }, + "ReportTokensRequest": { + "required": [ + "turnstileResponse", + "secrets" + ], + "type": "object", + "properties": { + "turnstileResponse": { + "maxLength": 2048, + "minLength": 0, + "type": "string" + }, + "secrets": { + "maxItems": 512, + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "RoleType": { + "enum": [ + "Support", + "Staff", + "Admin", + "System" + ], + "type": "string" + }, + "SendTestEmailDto": { + "required": [ + "type", + "recipient" + ], + "type": "object", + "properties": { + "type": { + "description": "Which template to preview.", + "$ref": "#/components/schemas/EmailType" + }, + "recipient": { + "examples": [ + "user@example.com" + ], + "type": "string", + "description": "Destination address for the test email." + }, + "recipientName": { + "type": [ + "null", + "string" + ], + "description": "Optional display name for the recipient." + } + }, + "description": "Request to enqueue a preview/test email of a chosen type to a chosen address. The message is\ndelivered by the Cron pipeline with placeholder data and a dummy link (no token, no request row)." + }, + "SetTokenPausedRequest": { + "required": [ + "paused" + ], + "type": "object", + "properties": { + "paused": { + "type": "boolean", + "description": "When true, the token is paused and may not send shocker control messages." + } + } + }, + "SetUserEmailRequestBody": { + "required": [ + "email" + ], + "type": "object", + "properties": { + "email": { + "examples": [ + "user@example.com" + ], + "type": "string" + } + } + }, + "SetUserNameRequestBody": { + "required": [ + "name" + ], + "type": "object", + "properties": { + "name": { + "examples": [ + "String" + ], + "type": "string" + } + } + }, + "SetUserPasswordRequestBody": { + "required": [ + "password" + ], + "type": "object", + "properties": { + "password": { + "examples": [ + "Password123!" + ], + "type": "string" + } + } + }, + "ShareCodeInfo": { + "required": [ + "id", + "createdOn" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "createdOn": { + "type": "string", + "format": "date-time" + } + } + }, + "ShareInfo": { + "required": [ + "sharedWith", + "createdOn", + "permissions", + "limits", + "paused" + ], + "type": "object", + "properties": { + "sharedWith": { + "$ref": "#/components/schemas/BasicUserInfo" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + }, + "paused": { + "type": "boolean" + } + } + }, + "ShareInviteBaseDetails": { + "required": [ + "shockers", + "id", + "createdAt", + "owner", + "sharedWith" + ], + "type": "object", + "properties": { + "shockers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ShockerPermLimitPairWithIdAndName" + } + }, + "id": { + "type": "string", + "format": "uuid" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "owner": { + "$ref": "#/components/schemas/BasicUserInfo" + }, + "sharedWith": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/BasicUserInfo" + } + ] + } + } + }, + "SharedDevice": { + "required": [ + "id", + "name", + "shockers" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "shockers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SharedShocker" + } + } + } + }, + "SharedShocker": { + "required": [ + "id", + "name", + "isPaused", + "permissions", + "limits" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "isPaused": { + "type": "boolean" + }, + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + } + } + }, + "ShockerControlSettings": { + "required": [ + "paused", + "intensity", + "duration" + ], + "type": "object", + "properties": { + "paused": { + "type": "boolean", + "description": "When true, this token is paused and may not send shocker control messages." + }, + "intensity": { + "$ref": "#/components/schemas/IntensityLimitSettings" + }, + "duration": { + "$ref": "#/components/schemas/DurationLimitSettings" + } + }, + "description": "Per-token shocker control configuration: a toggle plus min/max limits for intensity and duration." + }, + "ShockerControlStats": { + "required": [ + "shockerId", + "shockerName", + "stats" + ], + "type": "object", + "properties": { + "shockerId": { + "type": [ + "null", + "string" + ], + "description": "Null for shockers that have since been deleted, these are combined into one entry.", + "format": "uuid" + }, + "shockerName": { + "type": [ + "null", + "string" + ] + }, + "stats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ControlStatTotals" + } + } + } + }, + "ShockerLimits": { + "required": [ + "intensity", + "duration" + ], + "type": "object", + "properties": { + "intensity": { + "maximum": 100, + "minimum": 0, + "type": [ + "null", + "integer" + ], + "format": "int32" + }, + "duration": { + "maximum": 65535, + "minimum": 300, + "type": [ + "null", + "integer" + ], + "format": "int32" + } + } + }, + "ShockerModelType": { + "enum": [ + "CaiXianlin", + "PetTrainer", + "Petrainer998DR", + "WellturnT330" + ], + "type": "string" + }, + "ShockerPermLimitPair": { + "required": [ + "permissions", + "limits" + ], + "type": "object", + "properties": { + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + } + } + }, + "ShockerPermLimitPairWithId": { + "required": [ + "permissions", + "limits" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + } + } + }, + "ShockerPermLimitPairWithIdAndName": { + "required": [ + "name", + "permissions", + "limits" + ], + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "id": { + "type": "string", + "format": "uuid" + }, + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + } + } + }, + "ShockerPermissions": { + "required": [ + "vibrate", + "sound", + "shock" + ], + "type": "object", + "properties": { + "vibrate": { + "type": "boolean" + }, + "sound": { + "type": "boolean" + }, + "shock": { + "type": "boolean" + }, + "live": { + "type": "boolean" + } + } + }, + "ShockerResponse": { + "required": [ + "name", + "isPaused", + "createdOn", + "id", + "rfId", + "model" + ], + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "isPaused": { + "type": "boolean" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "id": { + "type": "string", + "format": "uuid" + }, + "rfId": { + "maximum": 65535, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "model": { + "$ref": "#/components/schemas/ShockerModelType" + } + } + }, + "ShockerWithDevice": { + "required": [ + "device", + "name", + "isPaused", + "createdOn", + "id", + "rfId", + "model" + ], + "type": "object", + "properties": { + "device": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "isPaused": { + "type": "boolean" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "id": { + "type": "string", + "format": "uuid" + }, + "rfId": { + "maximum": 65535, + "minimum": 0, + "type": "integer", + "format": "int32" + }, + "model": { + "$ref": "#/components/schemas/ShockerModelType" + } + } + }, + "SignUpV2": { + "required": [ + "username", + "password", + "email", + "turnstileResponse" + ], + "type": "object", + "properties": { + "username": { + "examples": [ + "String" + ], + "type": "string" + }, + "password": { + "examples": [ + "Password123!" + ], + "type": "string" + }, + "email": { + "examples": [ + "user@example.com" + ], + "type": "string" + }, + "turnstileResponse": { + "maxLength": 2048, + "minLength": 0, + "type": "string" + } + } + }, + "SortDirection": { + "enum": [ + "Asc", + "Desc" + ], + "type": "string", + "description": "Sort direction for list endpoints." + }, + "StatsResponse": { + "required": [ + "devicesOnline" + ], + "type": "object", + "properties": { + "devicesOnline": { + "type": "integer", + "format": "int64" + } + } + }, + "TokenCreatedResponseV2": { + "required": [ + "id", + "name", + "token", + "createdAt", + "validUntil", + "lastUsed", + "permissions", + "shockerControl" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "token": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "validUntil": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "lastUsed": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionType" + } + }, + "shockerControl": { + "$ref": "#/components/schemas/ShockerControlSettings" + } + } + }, + "TokenPausedResponse": { + "required": [ + "paused" + ], + "type": "object", + "properties": { + "paused": { + "type": "boolean", + "description": "The now-set paused state of the token." + } + } + }, + "TokenResponseV2": { + "required": [ + "id", + "name", + "createdOn", + "validUntil", + "lastUsed", + "permissions", + "shockerControl" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "validUntil": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "lastUsed": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionType" + } + }, + "shockerControl": { + "$ref": "#/components/schemas/ShockerControlSettings" + } + } + }, + "UserControlStatTotals": { + "required": [ + "userId", + "received", + "given" + ], + "type": "object", + "properties": { + "userId": { + "type": "string", + "format": "uuid" + }, + "received": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ControlStatTotals" + }, + "description": "Activity on shockers the user owns." + }, + "given": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ControlStatTotals" + }, + "description": "Activity the user sent to shockers, their own included." + } + }, + "description": "Lifetime totals of one user, the same views as ControlStatsResponse without breakdowns." + }, + "UserControlStats": { + "required": [ + "userId", + "user", + "stats" + ], + "type": "object", + "properties": { + "userId": { + "type": [ + "null", + "string" + ], + "description": "Null for guests (public shares).", + "format": "uuid" + }, + "user": { + "oneOf": [ + { + "type": "null" + }, + { + "description": "Null for guests and deleted users.", + "$ref": "#/components/schemas/BasicUserInfo" + } + ] + }, + "stats": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ControlStatTotals" + } + } + } + }, + "UserNameBlacklistDto": { + "required": [ + "id", + "value", + "matchType", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "value": { + "type": "string" + }, + "matchType": { + "$ref": "#/components/schemas/MatchTypeEnum" + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + }, + "UserPatchDto": { + "type": "object", + "properties": { + "name": { + "type": [ + "null", + "string" + ] + }, + "email": { + "type": [ + "null", + "string" + ] + } + } + }, + "UserSelfResponse": { + "required": [ + "id", + "name", + "email", + "image", + "roles", + "hasPassword" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "email": { + "type": "string" + }, + "image": { + "type": "string", + "format": "uri" + }, + "roles": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RoleType" + } + }, + "hasPassword": { + "type": "boolean" + } + } + }, + "UserShareInfo": { + "required": [ + "id", + "name", + "createdOn", + "permissions", + "limits", + "paused" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdOn": { + "type": "string", + "format": "date-time" + }, + "permissions": { + "$ref": "#/components/schemas/ShockerPermissions" + }, + "limits": { + "$ref": "#/components/schemas/ShockerLimits" + }, + "paused": { + "examples": [ + 6 + ], + "title": "PauseReason", + "type": "integer", + "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." + } + } + }, + "UsernameAvailability": { + "enum": [ + "Available", + "Taken", + "Invalid" + ], + "type": "string" + }, + "UsernameCheckResponse": { + "required": [ + "availability" + ], + "type": "object", + "properties": { + "availability": { + "$ref": "#/components/schemas/UsernameAvailability" + }, + "error": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UsernameError" + } + ] + } + } + }, + "UsernameError": { + "required": [ + "message", + "type" + ], + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "type": { + "$ref": "#/components/schemas/UsernameErrorType" + } + } + }, + "UsernameErrorType": { + "enum": [ + "TooShort", + "TooLong", + "StartOrEndWithWhitespace", + "ResembleEmail", + "ObnoxiousCharacters", + "Blacklisted" + ], + "type": "string" + }, + "V2UserShares": { + "required": [ + "outgoing", + "incoming" + ], + "type": "object", + "properties": { + "outgoing": { + "type": "array", + "items": { + "$ref": "#/components/schemas/V2UserSharesListItem" + } + }, + "incoming": { + "type": "array", + "items": { + "$ref": "#/components/schemas/V2UserSharesListItem" + } + } + } + }, + "V2UserSharesListItem": { + "required": [ + "id", + "name", + "image", + "shares" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "image": { + "type": "string", + "format": "uri" + }, + "shares": { + "type": "array", + "items": { + "$ref": "#/components/schemas/UserShareInfo" + } + } + } + }, + "WebhookDto": { + "required": [ + "id", + "name", + "url", + "createdAt" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + } + }, + "securitySchemes": { + "UserSessionCookie": { + "type": "apiKey", + "description": "Enter user session cookie", + "name": "openShockSession", + "in": "cookie" + }, + "ApiToken": { + "type": "apiKey", + "description": "Enter API Token", + "name": "OpenShockToken", + "in": "header" + }, + "HubToken": { + "type": "apiKey", + "description": "Enter hub token", + "name": "DeviceToken", + "in": "header" + } + } + }, + "tags": [ + { + "name": "API Tokens", + "description": "API token management" + }, + { + "name": "Account", + "description": "User account management" + }, + { + "name": "Admin", + "description": "Instance administration, for admins only" + }, + { + "name": "Hub Endpoints", + "description": "For devices (ESP's)" + }, + { + "name": "Hub Management", + "description": "Device management" + }, + { + "name": "Integrations", + "description": "Endpoints for first party services (e.g. the Discord bot). Not tied to a user session, every action checks\nfor an automation token that grants the capability it needs." + }, + { + "name": "Meta", + "description": "Version stuff" + }, + { + "name": "Public Shocker Shares", + "description": "Public shares management" + }, + { + "name": "Sessions", + "description": "Session management" + }, + { + "name": "Shocker Shares", + "description": "Shocker share management" + }, + { + "name": "Shockers", + "description": "Shocker management" + }, + { + "name": "User Shocker Shares", + "description": "Shocker share management" + }, + { + "name": "Users", + "description": "User information" + } + ] +} diff --git a/openshock/__init__.py b/openshock/__init__.py index d8a5922..0084d73 100644 --- a/openshock/__init__.py +++ b/openshock/__init__.py @@ -1,11 +1,11 @@ -"""Official OpenShock Python SDK. See https://github.com/OpenShock/SDK.Python""" +""" +Official OpenShock Python SDK. See https://github.com/OpenShock/SDK.Python + +- :mod:`openshock.rest` — the REST client, generated from the backend's OpenAPI document +- :mod:`openshock.realtime` — SignalR user hub and live control (needs the ``realtime`` extra) +""" from ._version import __version__ as __version__ -from .auth import ApiTokenAuth as ApiTokenAuth -from .auth import Auth as Auth -from .auth import HubTokenAuth as HubTokenAuth -from .client import AsyncOpenShockClient as AsyncOpenShockClient -from .client import AsyncOpenShockHubClient as AsyncOpenShockHubClient from .client import OpenShockClient as OpenShockClient from .client import OpenShockHubClient as OpenShockHubClient from .exceptions import ApiTokenPaused as ApiTokenPaused @@ -18,57 +18,10 @@ from .exceptions import OpenShockError as OpenShockError from .exceptions import OpenShockNotFound as OpenShockNotFound from .exceptions import OpenShockRateLimited as OpenShockRateLimited -from .exceptions import ProblemDetails as ProblemDetails +from .exceptions import Problem as Problem from .exceptions import ShockerControlError as ShockerControlError from .exceptions import ShockerNoPermission as ShockerNoPermission from .exceptions import ShockerNotFoundOrNoAccess as ShockerNotFoundOrNoAccess from .exceptions import ShockerPaused as ShockerPaused from .exceptions import TokenPermissionMissing as TokenPermissionMissing -from .models import BackendInfo as BackendInfo -from .models import BasicUserInfo as BasicUserInfo -from .models import BulkPauseResult as BulkPauseResult -from .models import Control as Control -from .models import ControlLogSender as ControlLogSender -from .models import ControlType as ControlType -from .models import CreatedToken as CreatedToken -from .models import Device as Device -from .models import DeviceSelf as DeviceSelf -from .models import DeviceWithShockers as DeviceWithShockers -from .models import DeviceWithToken as DeviceWithToken -from .models import HubGateway as HubGateway -from .models import LcgInfo as LcgInfo -from .models import LcgNode as LcgNode -from .models import LcgNodeV2 as LcgNodeV2 -from .models import MinimalShocker as MinimalShocker -from .models import OtaUpdate as OtaUpdate -from .models import OtaUpdateStatus as OtaUpdateStatus -from .models import OwnPublicShare as OwnPublicShare -from .models import PauseReason as PauseReason -from .models import PermissionType as PermissionType -from .models import PublicShare as PublicShare -from .models import PublicShareDevice as PublicShareDevice -from .models import PublicShareShocker as PublicShareShocker -from .models import RoleType as RoleType -from .models import Session as Session -from .models import ShareCode as ShareCode -from .models import SharedDevice as SharedDevice -from .models import SharedShocker as SharedShocker -from .models import ShareInfo as ShareInfo -from .models import ShareInvite as ShareInvite -from .models import ShareInviteShocker as ShareInviteShocker -from .models import Shocker as Shocker -from .models import ShockerLimits as ShockerLimits -from .models import ShockerLog as ShockerLog -from .models import ShockerLogWithHub as ShockerLogWithHub -from .models import ShockerModelType as ShockerModelType -from .models import ShockerOwner as ShockerOwner -from .models import ShockerPermissions as ShockerPermissions -from .models import Stats as Stats -from .models import Token as Token -from .models import User as User -from .models import UserShare as UserShare -from .models import UserShareInfo as UserShareInfo -from .models import UserShares as UserShares -from .models import WireEnum as WireEnum -from .models import parse_dt as parse_dt -from .models import parse_uuid as parse_uuid +from .exceptions import unwrap as unwrap diff --git a/openshock/_async/__init__.py b/openshock/_async/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/openshock/_async/client.py b/openshock/_async/client.py deleted file mode 100644 index 3f5d5b5..0000000 --- a/openshock/_async/client.py +++ /dev/null @@ -1,191 +0,0 @@ -from __future__ import annotations - -from collections.abc import Callable, Mapping -from types import TracebackType -from typing import Any, TypeVar - -import httpx - -from .._core import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, handle_response, http_user_agent -from ..auth import ApiTokenAuth, Auth, HubTokenAuth -from .resources.account import AsyncAccountResource -from .resources.devices import AsyncDevicesResource -from .resources.hub import AsyncHubResource -from .resources.meta import AsyncMetaResource -from .resources.sessions import AsyncSessionsResource -from .resources.shares import AsyncSharesResource -from .resources.shockers import AsyncShockersResource -from .resources.user_shares import AsyncUserSharesResource - -T = TypeVar("T") -_SelfT = TypeVar("_SelfT", bound="_AsyncBaseClient") - - -class _AsyncBaseClient: - """ - Internal base client that handles HTTP, auth and error mapping. - Concrete clients subclass this and attach resources. - """ - - def __init__( - self, - *, - auth: Auth, - base_url: str = DEFAULT_BASE_URL, - timeout: float = DEFAULT_TIMEOUT, - app_name: str | None = None, - app_version: str | None = None, - headers: Mapping[str, str] | None = None, - transport: httpx.AsyncBaseTransport | None = None, - ) -> None: - self._auth = auth - self._base_url = base_url.rstrip("/") - self._app_name = app_name - self._app_version = app_version - self._client = httpx.AsyncClient( - base_url=self._base_url, - timeout=timeout, - transport=transport, - headers={**(headers or {}), "User-Agent": http_user_agent(app_name, app_version)}, - ) - - # --- introspection ----------------------------------------------------- - - @property - def auth(self) -> Auth: - return self._auth - - @property - def base_url(self) -> str: - return self._base_url - - # --- lifecycle --------------------------------------------------------- - - async def aclose(self) -> None: - await self._client.aclose() - - async def __aenter__(self: _SelfT) -> _SelfT: - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - await self.aclose() - - # --- internal helpers -------------------------------------------------- - - async def _request( - self, - method: str, - path: str, - *, - params: dict[str, Any] | None = None, - json: Any = None, - transform: Callable[[Any], T] | None = None, - ) -> T | Any: - """ - Perform an HTTP request and return the parsed payload for 2xx responses - (JSON-decoded when possible, otherwise text, ``None`` for an empty body). - - On non-2xx an :class:`~openshock.exceptions.OpenShockApiError` subclass is raised; - see :func:`openshock.exceptions.error_from_response` for the mapping. - """ - resp = await self._client.request( - method, - path, - params=params, - json=json, - headers=dict(self._auth.headers()), - ) - return handle_response(resp, transform) - - -class AsyncOpenShockClient(_AsyncBaseClient): - """ - High-level client for the *user* OpenShock REST API (ApiToken-based). - - ``app_name`` / ``app_version`` identify your program in the User-Agent header. - """ - - def __init__( - self, - *, - auth: ApiTokenAuth | None = None, - api_token: str | None = None, - base_url: str = DEFAULT_BASE_URL, - timeout: float = DEFAULT_TIMEOUT, - app_name: str | None = None, - app_version: str | None = None, - headers: Mapping[str, str] | None = None, - transport: httpx.AsyncBaseTransport | None = None, - ) -> None: - if auth is not None and api_token is not None: - raise ValueError("Provide either `auth` or `api_token`, not both.") - - if auth is None: - if api_token is None: - raise ValueError("You must provide either `auth` or `api_token`.") - auth = ApiTokenAuth(api_token) - - super().__init__( - auth=auth, - base_url=base_url, - timeout=timeout, - app_name=app_name, - app_version=app_version, - headers=headers, - transport=transport, - ) - - self.meta = AsyncMetaResource(self) - self.account = AsyncAccountResource(self) - self.devices = AsyncDevicesResource(self) - self.shockers = AsyncShockersResource(self) - self.shares = AsyncSharesResource(self) - self.sessions = AsyncSessionsResource(self) - self.user_shares = AsyncUserSharesResource(self) - - -class AsyncOpenShockHubClient(_AsyncBaseClient): - """ - High-level client for the *hub/device* OpenShock REST API (DeviceToken-based). - - This is what a hub (the ESP32 device) itself talks to. To receive realtime user - events use :class:`openshock.realtime.UserHubClient` instead. - """ - - def __init__( - self, - *, - auth: HubTokenAuth | None = None, - hub_token: str | None = None, - base_url: str = DEFAULT_BASE_URL, - timeout: float = DEFAULT_TIMEOUT, - app_name: str | None = None, - app_version: str | None = None, - headers: Mapping[str, str] | None = None, - transport: httpx.AsyncBaseTransport | None = None, - ) -> None: - if auth is not None and hub_token is not None: - raise ValueError("Provide either `auth` or `hub_token`, not both.") - - if auth is None: - if hub_token is None: - raise ValueError("You must provide either `auth` or `hub_token`.") - auth = HubTokenAuth(hub_token) - - super().__init__( - auth=auth, - base_url=base_url, - timeout=timeout, - app_name=app_name, - app_version=app_version, - headers=headers, - transport=transport, - ) - - self.hub = AsyncHubResource(self) - self.meta = AsyncMetaResource(self) diff --git a/openshock/_async/resources/__init__.py b/openshock/_async/resources/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/openshock/_async/resources/account.py b/openshock/_async/resources/account.py deleted file mode 100644 index 2665d48..0000000 --- a/openshock/_async/resources/account.py +++ /dev/null @@ -1,77 +0,0 @@ -from __future__ import annotations - -from collections.abc import Sequence -from datetime import datetime -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import CreatedToken, PermissionType, Token, User - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -def _permissions(permissions: Sequence[PermissionType | str]) -> list[str]: - return [PermissionType(p).value for p in permissions] - - -class AsyncAccountResource: - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - async def user_self(self) -> User: - """GET /1/users/self — Get the authenticated user's info.""" - resp = await self._client._request("GET", "/1/users/self") - return User.from_dict(unwrap(resp)) - - async def token_self(self) -> Token: - """GET /1/tokens/self — Get info about the API token being used.""" - resp = await self._client._request("GET", "/1/tokens/self") - return Token.from_dict(unwrap(resp)) - - async def list_tokens(self) -> list[Token]: - """GET /1/tokens — List all API tokens for the authenticated user.""" - resp = await self._client._request("GET", "/1/tokens") - return [Token.from_dict(t) for t in unwrap_list(resp)] - - async def create_token( - self, - name: str, - permissions: Sequence[PermissionType | str], - valid_until: datetime | str | None = None, - ) -> CreatedToken: - """ - POST /1/tokens — Create a new API token. - - The returned object carries the token secret; it cannot be retrieved again later. - """ - body: dict[str, Any] = {"name": name, "permissions": _permissions(permissions)} - if valid_until is not None: - body["validUntil"] = valid_until.isoformat() if isinstance(valid_until, datetime) else valid_until - resp = await self._client._request("POST", "/1/tokens", json=body) - return CreatedToken.from_dict(unwrap(resp)) - - async def get_token(self, token_id: str | UUID) -> Token: - """GET /1/tokens/{tokenId} — Get a token by ID.""" - resp = await self._client._request("GET", f"/1/tokens/{token_id}") - return Token.from_dict(unwrap(resp)) - - async def edit_token( - self, - token_id: str | UUID, - *, - name: str | None = None, - permissions: Sequence[PermissionType | str] | None = None, - ) -> None: - """PATCH /1/tokens/{tokenId} — Edit a token's name or permissions.""" - body: dict[str, Any] = {} - if name is not None: - body["name"] = name - if permissions is not None: - body["permissions"] = _permissions(permissions) - await self._client._request("PATCH", f"/1/tokens/{token_id}", json=body) - - async def revoke_token(self, token_id: str | UUID) -> None: - """DELETE /1/tokens/{tokenId} — Permanently revoke a token.""" - await self._client._request("DELETE", f"/1/tokens/{token_id}") diff --git a/openshock/_async/resources/devices.py b/openshock/_async/resources/devices.py deleted file mode 100644 index 9cfd4c1..0000000 --- a/openshock/_async/resources/devices.py +++ /dev/null @@ -1,80 +0,0 @@ -from __future__ import annotations - -import builtins -from typing import TYPE_CHECKING -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import Device, DeviceWithToken, HubGateway, LcgInfo, OtaUpdate, Shocker - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -class AsyncDevicesResource: - """Hub (device) management.""" - - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - async def list(self) -> builtins.list[Device]: - """GET /1/devices — List all hubs owned by the authenticated user.""" - resp = await self._client._request("GET", "/1/devices") - return [Device.from_dict(d) for d in unwrap_list(resp)] - - async def create(self, name: str) -> UUID: - """POST /2/devices — Create a new hub. Returns the new hub's ID.""" - resp = await self._client._request("POST", "/2/devices", json={"name": name}) - return UUID(str(unwrap(resp)).strip().strip('"')) - - async def get(self, device_id: str | UUID) -> DeviceWithToken: - """ - GET /1/devices/{deviceId} — Get a hub. - - The hub's device token is included when you are allowed to see it. - """ - resp = await self._client._request("GET", f"/1/devices/{device_id}") - return DeviceWithToken.from_dict(unwrap(resp)) - - async def edit(self, device_id: str | UUID, *, name: str) -> None: - """PATCH /1/devices/{deviceId} — Rename a hub.""" - await self._client._request("PATCH", f"/1/devices/{device_id}", json={"name": name}) - - async def delete(self, device_id: str | UUID) -> None: - """DELETE /1/devices/{deviceId} — Delete a hub.""" - await self._client._request("DELETE", f"/1/devices/{device_id}") - - async def regenerate_token(self, device_id: str | UUID) -> str: - """PUT /1/devices/{deviceId} — Regenerate the hub's device token. Returns the new token.""" - resp = await self._client._request("PUT", f"/1/devices/{device_id}") - return str(unwrap(resp)) - - async def shockers(self, device_id: str | UUID) -> builtins.list[Shocker]: - """GET /1/devices/{deviceId}/shockers — List the shockers of a hub.""" - resp = await self._client._request("GET", f"/1/devices/{device_id}/shockers") - return [Shocker.from_dict(s) for s in unwrap_list(resp)] - - async def pair_code(self, device_id: str | UUID) -> str: - """GET /1/devices/{deviceId}/pair — Generate a pair code for a hub (valid 15 minutes).""" - resp = await self._client._request("GET", f"/1/devices/{device_id}/pair") - return str(unwrap(resp)) - - async def gateway(self, device_id: str | UUID) -> HubGateway: - """ - GET /2/devices/{deviceId}/lcg — Get the live control gateway a hub is connected to. - - Raises :class:`~openshock.exceptions.HubOffline` when the hub is not online and - :class:`~openshock.exceptions.HubNotFound` when it does not exist or is not yours. - """ - resp = await self._client._request("GET", f"/2/devices/{device_id}/lcg") - return HubGateway.from_dict(unwrap(resp)) - - async def lcg_info(self, device_id: str | UUID) -> LcgInfo: - """GET /1/devices/{deviceId}/lcg — Legacy gateway lookup. Prefer :meth:`gateway`.""" - resp = await self._client._request("GET", f"/1/devices/{device_id}/lcg") - return LcgInfo.from_dict(unwrap(resp)) - - async def ota_history(self, device_id: str | UUID) -> builtins.list[OtaUpdate]: - """GET /1/devices/{deviceId}/ota — Get the firmware update history of a hub.""" - resp = await self._client._request("GET", f"/1/devices/{device_id}/ota") - return [OtaUpdate.from_dict(o) for o in unwrap_list(resp)] diff --git a/openshock/_async/resources/hub.py b/openshock/_async/resources/hub.py deleted file mode 100644 index aa0d1d5..0000000 --- a/openshock/_async/resources/hub.py +++ /dev/null @@ -1,34 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -from ..._core import unwrap -from ...models import DeviceSelf, LcgNodeV2 - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -class AsyncHubResource: - """Endpoints called by ESP32 hubs using DeviceToken auth.""" - - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - async def self_info(self) -> DeviceSelf: - """GET /1/device/self — Get info about the authenticated hub.""" - resp = await self._client._request("GET", "/1/device/self") - return DeviceSelf.from_dict(unwrap(resp)) - - async def assign_lcg(self, *, version: int | None = None) -> LcgNodeV2: - """GET /2/device/assignLCG — Get the best LCG node for this hub (V2).""" - params: dict[str, Any] = {} - if version is not None: - params["version"] = version - resp = await self._client._request("GET", "/2/device/assignLCG", params=params or None) - return LcgNodeV2.from_dict(unwrap(resp)) - - async def pair(self, pair_code: str) -> str: - """GET /1/device/pair/{pairCode} — Exchange a pair code for the hub's device token.""" - resp = await self._client._request("GET", f"/1/device/pair/{pair_code}") - return str(unwrap(resp)) diff --git a/openshock/_async/resources/meta.py b/openshock/_async/resources/meta.py deleted file mode 100644 index 76376f5..0000000 --- a/openshock/_async/resources/meta.py +++ /dev/null @@ -1,24 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING - -from ..._core import unwrap -from ...models import BackendInfo, Stats - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -class AsyncMetaResource: - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - async def backend_info(self) -> BackendInfo: - """GET /1 — Returns backend version and metadata.""" - resp = await self._client._request("GET", "/1") - return BackendInfo.from_any(unwrap(resp)) - - async def online_stats(self) -> Stats: - """GET /1/public/stats — Returns online device/shocker counts.""" - resp = await self._client._request("GET", "/1/public/stats") - return Stats.from_any(unwrap(resp)) diff --git a/openshock/_async/resources/sessions.py b/openshock/_async/resources/sessions.py deleted file mode 100644 index 6fd921f..0000000 --- a/openshock/_async/resources/sessions.py +++ /dev/null @@ -1,32 +0,0 @@ -from __future__ import annotations - -import builtins -from typing import TYPE_CHECKING -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import Session - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -class AsyncSessionsResource: - """Login session management. These endpoints require user-session auth.""" - - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - async def list(self) -> builtins.list[Session]: - """GET /1/sessions — List all login sessions.""" - resp = await self._client._request("GET", "/1/sessions") - return [Session.from_dict(s) for s in unwrap_list(resp)] - - async def get_current(self) -> Session: - """GET /1/sessions/self — Get the current session.""" - resp = await self._client._request("GET", "/1/sessions/self") - return Session.from_dict(unwrap(resp)) - - async def delete(self, session_id: str | UUID) -> None: - """DELETE /1/sessions/{sessionId} — Invalidate a session.""" - await self._client._request("DELETE", f"/1/sessions/{session_id}") diff --git a/openshock/_async/resources/shares.py b/openshock/_async/resources/shares.py deleted file mode 100644 index 1cec38e..0000000 --- a/openshock/_async/resources/shares.py +++ /dev/null @@ -1,119 +0,0 @@ -from __future__ import annotations - -from datetime import datetime -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import ( - OwnPublicShare, - PauseReason, - PublicShare, - ShockerLimits, - ShockerPermissions, -) -from ...models.common import parse_pause_reason - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -class AsyncSharesResource: - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - # --- public share links --- - - async def list_public(self) -> list[OwnPublicShare]: - """GET /1/shares/links — List all public shares owned by the user.""" - resp = await self._client._request("GET", "/1/shares/links") - return [OwnPublicShare.from_dict(s) for s in unwrap_list(resp)] - - async def create_public( - self, - name: str, - *, - expires_on: datetime | str | None = None, - ) -> UUID: - """POST /1/shares/links — Create a new public share. Returns the share ID.""" - body: dict[str, Any] = {"name": name} - if expires_on is not None: - body["expiresOn"] = expires_on.isoformat() if isinstance(expires_on, datetime) else expires_on - resp = await self._client._request("POST", "/1/shares/links", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - async def delete_public(self, public_share_id: str | UUID) -> None: - """DELETE /1/shares/links/{publicShareId} — Delete a public share.""" - await self._client._request("DELETE", f"/1/shares/links/{public_share_id}") - - async def public_get(self, public_share_id: str | UUID) -> PublicShare: - """GET /1/public/shares/links/{publicShareId} — Get public share info (unauthenticated).""" - resp = await self._client._request("GET", f"/1/public/shares/links/{public_share_id}") - return PublicShare.from_dict(unwrap(resp)) - - # --- shockers within public shares --- - - async def add_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - ) -> None: - """POST /1/shares/links/{publicShareId}/{shockerId} — Add a shocker to a public share.""" - await self._client._request("POST", f"/1/shares/links/{public_share_id}/{shocker_id}") - - async def edit_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - cooldown: int | None = None, - ) -> None: - """PATCH /1/shares/links/{publicShareId}/{shockerId} — Edit a shocker within a public share.""" - body: dict[str, Any] = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - } - if cooldown is not None: - body["cooldown"] = cooldown - await self._client._request( - "PATCH", - f"/1/shares/links/{public_share_id}/{shocker_id}", - json=body, - ) - - async def remove_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - ) -> None: - """DELETE /1/shares/links/{publicShareId}/{shockerId} — Remove a shocker from a public share.""" - await self._client._request("DELETE", f"/1/shares/links/{public_share_id}/{shocker_id}") - - async def pause_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - pause: bool, - ) -> PauseReason: - """ - POST /1/shares/links/{publicShareId}/{shockerId}/pause — Pause or unpause a shocker - within a public share. Returns the resulting pause reasons. - """ - resp = await self._client._request( - "POST", - f"/1/shares/links/{public_share_id}/{shocker_id}/pause", - json={"pause": pause}, - ) - return parse_pause_reason(unwrap(resp)) - - # --- share codes --- - - async def link_code(self, share_code_id: str | UUID) -> None: - """POST /1/shares/code/{shareCodeId} — Redeem a share code.""" - await self._client._request("POST", f"/1/shares/code/{share_code_id}") - - async def delete_code(self, share_code_id: str | UUID) -> None: - """DELETE /1/shares/code/{shareCodeId} — Delete a share code.""" - await self._client._request("DELETE", f"/1/shares/code/{share_code_id}") diff --git a/openshock/_async/resources/shockers.py b/openshock/_async/resources/shockers.py deleted file mode 100644 index 2f75995..0000000 --- a/openshock/_async/resources/shockers.py +++ /dev/null @@ -1,225 +0,0 @@ -from __future__ import annotations - -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import ( - Control, - DeviceWithShockers, - ShareCode, - ShareInfo, - Shocker, - ShockerLimits, - ShockerLog, - ShockerLogWithHub, - ShockerModelType, - ShockerOwner, - ShockerPermissions, -) - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -class AsyncShockersResource: - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - # --- lists & info --- - - async def list_own(self) -> list[DeviceWithShockers]: - """GET /1/shockers/own — List your hubs, each with its shockers.""" - resp = await self._client._request("GET", "/1/shockers/own") - return [DeviceWithShockers.from_dict(d) for d in unwrap_list(resp)] - - async def list_shared(self) -> list[ShockerOwner]: - """GET /1/shockers/shared — List shockers shared with you, grouped by owner and hub.""" - resp = await self._client._request("GET", "/1/shockers/shared") - return [ShockerOwner.from_dict(o) for o in unwrap_list(resp)] - - async def get(self, shocker_id: str | UUID) -> Shocker: - """GET /1/shockers/{shockerId} — Get a shocker, including the ID of its hub (``.device``).""" - resp = await self._client._request("GET", f"/1/shockers/{shocker_id}") - return Shocker.from_dict(unwrap(resp)) - - # --- CRUD --- - - async def register( - self, - *, - name: str, - rf_id: int, - device: str | UUID, - model: ShockerModelType | str, - ) -> UUID: - """POST /1/shockers — Register a new shocker. Returns the new shocker ID.""" - body = { - "name": name, - "rfId": rf_id, - "device": str(device), - "model": ShockerModelType(model).value, - } - resp = await self._client._request("POST", "/1/shockers", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - async def edit( - self, - shocker_id: str | UUID, - *, - name: str | None = None, - rf_id: int | None = None, - device: str | UUID | None = None, - model: ShockerModelType | str | None = None, - ) -> None: - """PATCH /1/shockers/{shockerId} — Update a shocker.""" - body: dict[str, Any] = {} - if name is not None: - body["name"] = name - if rf_id is not None: - body["rfId"] = rf_id - if device is not None: - body["device"] = str(device) - if model is not None: - body["model"] = ShockerModelType(model).value - await self._client._request("PATCH", f"/1/shockers/{shocker_id}", json=body) - - async def delete(self, shocker_id: str | UUID) -> None: - """DELETE /1/shockers/{shockerId} — Delete a shocker.""" - await self._client._request("DELETE", f"/1/shockers/{shocker_id}") - - # --- control & pause --- - - async def control( - self, - controls: Sequence[Control | dict[str, Any]] | Control, - *, - custom_name: str | None = None, - ) -> None: - """ - POST /2/shockers/control — Send control commands to shockers. - - ``custom_name`` is shown in the control logs as the sender name. - - Raises :class:`~openshock.exceptions.ShockerNotFoundOrNoAccess`, - :class:`~openshock.exceptions.ShockerPaused` or - :class:`~openshock.exceptions.ShockerNoPermission` (each with ``.shocker_id``) - when the backend rejects a command. - """ - if isinstance(controls, Control): - controls = [controls] - if not controls: - raise ValueError("controls must be a non-empty sequence") - - body: dict[str, Any] = {"shocks": [c.to_dict() if isinstance(c, Control) else c for c in controls]} - if custom_name is not None: - body["customName"] = custom_name - - await self._client._request("POST", "/2/shockers/control", json=body) - - async def pause(self, shocker_id: str | UUID, pause: bool) -> bool: - """POST /1/shockers/{shockerId}/pause — Pause or unpause a shocker. Returns the new pause state.""" - resp = await self._client._request("POST", f"/1/shockers/{shocker_id}/pause", json={"pause": pause}) - data = unwrap(resp) - return bool(data) if data is not None else pause - - # --- logs --- - - async def logs( - self, - shocker_id: str | UUID, - *, - offset: int = 0, - limit: int = 100, - ) -> list[ShockerLog]: - """GET /1/shockers/{shockerId}/logs — Get control log history.""" - params = {"offset": offset, "limit": limit} - resp = await self._client._request("GET", f"/1/shockers/{shocker_id}/logs", params=params) - return [ShockerLog.from_dict(e) for e in unwrap_list(resp)] - - async def all_logs( - self, - *, - offset: int = 0, - limit: int = 100, - ) -> list[ShockerLogWithHub]: - """GET /1/shockers/logs — Get logs across all owned shockers.""" - params = {"offset": offset, "limit": limit} - resp = await self._client._request("GET", "/1/shockers/logs", params=params) - return [ShockerLogWithHub.from_dict(e) for e in unwrap_list(resp)] - - # --- shares --- - - async def get_shares(self, shocker_id: str | UUID) -> list[ShareInfo]: - """GET /1/shockers/{shockerId}/shares — Get all user shares for a shocker.""" - resp = await self._client._request("GET", f"/1/shockers/{shocker_id}/shares") - return [ShareInfo.from_dict(s) for s in unwrap_list(resp)] - - async def create_share_code( - self, - shocker_id: str | UUID, - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - ) -> UUID: - """POST /1/shockers/{shockerId}/shares — Create a share code. Returns the code ID.""" - body = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - } - resp = await self._client._request("POST", f"/1/shockers/{shocker_id}/shares", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - async def list_share_codes(self, shocker_id: str | UUID) -> list[ShareCode]: - """GET /1/shockers/{shockerId}/shareCodes — List all share codes.""" - resp = await self._client._request("GET", f"/1/shockers/{shocker_id}/shareCodes") - return [ShareCode.from_dict(c) for c in unwrap_list(resp)] - - async def update_share( - self, - shocker_id: str | UUID, - shared_with_user_id: str | UUID, - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - ) -> None: - """PATCH /1/shockers/{shockerId}/shares/{sharedWithUserId} — Update a share's permissions and limits.""" - body = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - } - await self._client._request( - "PATCH", - f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}", - json=body, - ) - - async def remove_share( - self, - shocker_id: str | UUID, - shared_with_user_id: str | UUID, - ) -> None: - """DELETE /1/shockers/{shockerId}/shares/{sharedWithUserId} — Stop sharing a shocker with a user.""" - await self._client._request( - "DELETE", - f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}", - ) - - async def pause_share( - self, - shocker_id: str | UUID, - shared_with_user_id: str | UUID, - pause: bool, - ) -> bool: - """ - POST /1/shockers/{shockerId}/shares/{sharedWithUserId}/pause — Pause or unpause a share. - Returns the new pause state. - """ - resp = await self._client._request( - "POST", - f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}/pause", - json={"pause": pause}, - ) - data = unwrap(resp) - return bool(data) if data is not None else pause diff --git a/openshock/_async/resources/user_shares.py b/openshock/_async/resources/user_shares.py deleted file mode 100644 index a304487..0000000 --- a/openshock/_async/resources/user_shares.py +++ /dev/null @@ -1,123 +0,0 @@ -from __future__ import annotations - -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import ( - BulkPauseResult, - ShareInvite, - ShareInviteShocker, - ShockerLimits, - ShockerPermissions, - UserShare, - UserShares, -) - -if TYPE_CHECKING: - from ..client import _AsyncBaseClient - - -class AsyncUserSharesResource: - """V2 user-to-user share management.""" - - def __init__(self, client: _AsyncBaseClient) -> None: - self._client = client - - async def get(self) -> UserShares: - """GET /2/shares/user — Get all user shares (incoming and outgoing).""" - resp = await self._client._request("GET", "/2/shares/user") - return UserShares.from_dict(unwrap(resp)) - - async def create_invite( - self, - shockers: Sequence[ShareInviteShocker | dict[str, Any]], - *, - user: str | UUID | None = None, - ) -> UUID: - """ - POST /2/shares/user/invites — Create a share invite. Returns the invite ID. - - ``user`` targets a specific user; leave it out to create an open invite. - """ - shocker_list = [] - for s in shockers: - if isinstance(s, ShareInviteShocker): - shocker_list.append(s.to_dict()) - else: - shocker_list.append(s) - - body: dict[str, Any] = {"shockers": shocker_list} - if user is not None: - body["user"] = str(user) - - resp = await self._client._request("POST", "/2/shares/user/invites", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - async def list_outgoing_invites(self) -> list[ShareInvite]: - """GET /2/shares/user/invites/outgoing — List pending outgoing invites.""" - resp = await self._client._request("GET", "/2/shares/user/invites/outgoing") - return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] - - async def list_incoming_invites(self) -> list[ShareInvite]: - """GET /2/shares/user/invites/incoming — List pending incoming invites.""" - resp = await self._client._request("GET", "/2/shares/user/invites/incoming") - return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] - - async def accept_invite(self, invite_id: str | UUID) -> UserShare: - """POST /2/shares/user/invites/incoming/{inviteId} — Accept a share invite.""" - resp = await self._client._request("POST", f"/2/shares/user/invites/incoming/{invite_id}") - return UserShare.from_dict(unwrap(resp)) - - async def delete_outgoing_invite(self, invite_id: str | UUID) -> None: - """DELETE /2/shares/user/invites/outgoing/{inviteId} — Cancel an outgoing invite.""" - await self._client._request("DELETE", f"/2/shares/user/invites/outgoing/{invite_id}") - - async def deny_incoming_invite(self, invite_id: str | UUID) -> None: - """DELETE /2/shares/user/invites/incoming/{inviteId} — Deny an incoming invite.""" - await self._client._request("DELETE", f"/2/shares/user/invites/incoming/{invite_id}") - - async def bulk_pause_shockers( - self, - user_id: str | UUID, - shockers: Sequence[str | UUID], - pause: bool, - ) -> BulkPauseResult: - """POST /2/shares/user/{userId}/shockers/pause — Bulk pause/unpause shared shockers.""" - body = { - "shockers": [str(s) for s in shockers], - "pause": pause, - } - resp = await self._client._request("POST", f"/2/shares/user/{user_id}/shockers/pause", json=body) - return BulkPauseResult.from_dict(unwrap(resp) or {}) - - async def bulk_remove_shockers( - self, - user_id: str | UUID, - shockers: Sequence[str | UUID], - ) -> int: - """DELETE /2/shares/user/{userId}/shockers — Bulk remove shared shockers. Returns the number removed.""" - resp = await self._client._request( - "DELETE", - f"/2/shares/user/{user_id}/shockers", - json=[str(s) for s in shockers], - ) - data = unwrap(resp) - return int(data.get("affectedRecords", 0)) if isinstance(data, dict) else 0 - - async def bulk_update_shockers( - self, - user_id: str | UUID, - shockers: Sequence[str | UUID], - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - ) -> None: - """PATCH /2/shares/user/{userId}/shockers — Bulk update shared shocker permissions.""" - body = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - "shockers": [str(s) for s in shockers], - } - await self._client._request("PATCH", f"/2/shares/user/{user_id}/shockers", json=body) diff --git a/openshock/_core.py b/openshock/_core.py index b05f3e6..168edc7 100644 --- a/openshock/_core.py +++ b/openshock/_core.py @@ -1,18 +1,12 @@ -"""IO-free pieces shared by the sync client, the async client and the realtime clients.""" +"""Small helpers shared by the REST client wrapper and the realtime clients.""" from __future__ import annotations import platform import re -from collections.abc import Callable -from typing import Any, TypeVar - -import httpx +from importlib.metadata import PackageNotFoundError, version from ._version import __version__ -from .exceptions import OpenShockApiError, error_from_response - -T = TypeVar("T") DEFAULT_BASE_URL = "https://api.openshock.app" DEFAULT_TIMEOUT = 10.0 @@ -25,93 +19,34 @@ def _os_name() -> str: return {"Windows": "Windows NT", "Darwin": "macOS", "Linux": "Linux"}.get(system, system or "Unknown OS") +def library_version(name: str) -> str: + try: + return version(name) + except PackageNotFoundError: + return "unknown" + + def build_user_agent( *, component: str = "", app_name: str | None = None, app_version: str | None = None, - libraries: dict[str, str] | None = None, + libraries: tuple[str, ...] = (), ) -> str: """ Build the SDK User-Agent, e.g.:: - OpenShock.SDK.Python/0.2.0 (Python 3.13.0; Linux; httpx 0.28.1; MyApp 1.4.0) + OpenShock.SDK.Python/0.2.0 (Python 3.13.0; Linux; httpx2 2.18.0; MyApp 1.4.0) ``app_name`` / ``app_version`` identify the program using the SDK. Setting them is strongly encouraged: it lets the OpenShock team tell integrations apart. """ product = "OpenShock.SDK.Python" + (f".{component}" if component else "") parts = [f"Python {platform.python_version()}", _os_name()] - for name, ver in (libraries or {}).items(): - parts.append(f"{name} {ver}") + parts += [f"{name} {library_version(name)}" for name in libraries] if app_name: app = _UA_UNSAFE.sub("", app_name).strip() ver = _UA_UNSAFE.sub("", app_version or "").strip() if app: parts.append(f"{app} {ver}".strip()) return f"{product}/{__version__} ({'; '.join(parts)})" - - -def http_user_agent(app_name: str | None, app_version: str | None) -> str: - return build_user_agent(app_name=app_name, app_version=app_version, libraries={"httpx": httpx.__version__}) - - -def _retry_after(resp: httpx.Response) -> float | None: - raw = resp.headers.get("Retry-After") - if raw is None: - return None - try: - return float(raw) - except ValueError: - return None - - -def error_from_httpx(resp: httpx.Response) -> OpenShockApiError: - try: - body_json: Any = resp.json() - except ValueError: - body_json = None - return error_from_response( - status_code=resp.status_code, - body_text=resp.text, - body_json=body_json, - method=resp.request.method, - url=str(resp.request.url), - retry_after=_retry_after(resp), - ) - - -def handle_response(resp: httpx.Response, transform: Callable[[Any], T] | None = None) -> T | Any: - """ - Turn a completed response into a payload, or raise the matching ``OpenShockApiError``. - - 2xx bodies are returned JSON-decoded when possible, else as text (``None`` when empty). - Legacy ``{"message", "data"}`` envelopes are *not* unwrapped here; resources do that. - """ - if not resp.is_success: - raise error_from_httpx(resp) - - payload: Any - if not resp.content: - payload = None - else: - try: - payload = resp.json() - except ValueError: - payload = resp.text - - if transform is not None: - return transform(payload) - return payload - - -def unwrap(payload: Any) -> Any: - """Unwrap the legacy ``{"message": ..., "data": ...}`` envelope if present.""" - if isinstance(payload, dict) and "data" in payload: - return payload["data"] - return payload - - -def unwrap_list(payload: Any) -> list[Any]: - data = unwrap(payload) - return data if isinstance(data, list) else [] diff --git a/openshock/_sync/__init__.py b/openshock/_sync/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/openshock/_sync/client.py b/openshock/_sync/client.py deleted file mode 100644 index 0716662..0000000 --- a/openshock/_sync/client.py +++ /dev/null @@ -1,192 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -from collections.abc import Callable, Mapping -from types import TracebackType -from typing import Any, TypeVar - -import httpx - -from .._core import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, handle_response, http_user_agent -from ..auth import ApiTokenAuth, Auth, HubTokenAuth -from .resources.account import AccountResource -from .resources.devices import DevicesResource -from .resources.hub import HubResource -from .resources.meta import MetaResource -from .resources.sessions import SessionsResource -from .resources.shares import SharesResource -from .resources.shockers import ShockersResource -from .resources.user_shares import UserSharesResource - -T = TypeVar("T") -_SelfT = TypeVar("_SelfT", bound="_BaseClient") - - -class _BaseClient: - """ - Internal base client that handles HTTP, auth and error mapping. - Concrete clients subclass this and attach resources. - """ - - def __init__( - self, - *, - auth: Auth, - base_url: str = DEFAULT_BASE_URL, - timeout: float = DEFAULT_TIMEOUT, - app_name: str | None = None, - app_version: str | None = None, - headers: Mapping[str, str] | None = None, - transport: httpx.BaseTransport | None = None, - ) -> None: - self._auth = auth - self._base_url = base_url.rstrip("/") - self._app_name = app_name - self._app_version = app_version - self._client = httpx.Client( - base_url=self._base_url, - timeout=timeout, - transport=transport, - headers={**(headers or {}), "User-Agent": http_user_agent(app_name, app_version)}, - ) - - # --- introspection ----------------------------------------------------- - - @property - def auth(self) -> Auth: - return self._auth - - @property - def base_url(self) -> str: - return self._base_url - - # --- lifecycle --------------------------------------------------------- - - def close(self) -> None: - self._client.close() - - def __enter__(self: _SelfT) -> _SelfT: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - self.close() - - # --- internal helpers -------------------------------------------------- - - def _request( - self, - method: str, - path: str, - *, - params: dict[str, Any] | None = None, - json: Any = None, - transform: Callable[[Any], T] | None = None, - ) -> T | Any: - """ - Perform an HTTP request and return the parsed payload for 2xx responses - (JSON-decoded when possible, otherwise text, ``None`` for an empty body). - - On non-2xx an :class:`~openshock.exceptions.OpenShockApiError` subclass is raised; - see :func:`openshock.exceptions.error_from_response` for the mapping. - """ - resp = self._client.request( - method, - path, - params=params, - json=json, - headers=dict(self._auth.headers()), - ) - return handle_response(resp, transform) - - -class OpenShockClient(_BaseClient): - """ - High-level client for the *user* OpenShock REST API (ApiToken-based). - - ``app_name`` / ``app_version`` identify your program in the User-Agent header. - """ - - def __init__( - self, - *, - auth: ApiTokenAuth | None = None, - api_token: str | None = None, - base_url: str = DEFAULT_BASE_URL, - timeout: float = DEFAULT_TIMEOUT, - app_name: str | None = None, - app_version: str | None = None, - headers: Mapping[str, str] | None = None, - transport: httpx.BaseTransport | None = None, - ) -> None: - if auth is not None and api_token is not None: - raise ValueError("Provide either `auth` or `api_token`, not both.") - - if auth is None: - if api_token is None: - raise ValueError("You must provide either `auth` or `api_token`.") - auth = ApiTokenAuth(api_token) - - super().__init__( - auth=auth, - base_url=base_url, - timeout=timeout, - app_name=app_name, - app_version=app_version, - headers=headers, - transport=transport, - ) - - self.meta = MetaResource(self) - self.account = AccountResource(self) - self.devices = DevicesResource(self) - self.shockers = ShockersResource(self) - self.shares = SharesResource(self) - self.sessions = SessionsResource(self) - self.user_shares = UserSharesResource(self) - - -class OpenShockHubClient(_BaseClient): - """ - High-level client for the *hub/device* OpenShock REST API (DeviceToken-based). - - This is what a hub (the ESP32 device) itself talks to. To receive realtime user - events use :class:`openshock.realtime.UserHubClient` instead. - """ - - def __init__( - self, - *, - auth: HubTokenAuth | None = None, - hub_token: str | None = None, - base_url: str = DEFAULT_BASE_URL, - timeout: float = DEFAULT_TIMEOUT, - app_name: str | None = None, - app_version: str | None = None, - headers: Mapping[str, str] | None = None, - transport: httpx.BaseTransport | None = None, - ) -> None: - if auth is not None and hub_token is not None: - raise ValueError("Provide either `auth` or `hub_token`, not both.") - - if auth is None: - if hub_token is None: - raise ValueError("You must provide either `auth` or `hub_token`.") - auth = HubTokenAuth(hub_token) - - super().__init__( - auth=auth, - base_url=base_url, - timeout=timeout, - app_name=app_name, - app_version=app_version, - headers=headers, - transport=transport, - ) - - self.hub = HubResource(self) - self.meta = MetaResource(self) diff --git a/openshock/_sync/resources/__init__.py b/openshock/_sync/resources/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/openshock/_sync/resources/account.py b/openshock/_sync/resources/account.py deleted file mode 100644 index 51e1322..0000000 --- a/openshock/_sync/resources/account.py +++ /dev/null @@ -1,78 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -from collections.abc import Sequence -from datetime import datetime -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import CreatedToken, PermissionType, Token, User - -if TYPE_CHECKING: - from ..client import _BaseClient - - -def _permissions(permissions: Sequence[PermissionType | str]) -> list[str]: - return [PermissionType(p).value for p in permissions] - - -class AccountResource: - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def user_self(self) -> User: - """GET /1/users/self — Get the authenticated user's info.""" - resp = self._client._request("GET", "/1/users/self") - return User.from_dict(unwrap(resp)) - - def token_self(self) -> Token: - """GET /1/tokens/self — Get info about the API token being used.""" - resp = self._client._request("GET", "/1/tokens/self") - return Token.from_dict(unwrap(resp)) - - def list_tokens(self) -> list[Token]: - """GET /1/tokens — List all API tokens for the authenticated user.""" - resp = self._client._request("GET", "/1/tokens") - return [Token.from_dict(t) for t in unwrap_list(resp)] - - def create_token( - self, - name: str, - permissions: Sequence[PermissionType | str], - valid_until: datetime | str | None = None, - ) -> CreatedToken: - """ - POST /1/tokens — Create a new API token. - - The returned object carries the token secret; it cannot be retrieved again later. - """ - body: dict[str, Any] = {"name": name, "permissions": _permissions(permissions)} - if valid_until is not None: - body["validUntil"] = valid_until.isoformat() if isinstance(valid_until, datetime) else valid_until - resp = self._client._request("POST", "/1/tokens", json=body) - return CreatedToken.from_dict(unwrap(resp)) - - def get_token(self, token_id: str | UUID) -> Token: - """GET /1/tokens/{tokenId} — Get a token by ID.""" - resp = self._client._request("GET", f"/1/tokens/{token_id}") - return Token.from_dict(unwrap(resp)) - - def edit_token( - self, - token_id: str | UUID, - *, - name: str | None = None, - permissions: Sequence[PermissionType | str] | None = None, - ) -> None: - """PATCH /1/tokens/{tokenId} — Edit a token's name or permissions.""" - body: dict[str, Any] = {} - if name is not None: - body["name"] = name - if permissions is not None: - body["permissions"] = _permissions(permissions) - self._client._request("PATCH", f"/1/tokens/{token_id}", json=body) - - def revoke_token(self, token_id: str | UUID) -> None: - """DELETE /1/tokens/{tokenId} — Permanently revoke a token.""" - self._client._request("DELETE", f"/1/tokens/{token_id}") diff --git a/openshock/_sync/resources/devices.py b/openshock/_sync/resources/devices.py deleted file mode 100644 index d80dfb1..0000000 --- a/openshock/_sync/resources/devices.py +++ /dev/null @@ -1,81 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -import builtins -from typing import TYPE_CHECKING -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import Device, DeviceWithToken, HubGateway, LcgInfo, OtaUpdate, Shocker - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class DevicesResource: - """Hub (device) management.""" - - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def list(self) -> builtins.list[Device]: - """GET /1/devices — List all hubs owned by the authenticated user.""" - resp = self._client._request("GET", "/1/devices") - return [Device.from_dict(d) for d in unwrap_list(resp)] - - def create(self, name: str) -> UUID: - """POST /2/devices — Create a new hub. Returns the new hub's ID.""" - resp = self._client._request("POST", "/2/devices", json={"name": name}) - return UUID(str(unwrap(resp)).strip().strip('"')) - - def get(self, device_id: str | UUID) -> DeviceWithToken: - """ - GET /1/devices/{deviceId} — Get a hub. - - The hub's device token is included when you are allowed to see it. - """ - resp = self._client._request("GET", f"/1/devices/{device_id}") - return DeviceWithToken.from_dict(unwrap(resp)) - - def edit(self, device_id: str | UUID, *, name: str) -> None: - """PATCH /1/devices/{deviceId} — Rename a hub.""" - self._client._request("PATCH", f"/1/devices/{device_id}", json={"name": name}) - - def delete(self, device_id: str | UUID) -> None: - """DELETE /1/devices/{deviceId} — Delete a hub.""" - self._client._request("DELETE", f"/1/devices/{device_id}") - - def regenerate_token(self, device_id: str | UUID) -> str: - """PUT /1/devices/{deviceId} — Regenerate the hub's device token. Returns the new token.""" - resp = self._client._request("PUT", f"/1/devices/{device_id}") - return str(unwrap(resp)) - - def shockers(self, device_id: str | UUID) -> builtins.list[Shocker]: - """GET /1/devices/{deviceId}/shockers — List the shockers of a hub.""" - resp = self._client._request("GET", f"/1/devices/{device_id}/shockers") - return [Shocker.from_dict(s) for s in unwrap_list(resp)] - - def pair_code(self, device_id: str | UUID) -> str: - """GET /1/devices/{deviceId}/pair — Generate a pair code for a hub (valid 15 minutes).""" - resp = self._client._request("GET", f"/1/devices/{device_id}/pair") - return str(unwrap(resp)) - - def gateway(self, device_id: str | UUID) -> HubGateway: - """ - GET /2/devices/{deviceId}/lcg — Get the live control gateway a hub is connected to. - - Raises :class:`~openshock.exceptions.HubOffline` when the hub is not online and - :class:`~openshock.exceptions.HubNotFound` when it does not exist or is not yours. - """ - resp = self._client._request("GET", f"/2/devices/{device_id}/lcg") - return HubGateway.from_dict(unwrap(resp)) - - def lcg_info(self, device_id: str | UUID) -> LcgInfo: - """GET /1/devices/{deviceId}/lcg — Legacy gateway lookup. Prefer :meth:`gateway`.""" - resp = self._client._request("GET", f"/1/devices/{device_id}/lcg") - return LcgInfo.from_dict(unwrap(resp)) - - def ota_history(self, device_id: str | UUID) -> builtins.list[OtaUpdate]: - """GET /1/devices/{deviceId}/ota — Get the firmware update history of a hub.""" - resp = self._client._request("GET", f"/1/devices/{device_id}/ota") - return [OtaUpdate.from_dict(o) for o in unwrap_list(resp)] diff --git a/openshock/_sync/resources/hub.py b/openshock/_sync/resources/hub.py deleted file mode 100644 index 851462b..0000000 --- a/openshock/_sync/resources/hub.py +++ /dev/null @@ -1,35 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -from ..._core import unwrap -from ...models import DeviceSelf, LcgNodeV2 - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class HubResource: - """Endpoints called by ESP32 hubs using DeviceToken auth.""" - - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def self_info(self) -> DeviceSelf: - """GET /1/device/self — Get info about the authenticated hub.""" - resp = self._client._request("GET", "/1/device/self") - return DeviceSelf.from_dict(unwrap(resp)) - - def assign_lcg(self, *, version: int | None = None) -> LcgNodeV2: - """GET /2/device/assignLCG — Get the best LCG node for this hub (V2).""" - params: dict[str, Any] = {} - if version is not None: - params["version"] = version - resp = self._client._request("GET", "/2/device/assignLCG", params=params or None) - return LcgNodeV2.from_dict(unwrap(resp)) - - def pair(self, pair_code: str) -> str: - """GET /1/device/pair/{pairCode} — Exchange a pair code for the hub's device token.""" - resp = self._client._request("GET", f"/1/device/pair/{pair_code}") - return str(unwrap(resp)) diff --git a/openshock/_sync/resources/meta.py b/openshock/_sync/resources/meta.py deleted file mode 100644 index a1e8cd0..0000000 --- a/openshock/_sync/resources/meta.py +++ /dev/null @@ -1,25 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -from typing import TYPE_CHECKING - -from ..._core import unwrap -from ...models import BackendInfo, Stats - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class MetaResource: - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def backend_info(self) -> BackendInfo: - """GET /1 — Returns backend version and metadata.""" - resp = self._client._request("GET", "/1") - return BackendInfo.from_any(unwrap(resp)) - - def online_stats(self) -> Stats: - """GET /1/public/stats — Returns online device/shocker counts.""" - resp = self._client._request("GET", "/1/public/stats") - return Stats.from_any(unwrap(resp)) diff --git a/openshock/_sync/resources/sessions.py b/openshock/_sync/resources/sessions.py deleted file mode 100644 index 346db9d..0000000 --- a/openshock/_sync/resources/sessions.py +++ /dev/null @@ -1,33 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -import builtins -from typing import TYPE_CHECKING -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import Session - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class SessionsResource: - """Login session management. These endpoints require user-session auth.""" - - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def list(self) -> builtins.list[Session]: - """GET /1/sessions — List all login sessions.""" - resp = self._client._request("GET", "/1/sessions") - return [Session.from_dict(s) for s in unwrap_list(resp)] - - def get_current(self) -> Session: - """GET /1/sessions/self — Get the current session.""" - resp = self._client._request("GET", "/1/sessions/self") - return Session.from_dict(unwrap(resp)) - - def delete(self, session_id: str | UUID) -> None: - """DELETE /1/sessions/{sessionId} — Invalidate a session.""" - self._client._request("DELETE", f"/1/sessions/{session_id}") diff --git a/openshock/_sync/resources/shares.py b/openshock/_sync/resources/shares.py deleted file mode 100644 index 2f3ff79..0000000 --- a/openshock/_sync/resources/shares.py +++ /dev/null @@ -1,120 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -from datetime import datetime -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import ( - OwnPublicShare, - PauseReason, - PublicShare, - ShockerLimits, - ShockerPermissions, -) -from ...models.common import parse_pause_reason - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class SharesResource: - def __init__(self, client: _BaseClient) -> None: - self._client = client - - # --- public share links --- - - def list_public(self) -> list[OwnPublicShare]: - """GET /1/shares/links — List all public shares owned by the user.""" - resp = self._client._request("GET", "/1/shares/links") - return [OwnPublicShare.from_dict(s) for s in unwrap_list(resp)] - - def create_public( - self, - name: str, - *, - expires_on: datetime | str | None = None, - ) -> UUID: - """POST /1/shares/links — Create a new public share. Returns the share ID.""" - body: dict[str, Any] = {"name": name} - if expires_on is not None: - body["expiresOn"] = expires_on.isoformat() if isinstance(expires_on, datetime) else expires_on - resp = self._client._request("POST", "/1/shares/links", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - def delete_public(self, public_share_id: str | UUID) -> None: - """DELETE /1/shares/links/{publicShareId} — Delete a public share.""" - self._client._request("DELETE", f"/1/shares/links/{public_share_id}") - - def public_get(self, public_share_id: str | UUID) -> PublicShare: - """GET /1/public/shares/links/{publicShareId} — Get public share info (unauthenticated).""" - resp = self._client._request("GET", f"/1/public/shares/links/{public_share_id}") - return PublicShare.from_dict(unwrap(resp)) - - # --- shockers within public shares --- - - def add_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - ) -> None: - """POST /1/shares/links/{publicShareId}/{shockerId} — Add a shocker to a public share.""" - self._client._request("POST", f"/1/shares/links/{public_share_id}/{shocker_id}") - - def edit_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - cooldown: int | None = None, - ) -> None: - """PATCH /1/shares/links/{publicShareId}/{shockerId} — Edit a shocker within a public share.""" - body: dict[str, Any] = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - } - if cooldown is not None: - body["cooldown"] = cooldown - self._client._request( - "PATCH", - f"/1/shares/links/{public_share_id}/{shocker_id}", - json=body, - ) - - def remove_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - ) -> None: - """DELETE /1/shares/links/{publicShareId}/{shockerId} — Remove a shocker from a public share.""" - self._client._request("DELETE", f"/1/shares/links/{public_share_id}/{shocker_id}") - - def pause_shocker( - self, - public_share_id: str | UUID, - shocker_id: str | UUID, - pause: bool, - ) -> PauseReason: - """ - POST /1/shares/links/{publicShareId}/{shockerId}/pause — Pause or unpause a shocker - within a public share. Returns the resulting pause reasons. - """ - resp = self._client._request( - "POST", - f"/1/shares/links/{public_share_id}/{shocker_id}/pause", - json={"pause": pause}, - ) - return parse_pause_reason(unwrap(resp)) - - # --- share codes --- - - def link_code(self, share_code_id: str | UUID) -> None: - """POST /1/shares/code/{shareCodeId} — Redeem a share code.""" - self._client._request("POST", f"/1/shares/code/{share_code_id}") - - def delete_code(self, share_code_id: str | UUID) -> None: - """DELETE /1/shares/code/{shareCodeId} — Delete a share code.""" - self._client._request("DELETE", f"/1/shares/code/{share_code_id}") diff --git a/openshock/_sync/resources/shockers.py b/openshock/_sync/resources/shockers.py deleted file mode 100644 index 5e46316..0000000 --- a/openshock/_sync/resources/shockers.py +++ /dev/null @@ -1,226 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import ( - Control, - DeviceWithShockers, - ShareCode, - ShareInfo, - Shocker, - ShockerLimits, - ShockerLog, - ShockerLogWithHub, - ShockerModelType, - ShockerOwner, - ShockerPermissions, -) - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class ShockersResource: - def __init__(self, client: _BaseClient) -> None: - self._client = client - - # --- lists & info --- - - def list_own(self) -> list[DeviceWithShockers]: - """GET /1/shockers/own — List your hubs, each with its shockers.""" - resp = self._client._request("GET", "/1/shockers/own") - return [DeviceWithShockers.from_dict(d) for d in unwrap_list(resp)] - - def list_shared(self) -> list[ShockerOwner]: - """GET /1/shockers/shared — List shockers shared with you, grouped by owner and hub.""" - resp = self._client._request("GET", "/1/shockers/shared") - return [ShockerOwner.from_dict(o) for o in unwrap_list(resp)] - - def get(self, shocker_id: str | UUID) -> Shocker: - """GET /1/shockers/{shockerId} — Get a shocker, including the ID of its hub (``.device``).""" - resp = self._client._request("GET", f"/1/shockers/{shocker_id}") - return Shocker.from_dict(unwrap(resp)) - - # --- CRUD --- - - def register( - self, - *, - name: str, - rf_id: int, - device: str | UUID, - model: ShockerModelType | str, - ) -> UUID: - """POST /1/shockers — Register a new shocker. Returns the new shocker ID.""" - body = { - "name": name, - "rfId": rf_id, - "device": str(device), - "model": ShockerModelType(model).value, - } - resp = self._client._request("POST", "/1/shockers", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - def edit( - self, - shocker_id: str | UUID, - *, - name: str | None = None, - rf_id: int | None = None, - device: str | UUID | None = None, - model: ShockerModelType | str | None = None, - ) -> None: - """PATCH /1/shockers/{shockerId} — Update a shocker.""" - body: dict[str, Any] = {} - if name is not None: - body["name"] = name - if rf_id is not None: - body["rfId"] = rf_id - if device is not None: - body["device"] = str(device) - if model is not None: - body["model"] = ShockerModelType(model).value - self._client._request("PATCH", f"/1/shockers/{shocker_id}", json=body) - - def delete(self, shocker_id: str | UUID) -> None: - """DELETE /1/shockers/{shockerId} — Delete a shocker.""" - self._client._request("DELETE", f"/1/shockers/{shocker_id}") - - # --- control & pause --- - - def control( - self, - controls: Sequence[Control | dict[str, Any]] | Control, - *, - custom_name: str | None = None, - ) -> None: - """ - POST /2/shockers/control — Send control commands to shockers. - - ``custom_name`` is shown in the control logs as the sender name. - - Raises :class:`~openshock.exceptions.ShockerNotFoundOrNoAccess`, - :class:`~openshock.exceptions.ShockerPaused` or - :class:`~openshock.exceptions.ShockerNoPermission` (each with ``.shocker_id``) - when the backend rejects a command. - """ - if isinstance(controls, Control): - controls = [controls] - if not controls: - raise ValueError("controls must be a non-empty sequence") - - body: dict[str, Any] = {"shocks": [c.to_dict() if isinstance(c, Control) else c for c in controls]} - if custom_name is not None: - body["customName"] = custom_name - - self._client._request("POST", "/2/shockers/control", json=body) - - def pause(self, shocker_id: str | UUID, pause: bool) -> bool: - """POST /1/shockers/{shockerId}/pause — Pause or unpause a shocker. Returns the new pause state.""" - resp = self._client._request("POST", f"/1/shockers/{shocker_id}/pause", json={"pause": pause}) - data = unwrap(resp) - return bool(data) if data is not None else pause - - # --- logs --- - - def logs( - self, - shocker_id: str | UUID, - *, - offset: int = 0, - limit: int = 100, - ) -> list[ShockerLog]: - """GET /1/shockers/{shockerId}/logs — Get control log history.""" - params = {"offset": offset, "limit": limit} - resp = self._client._request("GET", f"/1/shockers/{shocker_id}/logs", params=params) - return [ShockerLog.from_dict(e) for e in unwrap_list(resp)] - - def all_logs( - self, - *, - offset: int = 0, - limit: int = 100, - ) -> list[ShockerLogWithHub]: - """GET /1/shockers/logs — Get logs across all owned shockers.""" - params = {"offset": offset, "limit": limit} - resp = self._client._request("GET", "/1/shockers/logs", params=params) - return [ShockerLogWithHub.from_dict(e) for e in unwrap_list(resp)] - - # --- shares --- - - def get_shares(self, shocker_id: str | UUID) -> list[ShareInfo]: - """GET /1/shockers/{shockerId}/shares — Get all user shares for a shocker.""" - resp = self._client._request("GET", f"/1/shockers/{shocker_id}/shares") - return [ShareInfo.from_dict(s) for s in unwrap_list(resp)] - - def create_share_code( - self, - shocker_id: str | UUID, - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - ) -> UUID: - """POST /1/shockers/{shockerId}/shares — Create a share code. Returns the code ID.""" - body = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - } - resp = self._client._request("POST", f"/1/shockers/{shocker_id}/shares", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - def list_share_codes(self, shocker_id: str | UUID) -> list[ShareCode]: - """GET /1/shockers/{shockerId}/shareCodes — List all share codes.""" - resp = self._client._request("GET", f"/1/shockers/{shocker_id}/shareCodes") - return [ShareCode.from_dict(c) for c in unwrap_list(resp)] - - def update_share( - self, - shocker_id: str | UUID, - shared_with_user_id: str | UUID, - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - ) -> None: - """PATCH /1/shockers/{shockerId}/shares/{sharedWithUserId} — Update a share's permissions and limits.""" - body = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - } - self._client._request( - "PATCH", - f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}", - json=body, - ) - - def remove_share( - self, - shocker_id: str | UUID, - shared_with_user_id: str | UUID, - ) -> None: - """DELETE /1/shockers/{shockerId}/shares/{sharedWithUserId} — Stop sharing a shocker with a user.""" - self._client._request( - "DELETE", - f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}", - ) - - def pause_share( - self, - shocker_id: str | UUID, - shared_with_user_id: str | UUID, - pause: bool, - ) -> bool: - """ - POST /1/shockers/{shockerId}/shares/{sharedWithUserId}/pause — Pause or unpause a share. - Returns the new pause state. - """ - resp = self._client._request( - "POST", - f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}/pause", - json={"pause": pause}, - ) - data = unwrap(resp) - return bool(data) if data is not None else pause diff --git a/openshock/_sync/resources/user_shares.py b/openshock/_sync/resources/user_shares.py deleted file mode 100644 index 5a31dc9..0000000 --- a/openshock/_sync/resources/user_shares.py +++ /dev/null @@ -1,124 +0,0 @@ -# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand. -from __future__ import annotations - -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..._core import unwrap, unwrap_list -from ...models import ( - BulkPauseResult, - ShareInvite, - ShareInviteShocker, - ShockerLimits, - ShockerPermissions, - UserShare, - UserShares, -) - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class UserSharesResource: - """V2 user-to-user share management.""" - - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def get(self) -> UserShares: - """GET /2/shares/user — Get all user shares (incoming and outgoing).""" - resp = self._client._request("GET", "/2/shares/user") - return UserShares.from_dict(unwrap(resp)) - - def create_invite( - self, - shockers: Sequence[ShareInviteShocker | dict[str, Any]], - *, - user: str | UUID | None = None, - ) -> UUID: - """ - POST /2/shares/user/invites — Create a share invite. Returns the invite ID. - - ``user`` targets a specific user; leave it out to create an open invite. - """ - shocker_list = [] - for s in shockers: - if isinstance(s, ShareInviteShocker): - shocker_list.append(s.to_dict()) - else: - shocker_list.append(s) - - body: dict[str, Any] = {"shockers": shocker_list} - if user is not None: - body["user"] = str(user) - - resp = self._client._request("POST", "/2/shares/user/invites", json=body) - return UUID(str(unwrap(resp)).strip().strip('"')) - - def list_outgoing_invites(self) -> list[ShareInvite]: - """GET /2/shares/user/invites/outgoing — List pending outgoing invites.""" - resp = self._client._request("GET", "/2/shares/user/invites/outgoing") - return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] - - def list_incoming_invites(self) -> list[ShareInvite]: - """GET /2/shares/user/invites/incoming — List pending incoming invites.""" - resp = self._client._request("GET", "/2/shares/user/invites/incoming") - return [ShareInvite.from_dict(i) for i in unwrap_list(resp)] - - def accept_invite(self, invite_id: str | UUID) -> UserShare: - """POST /2/shares/user/invites/incoming/{inviteId} — Accept a share invite.""" - resp = self._client._request("POST", f"/2/shares/user/invites/incoming/{invite_id}") - return UserShare.from_dict(unwrap(resp)) - - def delete_outgoing_invite(self, invite_id: str | UUID) -> None: - """DELETE /2/shares/user/invites/outgoing/{inviteId} — Cancel an outgoing invite.""" - self._client._request("DELETE", f"/2/shares/user/invites/outgoing/{invite_id}") - - def deny_incoming_invite(self, invite_id: str | UUID) -> None: - """DELETE /2/shares/user/invites/incoming/{inviteId} — Deny an incoming invite.""" - self._client._request("DELETE", f"/2/shares/user/invites/incoming/{invite_id}") - - def bulk_pause_shockers( - self, - user_id: str | UUID, - shockers: Sequence[str | UUID], - pause: bool, - ) -> BulkPauseResult: - """POST /2/shares/user/{userId}/shockers/pause — Bulk pause/unpause shared shockers.""" - body = { - "shockers": [str(s) for s in shockers], - "pause": pause, - } - resp = self._client._request("POST", f"/2/shares/user/{user_id}/shockers/pause", json=body) - return BulkPauseResult.from_dict(unwrap(resp) or {}) - - def bulk_remove_shockers( - self, - user_id: str | UUID, - shockers: Sequence[str | UUID], - ) -> int: - """DELETE /2/shares/user/{userId}/shockers — Bulk remove shared shockers. Returns the number removed.""" - resp = self._client._request( - "DELETE", - f"/2/shares/user/{user_id}/shockers", - json=[str(s) for s in shockers], - ) - data = unwrap(resp) - return int(data.get("affectedRecords", 0)) if isinstance(data, dict) else 0 - - def bulk_update_shockers( - self, - user_id: str | UUID, - shockers: Sequence[str | UUID], - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - ) -> None: - """PATCH /2/shares/user/{userId}/shockers — Bulk update shared shocker permissions.""" - body = { - "permissions": permissions.to_dict(), - "limits": limits.to_dict(), - "shockers": [str(s) for s in shockers], - } - self._client._request("PATCH", f"/2/shares/user/{user_id}/shockers", json=body) diff --git a/openshock/auth.py b/openshock/auth.py deleted file mode 100644 index 9a834dc..0000000 --- a/openshock/auth.py +++ /dev/null @@ -1,44 +0,0 @@ -from __future__ import annotations - -from collections.abc import Mapping -from dataclasses import dataclass - - -class Auth: - """ - Base class for authentication. - - Subclasses should override `headers()` to return the headers - required for auth on each request. - """ - - def headers(self) -> Mapping[str, str]: - return {} - - -@dataclass -class ApiTokenAuth(Auth): - """ - Auth using an API token. - - Sends: OpenShockToken: - """ - - token: str - - def headers(self) -> Mapping[str, str]: - return {"OpenShockToken": self.token} - - -@dataclass -class HubTokenAuth(Auth): - """ - Auth using a Device / Hub token. - - Sends: DeviceToken: - """ - - token: str - - def headers(self) -> Mapping[str, str]: - return {"DeviceToken": self.token} diff --git a/openshock/client.py b/openshock/client.py index 60998c8..30b0b2b 100644 --- a/openshock/client.py +++ b/openshock/client.py @@ -1,6 +1,155 @@ -"""Public home of the REST clients. The sync classes are generated from the async ones.""" +""" +Preconfigured clients for the generated REST API (:mod:`openshock.rest`). -from ._async.client import AsyncOpenShockClient as AsyncOpenShockClient -from ._async.client import AsyncOpenShockHubClient as AsyncOpenShockHubClient -from ._sync.client import OpenShockClient as OpenShockClient -from ._sync.client import OpenShockHubClient as OpenShockHubClient +The generated client classes know nothing about OpenShock's header names or defaults. +These thin subclasses fill them in; everything else, including every endpoint, is generated. +""" + +from __future__ import annotations + +import contextlib +from typing import Any + +import httpx2 + +from ._core import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, build_user_agent +from .exceptions import OpenShockApiError, error_from_response +from .rest.client import AuthenticatedClient + + +def _error_for(response: httpx2.Response) -> OpenShockApiError: + try: + body_json: Any = response.json() + except ValueError: + body_json = None + retry_after: float | None = None + with contextlib.suppress(KeyError, ValueError): + retry_after = float(response.headers["Retry-After"]) + return error_from_response( + status_code=response.status_code, + body_text=response.text, + body_json=body_json, + method=response.request.method, + url=str(response.request.url), + retry_after=retry_after, + ) + + +def _raise_for_error(response: httpx2.Response) -> None: + if not response.is_success: + response.read() + raise _error_for(response) + + +async def _raise_for_error_async(response: httpx2.Response) -> None: + if not response.is_success: + await response.aread() + raise _error_for(response) + + +class _PresetClient(AuthenticatedClient): + _header_name = "" + + def __init__( + self, + credential: str | None = None, + *, + base_url: str = DEFAULT_BASE_URL, + app_name: str | None = None, + app_version: str | None = None, + timeout: httpx2.Timeout | float | None = DEFAULT_TIMEOUT, + headers: dict[str, str] | None = None, + raise_on_error: bool = True, + raise_on_unexpected_status: bool = True, + # Accepted so the generated with_headers()/with_cookies()/with_timeout() can rebuild us. + token: str | None = None, + prefix: str = "", + auth_header_name: str | None = None, + **kwargs: Any, + ) -> None: + credential = credential if credential is not None else token + if not credential: + raise ValueError(f"A token for the {self._header_name} header is required.") + merged = dict(headers or {}) + merged.setdefault( + "User-Agent", build_user_agent(app_name=app_name, app_version=app_version, libraries=("httpx2",)) + ) + if isinstance(timeout, int | float): + timeout = httpx2.Timeout(timeout) + super().__init__( + base_url.rstrip("/"), + credential, + prefix, + auth_header_name or self._header_name, + raise_on_unexpected_status=raise_on_unexpected_status, + headers=merged, + timeout=timeout, + **kwargs, + ) + self._raise_on_error = raise_on_error + + def get_httpx_client(self) -> httpx2.Client: + client = super().get_httpx_client() + hooks = client.event_hooks["response"] + if self._raise_on_error and _raise_for_error not in hooks: + hooks.append(_raise_for_error) + return client + + def get_async_httpx_client(self) -> httpx2.AsyncClient: + client = super().get_async_httpx_client() + hooks = client.event_hooks["response"] + if self._raise_on_error and _raise_for_error_async not in hooks: + hooks.append(_raise_for_error_async) + return client + + @property + def base_url(self) -> str: + return self._base_url + + @property + def auth_headers(self) -> dict[str, str]: + """The authentication header this client sends, for use outside the REST API.""" + return {self.auth_header_name: self.token} + + +class OpenShockClient(_PresetClient): + """ + Client for the user-facing REST API, authenticated with an API token. + + Pass it as ``client=`` to the functions under :mod:`openshock.rest.api`. Every endpoint + has a blocking and an asyncio form, and the same client serves both:: + + from openshock import OpenShockClient, unwrap + from openshock.rest.api.shockers import shocker_list_shockers + + with OpenShockClient("your-api-token", app_name="MyApp", app_version="1.0") as client: + hubs = unwrap(shocker_list_shockers.sync(client=client)).data + + async with OpenShockClient("your-api-token") as client: + hubs = unwrap(await shocker_list_shockers.asyncio(client=client)).data + + ``app_name`` / ``app_version`` identify your program in the User-Agent header. + + Unlike the plain generated client, a non-2xx answer raises the matching + :class:`~openshock.exceptions.OpenShockApiError` subclass instead of being returned. + Pass ``raise_on_error=False`` to get the generated behaviour back. + """ + + _header_name = "OpenShockToken" + + def __init__(self, api_token: str | None = None, **kwargs: Any) -> None: + super().__init__(api_token, **kwargs) + + +class OpenShockHubClient(_PresetClient): + """ + Client for the endpoints a hub (the ESP32 device) itself calls, authenticated with + its device token. See :mod:`openshock.rest.api.hub_endpoints`. + + To receive realtime user events use :class:`openshock.realtime.UserHubClient` instead. + """ + + _header_name = "DeviceToken" + + def __init__(self, hub_token: str | None = None, **kwargs: Any) -> None: + super().__init__(hub_token, **kwargs) diff --git a/openshock/exceptions.py b/openshock/exceptions.py index f2a11fb..9ebdfb4 100644 --- a/openshock/exceptions.py +++ b/openshock/exceptions.py @@ -1,12 +1,20 @@ from __future__ import annotations +import contextlib +import json from dataclasses import dataclass, field -from typing import Any +from typing import TYPE_CHECKING, Any, TypeVar, overload from uuid import UUID +if TYPE_CHECKING: + from .rest.models import OpenShockProblem, ProblemDetails + from .rest.types import Response + +_T = TypeVar("_T") + @dataclass(frozen=True) -class ProblemDetails: +class Problem: """An RFC 7807 problem document as returned by the OpenShock backend.""" type: str @@ -18,7 +26,7 @@ class ProblemDetails: extensions: dict[str, Any] = field(default_factory=dict) @classmethod - def from_dict(cls, data: dict[str, Any], *, status: int | None = None) -> ProblemDetails: + def from_dict(cls, data: dict[str, Any], *, status: int | None = None) -> Problem: known = {"type", "title", "status", "detail", "requestid", "traceid"} return cls( type=str(data.get("type") or ""), @@ -48,7 +56,7 @@ def __init__( message: str, *, status_code: int = 0, - problem: ProblemDetails | None = None, + problem: Problem | None = None, body: str | None = None, ) -> None: super().__init__(message) @@ -135,7 +143,7 @@ class HubInvocationError(OpenShockError): """The SignalR hub reported an error for a method invocation.""" -def _ext(problem: ProblemDetails | None, key: str) -> Any: +def _ext(problem: Problem | None, key: str) -> Any: if problem is None: return None for k, v in problem.extensions.items(): @@ -168,11 +176,11 @@ def error_from_response( retry_after: float | None = None, ) -> OpenShockApiError: """Build the most specific exception for a non-2xx response.""" - problem: ProblemDetails | None = None + problem: Problem | None = None text: str | None = None if isinstance(body_json, dict): if "type" in body_json or "title" in body_json: - problem = ProblemDetails.from_dict(body_json, status=status_code) + problem = Problem.from_dict(body_json, status=status_code) text = body_json.get("message") or body_json.get("detail") or body_json.get("title") text = text or body_text or f"HTTP {status_code}" @@ -191,3 +199,58 @@ def error_from_response( else: cls = OpenShockApiError return cls(message, **kwargs) + + +def _is_problem_model(value: Any) -> bool: + """True for the generated problem models (OpenShockProblem, ProblemDetails and their variants).""" + return ( + hasattr(value, "to_dict") and hasattr(value, "title") and hasattr(value, "type_") and hasattr(value, "status") + ) + + +@overload +def unwrap(result: Response[_T | OpenShockProblem | ProblemDetails]) -> _T: ... +@overload +def unwrap(result: Response[_T | OpenShockProblem]) -> _T: ... +@overload +def unwrap(result: Response[_T]) -> _T: ... +@overload +def unwrap(result: _T | OpenShockProblem | ProblemDetails | None) -> _T: ... +def unwrap(result: Any) -> Any: + """ + Narrow the result of a generated API function to its success value. + + The generated functions are typed as returning ``Model | OpenShockProblem | None``, + because the plain generated client hands problems back instead of raising them. + ``unwrap`` removes the non-success cases, raising if it is given one:: + + hubs = unwrap(shocker_list_shockers.sync(client=client)).data + + With :class:`openshock.OpenShockClient` errors are already raised when the response + arrives, so there ``unwrap`` only serves the type checker. It accepts the result of + ``sync()`` / ``asyncio()`` as well as a ``Response`` from the ``*_detailed()`` variants. + """ + # A detailed Response: has the raw status and body. + if hasattr(result, "status_code") and hasattr(result, "content") and hasattr(result, "parsed"): + status = int(result.status_code) + if 200 <= status < 300: + return result.parsed + text = bytes(result.content or b"").decode("utf-8", errors="replace") + try: + body_json = json.loads(text) if text else None + except ValueError: + body_json = None + retry_after = None + with contextlib.suppress(TypeError, ValueError, AttributeError): + retry_after = float(result.headers.get("Retry-After")) + raise error_from_response(status_code=status, body_text=text, body_json=body_json, retry_after=retry_after) + + if _is_problem_model(result): + body = result.to_dict() + status = body.get("status") + raise error_from_response( + status_code=int(status) if isinstance(status, int) else 0, + body_text=json.dumps(body), + body_json=body, + ) + return result diff --git a/openshock/models/__init__.py b/openshock/models/__init__.py deleted file mode 100644 index 12ea682..0000000 --- a/openshock/models/__init__.py +++ /dev/null @@ -1,48 +0,0 @@ -from .account import CreatedToken as CreatedToken -from .account import Token as Token -from .account import User as User -from .common import BasicUserInfo as BasicUserInfo -from .common import ControlType as ControlType -from .common import OtaUpdateStatus as OtaUpdateStatus -from .common import PauseReason as PauseReason -from .common import PermissionType as PermissionType -from .common import RoleType as RoleType -from .common import ShockerModelType as ShockerModelType -from .common import WireEnum as WireEnum -from .common import parse_dt as parse_dt -from .common import parse_uuid as parse_uuid -from .device import Device as Device -from .device import DeviceSelf as DeviceSelf -from .device import DeviceWithShockers as DeviceWithShockers -from .device import DeviceWithToken as DeviceWithToken -from .device import HubGateway as HubGateway -from .device import LcgInfo as LcgInfo -from .device import LcgNode as LcgNode -from .device import LcgNodeV2 as LcgNodeV2 -from .device import OtaUpdate as OtaUpdate -from .meta import BackendInfo as BackendInfo -from .meta import Stats as Stats -from .session import Session as Session -from .share import BulkPauseResult as BulkPauseResult -from .share import OwnPublicShare as OwnPublicShare -from .share import PublicShare as PublicShare -from .share import PublicShareDevice as PublicShareDevice -from .share import PublicShareShocker as PublicShareShocker -from .share import ShareInvite as ShareInvite -from .share import ShareInviteShocker as ShareInviteShocker -from .share import UserShare as UserShare -from .share import UserShareInfo as UserShareInfo -from .share import UserShares as UserShares -from .shocker import Control as Control -from .shocker import ControlLogSender as ControlLogSender -from .shocker import MinimalShocker as MinimalShocker -from .shocker import ShareCode as ShareCode -from .shocker import SharedDevice as SharedDevice -from .shocker import SharedShocker as SharedShocker -from .shocker import ShareInfo as ShareInfo -from .shocker import Shocker as Shocker -from .shocker import ShockerLimits as ShockerLimits -from .shocker import ShockerLog as ShockerLog -from .shocker import ShockerLogWithHub as ShockerLogWithHub -from .shocker import ShockerOwner as ShockerOwner -from .shocker import ShockerPermissions as ShockerPermissions diff --git a/openshock/models/account.py b/openshock/models/account.py deleted file mode 100644 index cca688c..0000000 --- a/openshock/models/account.py +++ /dev/null @@ -1,81 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime -from typing import Any -from uuid import UUID - -from .common import PermissionType, RoleType, parse_dt, require_dt, require_uuid - - -@dataclass -class User: - id: UUID - name: str - email: str - image: str - roles: list[RoleType] - rank: str = "" - has_password: bool | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> User: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - email=data["email"], - image=data["image"], - roles=[RoleType(r) for r in data.get("roles") or []], - rank=data.get("rank") or "", - has_password=data.get("hasPassword"), - ) - - -@dataclass -class Token: - id: UUID - name: str - created_on: datetime - valid_until: datetime | None - last_used: datetime | None - permissions: list[PermissionType] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Token: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - created_on=require_dt(data["createdOn"]), - valid_until=parse_dt(data.get("validUntil")), - last_used=parse_dt(data.get("lastUsed")), - permissions=[PermissionType(p) for p in data.get("permissions") or []], - ) - - -@dataclass -class CreatedToken: - """ - Response of ``account.create_token()``. - - ``token`` is the secret itself. It is only ever returned here, at creation time. - """ - - id: UUID - name: str - token: str - created_on: datetime - valid_until: datetime | None - last_used: datetime | None - permissions: list[PermissionType] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> CreatedToken: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - token=data["token"], - created_on=require_dt(data.get("createdAt") or data["createdOn"]), - valid_until=parse_dt(data.get("validUntil")), - last_used=parse_dt(data.get("lastUsed")), - permissions=[PermissionType(p) for p in data.get("permissions") or []], - ) diff --git a/openshock/models/common.py b/openshock/models/common.py deleted file mode 100644 index 5a7ea53..0000000 --- a/openshock/models/common.py +++ /dev/null @@ -1,186 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime -from enum import Enum, IntFlag -from typing import Any, TypeVar -from uuid import UUID - -_E = TypeVar("_E", bound="WireEnum") - - -def parse_dt(value: str | None) -> datetime | None: - if value is None: - return None - return require_dt(value) - - -def parse_uuid(value: str | None) -> UUID | None: - if value is None: - return None - return UUID(value) - - -def require_dt(value: str) -> datetime: - """Parse a required ISO-8601 datetime string (never None).""" - value = value.replace("Z", "+00:00") - try: - return datetime.fromisoformat(value) - except ValueError: - # Python 3.10 only accepts 0, 3 or 6 fractional digits; .NET emits up to 7. - return datetime.fromisoformat(_normalize_fraction(value)) - - -def _normalize_fraction(value: str) -> str: - head, dot, rest = value.partition(".") - if not dot: - return value - digits = "" - for ch in rest: - if not ch.isdigit(): - break - digits += ch - tz = rest[len(digits) :] - return f"{head}.{digits[:6].ljust(6, '0')}{tz}" - - -def require_uuid(value: str) -> UUID: - """Parse a required UUID string (never None).""" - return UUID(value) - - -class WireEnum(str, Enum): - """ - String enum that mirrors a backend enum. - - - Members compare equal to their wire string (``ControlType.SHOCK == "Shock"``), - so plain strings keep working wherever an enum is accepted. - - Lookup is case-insensitive and also accepts the backend's integer value - (SignalR sends enums as integers, REST sends them as strings). - - Values this SDK version does not know about do not raise: they become a - pseudo-member carrying the raw value, with ``is_known`` set to ``False``. - This keeps older SDK versions working when the backend adds a value. - """ - - @classmethod - def _missing_(cls, value: object) -> WireEnum | None: - members = list(cls) - if isinstance(value, bool): - return None - if isinstance(value, int): - if 0 <= value < len(members): - return members[value] - return cls._unknown(str(value)) - if isinstance(value, str): - lowered = value.lower() - for member in members: - if member.value.lower() == lowered or member.name.lower() == lowered: - return member - if value.isdigit(): - return cls._missing_(int(value)) - return cls._unknown(value) - return None - - @classmethod - def _unknown(cls: type[_E], value: str) -> _E: - obj = str.__new__(cls, value) - obj._name_ = "UNKNOWN" - obj._value_ = value - return obj - - @property - def is_known(self) -> bool: - """False when the backend sent a value this SDK version has no member for.""" - return self._name_ != "UNKNOWN" - - def to_int(self) -> int: - """The backend's integer value for this member (used on the SignalR wire).""" - if not self.is_known: - raise ValueError(f"{type(self).__name__} value {self.value!r} is not known to this SDK version") - return list(type(self)).index(self) - - def __str__(self) -> str: - return str(self.value) - - -class ControlType(WireEnum): - STOP = "Stop" - SHOCK = "Shock" - VIBRATE = "Vibrate" - SOUND = "Sound" - - -class ShockerModelType(WireEnum): - CAIXIANLIN = "CaiXianlin" - PETTRAINER = "PetTrainer" - PETRAINER_998DR = "Petrainer998DR" - WELLTURN_T330 = "WellturnT330" - - -class PermissionType(WireEnum): - """API token permissions.""" - - SHOCKERS_USE = "shockers.use" - SHOCKERS_EDIT = "shockers.edit" - SHOCKERS_PAUSE = "shockers.pause" - DEVICES_EDIT = "devices.edit" - DEVICES_AUTH = "devices.auth" - USERSHARES_EDIT = "usershares.edit" - USERSHARES_PAUSE = "usershares.pause" - PUBLICSHARES_PAUSE = "publicshares.pause" - PUBLICSHARES_EDIT = "publicshares.edit" - - -class RoleType(WireEnum): - SUPPORT = "Support" - STAFF = "Staff" - ADMIN = "Admin" - SYSTEM = "System" - - -class OtaUpdateStatus(WireEnum): - STARTED = "Started" - RUNNING = "Running" - FINISHED = "Finished" - ERROR = "Error" - TIMEOUT = "Timeout" - - -class PauseReason(IntFlag): - """Bitfield for pause reasons. Values can be OR'd together.""" - - NONE = 0 - SHOCKER = 1 - USER_SHARE = 2 - PUBLIC_SHARE = 4 - - -def parse_pause_reason(value: Any) -> PauseReason: - """Parse a pause reason sent as an integer bitfield or as comma-separated flag names.""" - if value is None: - return PauseReason.NONE - if isinstance(value, int): - return PauseReason(value) - text = str(value).strip() - if text.lstrip("-").isdigit(): - return PauseReason(int(text)) - names = {"none": 0, "shocker": 1, "usershare": 2, "publicshare": 4} - result = PauseReason.NONE - for part in text.split(","): - result |= PauseReason(names.get(part.strip().lower().replace("_", ""), 0)) - return result - - -@dataclass -class BasicUserInfo: - id: UUID - name: str - image: str - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> BasicUserInfo: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - image=data["image"], - ) diff --git a/openshock/models/device.py b/openshock/models/device.py deleted file mode 100644 index 169b9c7..0000000 --- a/openshock/models/device.py +++ /dev/null @@ -1,179 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime -from typing import Any -from uuid import UUID - -from .common import OtaUpdateStatus, require_dt, require_uuid -from .shocker import MinimalShocker, Shocker - - -@dataclass -class Device: - id: UUID - name: str - created_on: datetime - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Device: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - created_on=require_dt(data["createdOn"]), - ) - - -@dataclass -class DeviceWithShockers(Device): - """A hub together with its shockers, as returned by ``shockers.list_own()``.""" - - shockers: list[Shocker] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> DeviceWithShockers: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - created_on=require_dt(data["createdOn"]), - shockers=[Shocker.from_dict(s) for s in data.get("shockers") or []], - ) - - -@dataclass -class DeviceWithToken(Device): - """ - A hub as returned by ``devices.get()``. - - ``token`` is the hub's device token. It is only present when authenticated with a - user session or an API token holding the ``devices.auth`` permission. - """ - - token: str | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> DeviceWithToken: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - created_on=require_dt(data["createdOn"]), - token=data.get("token"), - ) - - -@dataclass -class LcgNode: - """V1 LCG assignment response.""" - - fqdn: str - country: str - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> LcgNode: - return cls( - fqdn=data["fqdn"], - country=data["country"], - ) - - -@dataclass -class LcgNodeV2: - """V2 LCG assignment response.""" - - host: str - port: int - path: str - country: str - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> LcgNodeV2: - return cls( - host=data["host"], - port=data["port"], - path=data["path"], - country=data["country"], - ) - - -@dataclass -class LcgInfo: - """LCG connection info for a specific device.""" - - gateway: str - country: str - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> LcgInfo: - return cls( - gateway=data["gateway"], - country=data["country"], - ) - - -@dataclass -class HubGateway: - """ - The live control gateway a hub is currently connected to (GET /2/devices/{id}/lcg). - """ - - host: str - port: int - #: Path prefix the gateway is served under, e.g. "/gateway" (empty for root). - path_prefix: str - country: str - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> HubGateway: - return cls( - host=data["host"], - port=int(data.get("port") or 443), - path_prefix=data.get("pathPrefix") or "", - country=data.get("country") or "", - ) - - @property - def display_url(self) -> str: - port = "" if self.port == 443 else f":{self.port}" - prefix = self.path_prefix.strip("/") - return f"{self.host}{port}{'/' + prefix if prefix else ''}" - - @property - def ws_url(self) -> str: - """Base WebSocket URL of the gateway, without a trailing slash.""" - return f"wss://{self.display_url}" - - -@dataclass -class OtaUpdate: - id: int - started_at: datetime - status: OtaUpdateStatus - version: str - message: str | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> OtaUpdate: - return cls( - id=data["id"], - started_at=require_dt(data["startedAt"]), - status=OtaUpdateStatus(data["status"]), - version=data["version"], - message=data.get("message"), - ) - - -@dataclass -class DeviceSelf: - """Response from GET /1/device/self (hub endpoint).""" - - id: UUID - name: str - shockers: list[MinimalShocker] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> DeviceSelf: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - shockers=[MinimalShocker.from_dict(s) for s in data.get("shockers") or []], - ) diff --git a/openshock/models/meta.py b/openshock/models/meta.py deleted file mode 100644 index c34b721..0000000 --- a/openshock/models/meta.py +++ /dev/null @@ -1,79 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime -from typing import Any - -from .common import require_dt - - -@dataclass -class BackendInfo: - """ - Represents the backend info returned from GET /1 (after unwrapping legacy). - - Example payload (inner `data` object): - - { - "version": "1.2.3", - "commit": "abcdef", - "currentTime": "2024-06-01T12:34:56Z", - "frontendUrl": "https://openshock.app", - "shortLinkUrl": "https://os.link", - "turnstileSiteKey": "xxx", - "isUserAuthenticated": true, - "oAuthProviders": ["discord", "github"], - "docsUrl": "https://docs.openshock.app" - } - """ - - version: str - commit: str - current_time: datetime - frontend_url: str - short_link_url: str - turnstile_site_key: str - is_user_authenticated: bool - o_auth_providers: list[str] - docs_url: str | None = None - - @classmethod - def from_any(cls, data: Any) -> BackendInfo: - if not isinstance(data, dict): - raise TypeError(f"BackendInfo.from_any expected dict, got {type(data)!r}") - - return cls( - version=data["version"], - commit=data["commit"], - current_time=require_dt(data["currentTime"]), - frontend_url=data["frontendUrl"], - short_link_url=data["shortLinkUrl"], - turnstile_site_key=data["turnstileSiteKey"], - is_user_authenticated=bool(data["isUserAuthenticated"]), - o_auth_providers=list(data.get("oAuthProviders", [])), - docs_url=data.get("docsUrl"), - ) - - -@dataclass -class Stats: - """ - Represents the stats returned from GET /1/public/stats (after unwrapping). - - Example payload (inner `data` object): - - { - "devicesOnline": 42 - } - """ - - devices_online: int - - @classmethod - def from_any(cls, data: Any) -> Stats: - if not isinstance(data, dict): - raise TypeError(f"Stats.from_any expected dict, got {type(data)!r}") - - return cls( - devices_online=int(data["devicesOnline"]), - ) diff --git a/openshock/models/session.py b/openshock/models/session.py deleted file mode 100644 index ec6cfde..0000000 --- a/openshock/models/session.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime -from typing import Any -from uuid import UUID - -from .common import parse_dt, require_dt, require_uuid - - -@dataclass -class Session: - id: UUID - ip: str - user_agent: str - created: datetime - expires: datetime - last_used: datetime | None = None - asn_org: str | None = None - is_vpn: bool | None = None - country_code: str | None = None - city: str | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Session: - return cls( - id=require_uuid(data["id"]), - ip=data["ip"], - user_agent=data["userAgent"], - created=require_dt(data["created"]), - expires=require_dt(data["expires"]), - last_used=parse_dt(data.get("lastUsed")), - asn_org=data.get("asnOrg"), - is_vpn=data.get("isVpn"), - country_code=data.get("countryCode"), - city=data.get("city"), - ) diff --git a/openshock/models/share.py b/openshock/models/share.py deleted file mode 100644 index b002702..0000000 --- a/openshock/models/share.py +++ /dev/null @@ -1,199 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime -from typing import Any -from uuid import UUID - -from .common import BasicUserInfo, PauseReason, parse_dt, parse_pause_reason, parse_uuid, require_dt, require_uuid -from .shocker import ShockerLimits, ShockerPermissions - - -@dataclass -class PublicShareShocker: - id: UUID - name: str - permissions: ShockerPermissions - limits: ShockerLimits - paused: PauseReason - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> PublicShareShocker: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - permissions=ShockerPermissions.from_dict(data["permissions"]), - limits=ShockerLimits.from_dict(data["limits"]), - paused=parse_pause_reason(data.get("paused")), - ) - - -@dataclass -class PublicShareDevice: - id: UUID - name: str - shockers: list[PublicShareShocker] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> PublicShareDevice: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - shockers=[PublicShareShocker.from_dict(s) for s in data.get("shockers", [])], - ) - - -@dataclass -class PublicShare: - id: UUID - name: str - created_on: datetime - expires_on: datetime | None - author: BasicUserInfo - devices: list[PublicShareDevice] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> PublicShare: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - created_on=require_dt(data["createdOn"]), - expires_on=parse_dt(data.get("expiresOn")), - author=BasicUserInfo.from_dict(data["author"]), - devices=[PublicShareDevice.from_dict(d) for d in data.get("devices", [])], - ) - - -@dataclass -class OwnPublicShare: - """Response from GET /1/shares/links (listing own shares).""" - - id: UUID - name: str - created_on: datetime - expires_on: datetime | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> OwnPublicShare: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - created_on=require_dt(data["createdOn"]), - expires_on=parse_dt(data.get("expiresOn")), - ) - - -@dataclass -class UserShareInfo: - id: UUID - name: str - created_on: datetime - permissions: ShockerPermissions - limits: ShockerLimits - paused: PauseReason - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> UserShareInfo: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - created_on=require_dt(data["createdOn"]), - permissions=ShockerPermissions.from_dict(data["permissions"]), - limits=ShockerLimits.from_dict(data["limits"]), - paused=parse_pause_reason(data.get("paused")), - ) - - -@dataclass -class UserShare: - """A user and their shared shockers.""" - - id: UUID - name: str - image: str - shares: list[UserShareInfo] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> UserShare: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - image=data["image"], - shares=[UserShareInfo.from_dict(s) for s in data.get("shares", [])], - ) - - -@dataclass -class UserShares: - """Response from GET /2/shares/user.""" - - outgoing: list[UserShare] - incoming: list[UserShare] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> UserShares: - return cls( - outgoing=[UserShare.from_dict(s) for s in data.get("outgoing", [])], - incoming=[UserShare.from_dict(s) for s in data.get("incoming", [])], - ) - - -@dataclass -class ShareInviteShocker: - permissions: ShockerPermissions - limits: ShockerLimits - id: UUID | None = None - name: str | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShareInviteShocker: - return cls( - permissions=ShockerPermissions.from_dict(data["permissions"]), - limits=ShockerLimits.from_dict(data["limits"]), - id=parse_uuid(data.get("id")), - name=data.get("name"), - ) - - def to_dict(self) -> dict[str, Any]: - d: dict[str, Any] = { - "permissions": self.permissions.to_dict(), - "limits": self.limits.to_dict(), - } - if self.id is not None: - d["id"] = str(self.id) - return d - - -@dataclass -class ShareInvite: - id: UUID - created_at: datetime - owner: BasicUserInfo - shared_with: BasicUserInfo - shockers: list[ShareInviteShocker] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShareInvite: - return cls( - id=require_uuid(data["id"]), - created_at=require_dt(data["createdAt"]), - owner=BasicUserInfo.from_dict(data["owner"]), - shared_with=BasicUserInfo.from_dict(data["sharedWith"]), - shockers=[ShareInviteShocker.from_dict(s) for s in data.get("shockers", [])], - ) - - -@dataclass -class BulkPauseResult: - """Response of ``user_shares.bulk_pause_shockers()``.""" - - affected_records: int - #: Resulting pause reasons per shocker ID. - pause_states: dict[UUID, PauseReason] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> BulkPauseResult: - return cls( - affected_records=int(data.get("affectedRecords", 0)), - pause_states={require_uuid(k): parse_pause_reason(v) for k, v in (data.get("pauseStates") or {}).items()}, - ) diff --git a/openshock/models/shocker.py b/openshock/models/shocker.py deleted file mode 100644 index 1e2f678..0000000 --- a/openshock/models/shocker.py +++ /dev/null @@ -1,287 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from datetime import datetime -from typing import Any -from uuid import UUID - -from .common import BasicUserInfo, ControlType, ShockerModelType, require_dt, require_uuid - - -@dataclass -class ShockerPermissions: - vibrate: bool - sound: bool - shock: bool - live: bool = False - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShockerPermissions: - return cls( - vibrate=data["vibrate"], - sound=data["sound"], - shock=data["shock"], - live=data.get("live", False), - ) - - def to_dict(self) -> dict[str, Any]: - return { - "vibrate": self.vibrate, - "sound": self.sound, - "shock": self.shock, - "live": self.live, - } - - -@dataclass -class ShockerLimits: - intensity: int | None = None - duration: int | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShockerLimits: - return cls( - intensity=data.get("intensity"), - duration=data.get("duration"), - ) - - def to_dict(self) -> dict[str, Any]: - return { - "intensity": self.intensity, - "duration": self.duration, - } - - -@dataclass -class Shocker: - id: UUID - name: str - rf_id: int - model: ShockerModelType - created_on: datetime - is_paused: bool = False - permissions: ShockerPermissions | None = None - limits: ShockerLimits | None = None - #: ID of the hub this shocker belongs to. Only set by ``shockers.get()``. - device: UUID | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Shocker: - permissions = data.get("permissions") - limits = data.get("limits") - device = data.get("device") - return cls( - id=require_uuid(data["id"]), - name=data["name"], - rf_id=data["rfId"], - model=ShockerModelType(data["model"]), - created_on=require_dt(data["createdOn"]), - is_paused=data.get("isPaused", False), - permissions=ShockerPermissions.from_dict(permissions) if permissions else None, - limits=ShockerLimits.from_dict(limits) if limits else None, - device=require_uuid(device) if device else None, - ) - - -@dataclass -class MinimalShocker: - id: UUID - rf_id: int - model: ShockerModelType - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> MinimalShocker: - return cls( - id=require_uuid(data["id"]), - rf_id=data["rfId"], - model=ShockerModelType(data["model"]), - ) - - -@dataclass -class SharedShocker: - """A shocker somebody else shared with you.""" - - id: UUID - name: str - is_paused: bool - permissions: ShockerPermissions - limits: ShockerLimits - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> SharedShocker: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - is_paused=data.get("isPaused", False), - permissions=ShockerPermissions.from_dict(data["permissions"]), - limits=ShockerLimits.from_dict(data["limits"]), - ) - - -@dataclass -class SharedDevice: - """A hub of another user, holding the shockers they shared with you.""" - - id: UUID - name: str - shockers: list[SharedShocker] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> SharedDevice: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - shockers=[SharedShocker.from_dict(s) for s in data.get("shockers") or []], - ) - - -@dataclass -class ShockerOwner: - """An entry of ``shockers.list_shared()``: a user and what they shared with you.""" - - id: UUID - name: str - image: str - devices: list[SharedDevice] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShockerOwner: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - image=data["image"], - devices=[SharedDevice.from_dict(d) for d in data.get("devices") or []], - ) - - -@dataclass -class ControlLogSender: - id: UUID - name: str - image: str - custom_name: str | None = None - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ControlLogSender: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - image=data["image"], - custom_name=data.get("customName"), - ) - - -@dataclass -class ShockerLog: - id: UUID - created_on: datetime - type: ControlType - controlled_by: ControlLogSender - intensity: int - duration: int - live_control: bool = False - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShockerLog: - return cls( - id=require_uuid(data["id"]), - created_on=require_dt(data["createdOn"]), - type=ControlType(data["type"]), - controlled_by=ControlLogSender.from_dict(data["controlledBy"]), - intensity=data["intensity"], - duration=data["duration"], - live_control=data.get("liveControl", False), - ) - - -@dataclass -class ShockerLogWithHub(ShockerLog): - """A log entry of ``shockers.all_logs()``, which spans every owned shocker.""" - - hub_id: UUID | None = None - hub_name: str = "" - shocker_id: UUID | None = None - shocker_name: str = "" - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShockerLogWithHub: - hub_id = data.get("hubId") - shocker_id = data.get("shockerId") - return cls( - id=require_uuid(data["id"]), - created_on=require_dt(data["createdOn"]), - type=ControlType(data["type"]), - controlled_by=ControlLogSender.from_dict(data["controlledBy"]), - intensity=data["intensity"], - duration=data["duration"], - live_control=data.get("liveControl", False), - hub_id=require_uuid(hub_id) if hub_id else None, - hub_name=data.get("hubName") or "", - shocker_id=require_uuid(shocker_id) if shocker_id else None, - shocker_name=data.get("shockerName") or "", - ) - - -@dataclass -class Control: - """ - A single control command. - - ``intensity`` is 0-100, ``duration`` is in milliseconds. ``exclusive`` makes this - command take precedence over live control for its duration. - """ - - id: str | UUID - type: ControlType | str - intensity: int - duration: int - exclusive: bool = False - - def to_dict(self) -> dict[str, Any]: - """REST wire form (control type as string).""" - return { - "id": str(self.id), - "type": ControlType(self.type).value, - "intensity": self.intensity, - "duration": self.duration, - "exclusive": self.exclusive, - } - - def to_signalr(self) -> dict[str, Any]: - """SignalR wire form (control type as integer).""" - d = self.to_dict() - d["type"] = ControlType(self.type).to_int() - return d - - -@dataclass -class ShareInfo: - shared_with: BasicUserInfo - created_on: datetime - permissions: ShockerPermissions - limits: ShockerLimits - paused: bool - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShareInfo: - return cls( - shared_with=BasicUserInfo.from_dict(data["sharedWith"]), - created_on=require_dt(data["createdOn"]), - permissions=ShockerPermissions.from_dict(data["permissions"]), - limits=ShockerLimits.from_dict(data["limits"]), - paused=data.get("paused", False), - ) - - -@dataclass -class ShareCode: - id: UUID - created_on: datetime - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShareCode: - return cls( - id=require_uuid(data["id"]), - created_on=require_dt(data["createdOn"]), - ) diff --git a/openshock/realtime/__init__.py b/openshock/realtime/__init__.py index 6630b91..a4fa1d8 100644 --- a/openshock/realtime/__init__.py +++ b/openshock/realtime/__init__.py @@ -20,6 +20,7 @@ from ._transport import StepRetryPolicy as StepRetryPolicy from .live_control import LiveControlClient as LiveControlClient from .live_control import LiveControlRetryPolicy as LiveControlRetryPolicy +from .live_control import gateway_ws_url as gateway_ws_url from .models import BasicShockerInfo as BasicShockerInfo from .models import ControlLog as ControlLog from .models import HubControlLogSender as HubControlLogSender diff --git a/openshock/realtime/_transport.py b/openshock/realtime/_transport.py index a4f811e..035f84c 100644 --- a/openshock/realtime/_transport.py +++ b/openshock/realtime/_transport.py @@ -7,12 +7,11 @@ import json import logging from collections.abc import Awaitable, Callable, Mapping, Sequence -from enum import Enum -from importlib.metadata import version as _package_version +from enum import StrEnum from types import TracebackType from typing import Any, Protocol, TypeVar -import httpx +import httpx2 from websockets.asyncio.client import ClientConnection, connect from websockets.exceptions import ConnectionClosed, InvalidMessage, InvalidStatus @@ -28,10 +27,8 @@ _SelfT = TypeVar("_SelfT", bound="WebSocketSession") -WEBSOCKETS_VERSION: str = _package_version("websockets") - -class ConnectionState(str, Enum): +class ConnectionState(StrEnum): DISCONNECTED = "Disconnected" CONNECTING = "Connecting" CONNECTED = "Connected" @@ -97,9 +94,9 @@ async def _probe_rejection(url: str, headers: Mapping[str, str], user_agent: str """ http_url = "http" + url[2:] if url.startswith(("ws://", "wss://")) else url try: - async with httpx.AsyncClient(timeout=10) as client: + async with httpx2.AsyncClient(timeout=10) as client: resp = await client.get(http_url, headers={**headers, "User-Agent": user_agent}) - except httpx.HTTPError: + except httpx2.HTTPError: return None error = _rejection(resp.status_code, resp.text, url) if resp.status_code in (401, 403) or type(error) not in (OpenShockApiError, OpenShockNotFound): @@ -218,7 +215,7 @@ async def wait_connected(self, timeout: float | None = None) -> None: if self._connected.is_set(): return if not done: - raise asyncio.TimeoutError() + raise TimeoutError() raise self._close_error or OpenShockConnectionError("The connection was closed") async def wait_closed(self) -> None: diff --git a/openshock/realtime/_wire.py b/openshock/realtime/_wire.py new file mode 100644 index 0000000..aafb728 --- /dev/null +++ b/openshock/realtime/_wire.py @@ -0,0 +1,81 @@ +"""Parsing helpers for values on the realtime wires.""" + +from __future__ import annotations + +from datetime import datetime +from enum import StrEnum +from typing import Any, Self +from uuid import UUID + +from ..rest.models import ControlType + +#: SignalR sends ``ControlType`` as the backend's integer value, REST and live control as its name. +CONTROL_TYPE_VALUES: dict[ControlType, int] = { + ControlType.STOP: 0, + ControlType.SHOCK: 1, + ControlType.VIBRATE: 2, + ControlType.SOUND: 3, +} +_CONTROL_TYPE_BY_VALUE = {v: k for k, v in CONTROL_TYPE_VALUES.items()} + + +def require_dt(value: str) -> datetime: + return datetime.fromisoformat(value) + + +def require_uuid(value: str) -> UUID: + return UUID(value) + + +def parse_control_type(value: Any) -> ControlType | str: + """Accept the integer or name form. Unknown values are returned as a string, never raised.""" + if isinstance(value, int) and not isinstance(value, bool): + return _CONTROL_TYPE_BY_VALUE.get(value, str(value)) + text = str(value) + for member in ControlType: + if member.value.lower() == text.lower(): + return member + return text + + +def control_type(value: ControlType | str) -> ControlType: + """Coerce user input (``ControlType.SHOCK``, ``"Shock"``, ``"shock"``) to the enum.""" + parsed = parse_control_type(value) + if not isinstance(parsed, ControlType): + raise ValueError(f"Unknown control type {value!r}") + return parsed + + +class WireEnum(StrEnum): + """ + String enum for values SignalR sends as integers. + + Lookup accepts the integer (position in declaration order), or the name in any casing. + Values this SDK version does not know become a pseudo-member with ``is_known`` False + instead of raising, so a backend addition does not break event delivery. + """ + + @classmethod + def _missing_(cls, value: object) -> Self | None: + members = list(cls) + if isinstance(value, bool): + return None + if isinstance(value, int): + return members[value] if 0 <= value < len(members) else cls._unknown(str(value)) + if isinstance(value, str): + for member in members: + if member.value.lower() == value.lower(): + return member + return cls._unknown(value) + return None + + @classmethod + def _unknown(cls, value: str) -> Self: + obj = str.__new__(cls, value) + obj._name_ = "UNKNOWN" + obj._value_ = value + return obj + + @property + def is_known(self) -> bool: + return self._name_ != "UNKNOWN" diff --git a/openshock/realtime/live_control.py b/openshock/realtime/live_control.py index 5eb321f..a52242b 100644 --- a/openshock/realtime/live_control.py +++ b/openshock/realtime/live_control.py @@ -10,12 +10,14 @@ from websockets.asyncio.client import ClientConnection -from .._async.client import AsyncOpenShockClient from .._core import DEFAULT_BASE_URL, build_user_agent -from ..auth import ApiTokenAuth -from ..models import ControlType, HubGateway +from ..client import OpenShockClient +from ..exceptions import unwrap +from ..rest.api.hub_management import devices_get_live_control_gateway_info_v2 +from ..rest.models import ControlType, LcgResponseV2 from ._events import Event -from ._transport import WEBSOCKETS_VERSION, RetryPolicy, WebSocketSession +from ._transport import RetryPolicy, WebSocketSession +from ._wire import control_type as _control_type from .models import LiveResponseType, _get #: Ticks per second assumed until the gateway announces the real value. @@ -23,7 +25,14 @@ #: A frame given to ``intake_frame`` stays active for this many ticks. FRAME_HOLD_TICKS = 2.5 -GatewayResolver = Callable[[], Awaitable["HubGateway | str"]] +GatewayResolver = Callable[[], Awaitable["LcgResponseV2 | str"]] + + +def gateway_ws_url(gateway: LcgResponseV2) -> str: + """Base WebSocket URL of a gateway, without a trailing slash.""" + port = "" if gateway.port == 443 else f":{gateway.port}" + prefix = gateway.path_prefix.strip("/") + return f"wss://{gateway.host}{port}{'/' + prefix if prefix else ''}" class LiveControlRetryPolicy: @@ -78,9 +87,9 @@ def __init__( hub_id: str | UUID, *, api_token: str | None = None, - client: AsyncOpenShockClient | None = None, + client: OpenShockClient | None = None, base_url: str = DEFAULT_BASE_URL, - gateway: HubGateway | str | None = None, + gateway: LcgResponseV2 | str | None = None, gateway_resolver: GatewayResolver | None = None, tps: int | None = None, app_name: str | None = None, @@ -105,12 +114,12 @@ def __init__( self._headers = dict(headers or {}) self._owns_client = False self._api_options: dict[str, Any] = {} - self._api: AsyncOpenShockClient | None = client + self._api: OpenShockClient | None = client if client is not None: - self._headers = {**client.auth.headers(), **self._headers} + self._headers = {**client.auth_headers, **self._headers} elif api_token is not None: - self._headers = {**ApiTokenAuth(api_token).headers(), **self._headers} + self._headers = {"OpenShockToken": api_token, **self._headers} if gateway is None and gateway_resolver is None: # Created on first use and closed again in stop(), so the client can be restarted. self._owns_client = True @@ -132,10 +141,10 @@ def __init__( component="Live", app_name=app_name, app_version=app_version, - libraries={"websockets": WEBSOCKETS_VERSION}, + libraries=("websockets",), ) - self._gateway: HubGateway | str | None = gateway + self._gateway: LcgResponseV2 | str | None = gateway self._tps = 0 self._latency_ms: int | None = None self._hub_latency_ms: int | None = None @@ -158,7 +167,7 @@ def __init__( # --- state ------------------------------------------------------------- @property - def gateway(self) -> HubGateway | str | None: + def gateway(self) -> LcgResponseV2 | str | None: """The gateway currently (or last) connected to.""" return self._gateway @@ -202,9 +211,7 @@ def intake_frame( """ if not 0 <= intensity <= 100: raise ValueError("intensity must be between 0 and 100") - control_type = ControlType(type) - if not control_type.is_known: - raise ValueError(f"Unknown control type {type!r}") + control_type = _control_type(type) window = hold_for if hold_for is not None else FRAME_HOLD_TICKS / (self._tps or DEFAULT_TPS) self._states[UUID(str(shocker))] = _ShockerState( type=control_type, @@ -227,7 +234,7 @@ async def send_frame(self, shocker: str | UUID, type: ControlType | str, intensi """ if not 0 <= intensity <= 100: raise ValueError("intensity must be between 0 and 100") - await self._send("Frame", self._frame(UUID(str(shocker)), ControlType(type), intensity)) + await self._send("Frame", self._frame(UUID(str(shocker)), _control_type(type), intensity)) # --- session hooks ----------------------------------------------------- @@ -245,10 +252,10 @@ async def stop(self) -> None: async def _close_owned_client(self) -> None: if self._owns_client and self._api is not None: api, self._api = self._api, None - await api.aclose() + await api.get_async_httpx_client().aclose() - def _url_for(self, gateway: HubGateway | str) -> str: - base = gateway.ws_url if isinstance(gateway, HubGateway) else gateway.rstrip("/") + def _url_for(self, gateway: LcgResponseV2 | str) -> str: + base = gateway_ws_url(gateway) if isinstance(gateway, LcgResponseV2) else gateway.rstrip("/") if "://" not in base: base = f"wss://{base}" url = f"{base}/1/ws/live/{self.hub_id}" @@ -256,14 +263,16 @@ def _url_for(self, gateway: HubGateway | str) -> str: url += f"?tps={self._requested_tps}" return url - async def _resolve_gateway(self) -> HubGateway | str: + async def _resolve_gateway(self) -> LcgResponseV2 | str: if self._fixed_gateway is not None: return self._fixed_gateway if self._gateway_resolver is not None: return await self._gateway_resolver() if self._api is None: - self._api = AsyncOpenShockClient(**self._api_options) - return await self._api.devices.gateway(self.hub_id) + self._api = OpenShockClient(**self._api_options) + # unwrap() raises HubOffline / HubNotFound / OpenShockAuthError from the response. + response = await devices_get_live_control_gateway_info_v2.asyncio_detailed(self.hub_id, client=self._api) + return unwrap(response) async def _open(self) -> ClientConnection: gateway = await self._resolve_gateway() diff --git a/openshock/realtime/models.py b/openshock/realtime/models.py index b7b8c46..c633193 100644 --- a/openshock/realtime/models.py +++ b/openshock/realtime/models.py @@ -6,7 +6,8 @@ from typing import Any from uuid import UUID -from ..models.common import ControlType, WireEnum, require_dt, require_uuid +from ..rest.models import ControlType +from ._wire import WireEnum, parse_control_type, require_dt, require_uuid def _get(data: dict[str, Any], key: str, default: Any = None) -> Any: @@ -98,7 +99,8 @@ class ControlLog: """One executed command of a live log event.""" shocker: BasicShockerInfo - type: ControlType + #: A ``ControlType``, or the raw value as a string if this SDK version does not know it. + type: ControlType | str intensity: int duration: int executed_at: datetime @@ -108,7 +110,7 @@ class ControlLog: def from_dict(cls, data: dict[str, Any]) -> ControlLog: return cls( shocker=BasicShockerInfo.from_dict(_get(data, "shocker")), - type=ControlType(_get(data, "type")), + type=parse_control_type(_get(data, "type")), intensity=int(_get(data, "intensity", 0)), duration=int(_get(data, "duration", 0)), executed_at=require_dt(_get(data, "executedAt")), diff --git a/openshock/realtime/user_hub.py b/openshock/realtime/user_hub.py index 867b0c6..f351f2b 100644 --- a/openshock/realtime/user_hub.py +++ b/openshock/realtime/user_hub.py @@ -6,11 +6,11 @@ from uuid import UUID from .._core import DEFAULT_BASE_URL, build_user_agent -from ..models import Control -from ..models.common import require_uuid +from ..rest.models import Control from ._events import Event from ._signalr import SignalRConnection -from ._transport import WEBSOCKETS_VERSION, RetryPolicy, StepRetryPolicy +from ._transport import RetryPolicy, StepRetryPolicy +from ._wire import CONTROL_TYPE_VALUES, require_uuid from .models import ControlLog, HubControlLogSender, HubOnlineState, HubUpdateType, OtaUpdateProgressTask #: Reconnect immediately, then after 2s, 10s, and every 30s from there on. @@ -26,6 +26,14 @@ def _ws_url(base_url: str, path: str) -> str: return base + path +def _signalr_control(control: Control) -> dict[str, Any]: + """SignalR wire form of a control command: the control type goes out as an integer.""" + data = control.to_dict() + data["type"] = CONTROL_TYPE_VALUES[control.type_] + data.setdefault("exclusive", False) + return data + + class UserHubClient(SignalRConnection): """ Realtime connection to the OpenShock user hub (SignalR, ``/1/hubs/user``). @@ -41,7 +49,7 @@ async def on_log(sender, logs): for log in logs: print(sender.name, log.type, log.intensity, log.shocker.name) - await hub.control([Control(id=shocker_id, type=ControlType.VIBRATE, intensity=30, duration=1000)]) + await hub.control([Control(id=shocker_id, type_=ControlType.VIBRATE, intensity=30, duration=1000)]) await hub.wait_closed() The connection reconnects by itself (see ``retry_policy``). A rejected or revoked @@ -78,7 +86,7 @@ def __init__( component="Hub", app_name=app_name, app_version=app_version, - libraries={"websockets": WEBSOCKETS_VERSION}, + libraries=("websockets",), ), retry_policy=retry_policy or USER_HUB_RETRY_POLICY, logger=logger, @@ -138,13 +146,13 @@ async def control( Unlike the REST endpoint this does not report per-shocker rejections: commands the server refuses (unknown shocker, paused, no permission) are dropped silently. - Use ``client.shockers.control()`` when you need that feedback. + Use the REST endpoint (``openshock.rest.api.shockers.shocker_send_control``) when you need that feedback. """ if isinstance(controls, Control): controls = [controls] if not controls: raise ValueError("controls must be a non-empty sequence") - shocks = [c.to_signalr() if isinstance(c, Control) else c for c in controls] + shocks = [_signalr_control(c) if isinstance(c, Control) else c for c in controls] await self.invoke("ControlV2", shocks, custom_name) async def set_captive_portal(self, hub_id: str | UUID, enabled: bool) -> None: diff --git a/openshock/resources/__init__.py b/openshock/resources/__init__.py deleted file mode 100644 index 97cbf7a..0000000 --- a/openshock/resources/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Resource classes behind ``client.``. Exposed for type annotations.""" - -from .._async.resources.account import AsyncAccountResource as AsyncAccountResource -from .._async.resources.devices import AsyncDevicesResource as AsyncDevicesResource -from .._async.resources.hub import AsyncHubResource as AsyncHubResource -from .._async.resources.meta import AsyncMetaResource as AsyncMetaResource -from .._async.resources.sessions import AsyncSessionsResource as AsyncSessionsResource -from .._async.resources.shares import AsyncSharesResource as AsyncSharesResource -from .._async.resources.shockers import AsyncShockersResource as AsyncShockersResource -from .._async.resources.user_shares import AsyncUserSharesResource as AsyncUserSharesResource -from .._sync.resources.account import AccountResource as AccountResource -from .._sync.resources.devices import DevicesResource as DevicesResource -from .._sync.resources.hub import HubResource as HubResource -from .._sync.resources.meta import MetaResource as MetaResource -from .._sync.resources.sessions import SessionsResource as SessionsResource -from .._sync.resources.shares import SharesResource as SharesResource -from .._sync.resources.shockers import ShockersResource as ShockersResource -from .._sync.resources.user_shares import UserSharesResource as UserSharesResource diff --git a/openshock/rest/__init__.py b/openshock/rest/__init__.py new file mode 100644 index 0000000..0dbc2df --- /dev/null +++ b/openshock/rest/__init__.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""A client library for accessing OpenShock.API""" + +from .client import AuthenticatedClient, Client + +__all__ = ( + "AuthenticatedClient", + "Client", +) diff --git a/openshock/rest/api/__init__.py b/openshock/rest/api/__init__.py new file mode 100644 index 0000000..c76d857 --- /dev/null +++ b/openshock/rest/api/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains methods for accessing the API""" diff --git a/openshock/rest/api/account/__init__.py b/openshock/rest/api/account/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/account/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/account/account_activate.py b/openshock/rest/api/account/account_activate.py new file mode 100644 index 0000000..d6f015f --- /dev/null +++ b/openshock/rest/api/account/account_activate.py @@ -0,0 +1,165 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + token: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["token"] = token + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/activate", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Response[Any | OpenShockProblem]: + """Activate account + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token=token, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Any | OpenShockProblem | None: + """Activate account + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + token=token, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Response[Any | OpenShockProblem]: + """Activate account + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token=token, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Any | OpenShockProblem | None: + """Activate account + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + token=token, + ) + ).parsed diff --git a/openshock/rest/api/account/account_check_username.py b/openshock/rest/api/account/account_check_username.py new file mode 100644 index 0000000..b40e546 --- /dev/null +++ b/openshock/rest/api/account/account_check_username.py @@ -0,0 +1,159 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.change_username_request import ChangeUsernameRequest +from ...models.username_check_response import UsernameCheckResponse +from ...types import Response + + +def _get_kwargs( + *, + body: ChangeUsernameRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/username/check", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> UsernameCheckResponse | None: + if response.status_code == 200: + response_200 = UsernameCheckResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[UsernameCheckResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + body: ChangeUsernameRequest, +) -> Response[UsernameCheckResponse]: + """Check if a username is available + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[UsernameCheckResponse] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + body: ChangeUsernameRequest, +) -> UsernameCheckResponse | None: + """Check if a username is available + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + UsernameCheckResponse + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: ChangeUsernameRequest, +) -> Response[UsernameCheckResponse]: + """Check if a username is available + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[UsernameCheckResponse] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + body: ChangeUsernameRequest, +) -> UsernameCheckResponse | None: + """Check if a username is available + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + UsernameCheckResponse + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/account_email_verify.py b/openshock/rest/api/account/account_email_verify.py new file mode 100644 index 0000000..d2c68ab --- /dev/null +++ b/openshock/rest/api/account/account_email_verify.py @@ -0,0 +1,170 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + token: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["token"] = token + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/email-change/verify", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Response[Any | OpenShockProblem]: + """Verify a pending email change using the token from the verification email. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token=token, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Any | OpenShockProblem | None: + """Verify a pending email change using the token from the verification email. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + token=token, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Response[Any | OpenShockProblem]: + """Verify a pending email change using the token from the verification email. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token=token, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Any | OpenShockProblem | None: + """Verify a pending email change using the token from the verification email. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + token=token, + ) + ).parsed diff --git a/openshock/rest/api/account/account_email_verify_legacy.py b/openshock/rest/api/account/account_email_verify_legacy.py new file mode 100644 index 0000000..a74c0d2 --- /dev/null +++ b/openshock/rest/api/account/account_email_verify_legacy.py @@ -0,0 +1,170 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + token: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["token"] = token + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/verify-email", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Response[Any | OpenShockProblem]: + """Verify a pending email change. Deprecated: use POST /email-change/verify instead. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token=token, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Any | OpenShockProblem | None: + """Verify a pending email change. Deprecated: use POST /email-change/verify instead. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + token=token, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Response[Any | OpenShockProblem]: + """Verify a pending email change. Deprecated: use POST /email-change/verify instead. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token=token, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + token: str | Unset = UNSET, +) -> Any | OpenShockProblem | None: + """Verify a pending email change. Deprecated: use POST /email-change/verify instead. + + Args: + token (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + token=token, + ) + ).parsed diff --git a/openshock/rest/api/account/account_login_v2.py b/openshock/rest/api/account/account_login_v2.py new file mode 100644 index 0000000..c98fee0 --- /dev/null +++ b/openshock/rest/api/account/account_login_v2.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.login_v2 import LoginV2 +from ...models.login_v2_ok_response import LoginV2OkResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: LoginV2, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/account/login", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LoginV2OkResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LoginV2OkResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = OpenShockProblem.from_dict(response.json()) + + return response_401 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LoginV2OkResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + body: LoginV2, +) -> Response[LoginV2OkResponse | OpenShockProblem]: + """Authenticate a user + + Args: + body (LoginV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LoginV2OkResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + body: LoginV2, +) -> LoginV2OkResponse | OpenShockProblem | None: + """Authenticate a user + + Args: + body (LoginV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LoginV2OkResponse | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: LoginV2, +) -> Response[LoginV2OkResponse | OpenShockProblem]: + """Authenticate a user + + Args: + body (LoginV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LoginV2OkResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + body: LoginV2, +) -> LoginV2OkResponse | OpenShockProblem | None: + """Authenticate a user + + Args: + body (LoginV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LoginV2OkResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/account_logout.py b/openshock/rest/api/account/account_logout.py new file mode 100644 index 0000000..606552a --- /dev/null +++ b/openshock/rest/api/account/account_logout.py @@ -0,0 +1,80 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/logout", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[Any]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[Any]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/account/account_password_reset_check_valid.py b/openshock/rest/api/account/account_password_reset_check_valid.py new file mode 100644 index 0000000..16d1ce2 --- /dev/null +++ b/openshock/rest/api/account/account_password_reset_check_valid.py @@ -0,0 +1,177 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + password_reset_id: UUID, + secret: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/account/password-reset/{password_reset_id}/{secret}".format( + password_reset_id=quote(str(password_reset_id), safe=""), + secret=quote(str(secret), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Check if a password reset is in progress + + Args: + password_reset_id (UUID): + secret (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + password_reset_id=password_reset_id, + secret=secret, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Check if a password reset is in progress + + Args: + password_reset_id (UUID): + secret (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + password_reset_id=password_reset_id, + secret=secret, + client=client, + ).parsed + + +async def asyncio_detailed( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Check if a password reset is in progress + + Args: + password_reset_id (UUID): + secret (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + password_reset_id=password_reset_id, + secret=secret, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Check if a password reset is in progress + + Args: + password_reset_id (UUID): + secret (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + password_reset_id=password_reset_id, + secret=secret, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/account/account_password_reset_complete.py b/openshock/rest/api/account/account_password_reset_complete.py new file mode 100644 index 0000000..909b8d2 --- /dev/null +++ b/openshock/rest/api/account/account_password_reset_complete.py @@ -0,0 +1,198 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...models.password_reset_process_data import PasswordResetProcessData +from ...types import Response + + +def _get_kwargs( + password_reset_id: UUID, + secret: str, + *, + body: PasswordResetProcessData, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/password-reset/{password_reset_id}/{secret}/complete".format( + password_reset_id=quote(str(password_reset_id), safe=""), + secret=quote(str(secret), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, + body: PasswordResetProcessData, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Complete a password reset process + + Args: + password_reset_id (UUID): + secret (str): + body (PasswordResetProcessData): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + password_reset_id=password_reset_id, + secret=secret, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, + body: PasswordResetProcessData, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Complete a password reset process + + Args: + password_reset_id (UUID): + secret (str): + body (PasswordResetProcessData): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + password_reset_id=password_reset_id, + secret=secret, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, + body: PasswordResetProcessData, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Complete a password reset process + + Args: + password_reset_id (UUID): + secret (str): + body (PasswordResetProcessData): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + password_reset_id=password_reset_id, + secret=secret, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + password_reset_id: UUID, + secret: str, + *, + client: AuthenticatedClient | Client, + body: PasswordResetProcessData, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Complete a password reset process + + Args: + password_reset_id (UUID): + secret (str): + body (PasswordResetProcessData): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + password_reset_id=password_reset_id, + secret=secret, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/account_password_reset_initiate_v2.py b/openshock/rest/api/account/account_password_reset_initiate_v2.py new file mode 100644 index 0000000..8d0fe30 --- /dev/null +++ b/openshock/rest/api/account/account_password_reset_initiate_v2.py @@ -0,0 +1,165 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.password_reset_request_v2 import PasswordResetRequestV2 +from ...types import Response + + +def _get_kwargs( + *, + body: PasswordResetRequestV2, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/account/password-reset", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + body: PasswordResetRequestV2, +) -> Response[Any | OpenShockProblem]: + """Initiate a password reset + + Args: + body (PasswordResetRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + body: PasswordResetRequestV2, +) -> Any | OpenShockProblem | None: + """Initiate a password reset + + Args: + body (PasswordResetRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: PasswordResetRequestV2, +) -> Response[Any | OpenShockProblem]: + """Initiate a password reset + + Args: + body (PasswordResetRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + body: PasswordResetRequestV2, +) -> Any | OpenShockProblem | None: + """Initiate a password reset + + Args: + body (PasswordResetRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/account_resend_activation.py b/openshock/rest/api/account/account_resend_activation.py new file mode 100644 index 0000000..ee3eeb3 --- /dev/null +++ b/openshock/rest/api/account/account_resend_activation.py @@ -0,0 +1,154 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/activate/resend", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 429: + response_429 = OpenShockProblem.from_dict(response.json()) + + return response_429 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[Any | OpenShockProblem]: + """Resend the account activation email for the account this browser just signed up + + Identifies the account by the activation-resend cookie set on signup, not by an email address, + so it can only target an account created from this browser and can't be used to probe registered + emails. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, +) -> Any | OpenShockProblem | None: + """Resend the account activation email for the account this browser just signed up + + Identifies the account by the activation-resend cookie set on signup, not by an email address, + so it can only target an account created from this browser and can't be used to probe registered + emails. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[Any | OpenShockProblem]: + """Resend the account activation email for the account this browser just signed up + + Identifies the account by the activation-resend cookie set on signup, not by an email address, + so it can only target an account created from this browser and can't be used to probe registered + emails. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, +) -> Any | OpenShockProblem | None: + """Resend the account activation email for the account this browser just signed up + + Identifies the account by the activation-resend cookie set on signup, not by an email address, + so it can only target an account created from this browser and can't be used to probe registered + emails. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/account/account_sign_up_v2.py b/openshock/rest/api/account/account_sign_up_v2.py new file mode 100644 index 0000000..587653c --- /dev/null +++ b/openshock/rest/api/account/account_sign_up_v2.py @@ -0,0 +1,174 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.sign_up_v2 import SignUpV2 +from ...types import Response + + +def _get_kwargs( + *, + body: SignUpV2, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/account/signup", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = cast(Any, None) + return response_400 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + body: SignUpV2, +) -> Response[Any | OpenShockProblem]: + """Signs up a new user + + Args: + body (SignUpV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + body: SignUpV2, +) -> Any | OpenShockProblem | None: + """Signs up a new user + + Args: + body (SignUpV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: SignUpV2, +) -> Response[Any | OpenShockProblem]: + """Signs up a new user + + Args: + body (SignUpV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + body: SignUpV2, +) -> Any | OpenShockProblem | None: + """Signs up a new user + + Args: + body (SignUpV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_email.py b/openshock/rest/api/account/authenticated_account_change_email.py new file mode 100644 index 0000000..61c9030 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_change_email.py @@ -0,0 +1,189 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.change_email_request import ChangeEmailRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ChangeEmailRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/email-change", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = OpenShockProblem.from_dict(response.json()) + + return response_401 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if response.status_code == 429: + response_429 = OpenShockProblem.from_dict(response.json()) + + return response_429 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Response[Any | OpenShockProblem]: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Any | OpenShockProblem | None: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Response[Any | OpenShockProblem]: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Any | OpenShockProblem | None: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_password.py b/openshock/rest/api/account/authenticated_account_change_password.py new file mode 100644 index 0000000..278a24f --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_change_password.py @@ -0,0 +1,170 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.change_password_request import ChangePasswordRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ChangePasswordRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/password", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Response[Any | OpenShockProblem]: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Any | OpenShockProblem | None: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Response[Any | OpenShockProblem]: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Any | OpenShockProblem | None: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_username.py b/openshock/rest/api/account/authenticated_account_change_username.py new file mode 100644 index 0000000..4f5f5c2 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_change_username.py @@ -0,0 +1,175 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.change_username_request import ChangeUsernameRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ChangeUsernameRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/username", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Response[Any | OpenShockProblem]: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Any | OpenShockProblem | None: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Response[Any | OpenShockProblem]: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Any | OpenShockProblem | None: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_deactivate.py b/openshock/rest/api/account/authenticated_account_deactivate.py new file mode 100644 index 0000000..1c590a1 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_deactivate.py @@ -0,0 +1,133 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/account", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 204: + response_204 = cast(Any, None) + return response_204 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_get_audit_log.py b/openshock/rest/api/account/authenticated_account_get_audit_log.py new file mode 100644 index 0000000..36ca1f4 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_get_audit_log.py @@ -0,0 +1,226 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse +from ...models.sort_direction import SortDirection +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["page"] = page + + params["pageSize"] = page_size + + params["search"] = search + + params["sort"] = sort + + json_sort_dir: str | Unset = UNSET + if not isinstance(sort_dir, Unset): + json_sort_dir = sort_dir.value + + params["sortDir"] = json_sort_dir + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/account/audit-log", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> PagedResultOfAuditLogEntryResponse | None: + if response.status_code == 200: + response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[PagedResultOfAuditLogEntryResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return sync_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return ( + await asyncio_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_get_self.py b/openshock/rest/api/account/authenticated_account_get_self.py new file mode 100644 index 0000000..81c279e --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_get_self.py @@ -0,0 +1,125 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.user_self_response import UserSelfResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/account", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> UserSelfResponse | None: + if response.status_code == 200: + response_200 = UserSelfResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[UserSelfResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[UserSelfResponse]: + """Get the current user's account information. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[UserSelfResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> UserSelfResponse | None: + """Get the current user's account information. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + UserSelfResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[UserSelfResponse]: + """Get the current user's account information. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[UserSelfResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> UserSelfResponse | None: + """Get the current user's account information. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + UserSelfResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py b/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py new file mode 100644 index 0000000..4bed30e --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py @@ -0,0 +1,134 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.o_auth_connection_response import OAuthConnectionResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/account/connections", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[OAuthConnectionResponse] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = OAuthConnectionResponse.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[OAuthConnectionResponse]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[OAuthConnectionResponse]]: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[OAuthConnectionResponse]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[OAuthConnectionResponse] | None: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[OAuthConnectionResponse] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[OAuthConnectionResponse]]: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[OAuthConnectionResponse]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[OAuthConnectionResponse] | None: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[OAuthConnectionResponse] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py b/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py new file mode 100644 index 0000000..d91c1ca --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py @@ -0,0 +1,158 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + provider: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/account/connections/{provider}".format( + provider=quote(str(provider), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 204: + response_204 = cast(Any, None) + return response_204 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + provider: str, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + provider=provider, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + provider: str, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + provider=provider, + client=client, + ).parsed + + +async def asyncio_detailed( + provider: str, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + provider=provider, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + provider: str, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + provider=provider, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/__init__.py b/openshock/rest/api/admin/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/admin/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/admin/admin_add_email_provider_blacklist.py b/openshock/rest/api/admin/admin_add_email_provider_blacklist.py new file mode 100644 index 0000000..2dcec86 --- /dev/null +++ b/openshock/rest/api/admin/admin_add_email_provider_blacklist.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto +from ...types import Response + + +def _get_kwargs( + *, + body: AddEmailProviderBlacklistDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/blacklist/emailProviders", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: AddEmailProviderBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddEmailProviderBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: AddEmailProviderBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddEmailProviderBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_username_blacklist.py b/openshock/rest/api/admin/admin_add_username_blacklist.py new file mode 100644 index 0000000..c5fbddb --- /dev/null +++ b/openshock/rest/api/admin/admin_add_username_blacklist.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.add_username_blacklist_dto import AddUsernameBlacklistDto +from ...types import Response + + +def _get_kwargs( + *, + body: AddUsernameBlacklistDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/blacklist/usernames", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: AddUsernameBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddUsernameBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: AddUsernameBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddUsernameBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_webhook.py b/openshock/rest/api/admin/admin_add_webhook.py new file mode 100644 index 0000000..833d05d --- /dev/null +++ b/openshock/rest/api/admin/admin_add_webhook.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.add_webhook_dto import AddWebhookDto +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + *, + body: AddWebhookDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/webhooks", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = ProblemDetails.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Response[Any | ProblemDetails]: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Any | ProblemDetails | None: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Response[Any | ProblemDetails]: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Any | ProblemDetails | None: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py b/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py new file mode 100644 index 0000000..a4c511e --- /dev/null +++ b/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py @@ -0,0 +1,177 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest +from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from ...types import Response + + +def _get_kwargs( + *, + body: EmailOutboxBulkRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/bulk/cancel", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxBulkResultDto | None: + if response.status_code == 200: + response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxBulkResultDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py b/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py new file mode 100644 index 0000000..775933d --- /dev/null +++ b/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py @@ -0,0 +1,173 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest +from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from ...types import Response + + +def _get_kwargs( + *, + body: EmailOutboxBulkRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/bulk/delete", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxBulkResultDto | None: + if response.status_code == 200: + response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxBulkResultDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py b/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py new file mode 100644 index 0000000..5e3f3ed --- /dev/null +++ b/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py @@ -0,0 +1,177 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest +from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from ...types import Response + + +def _get_kwargs( + *, + body: EmailOutboxBulkRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/bulk/requeue", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxBulkResultDto | None: + if response.status_code == 200: + response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxBulkResultDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_cancel_email_outbox.py b/openshock/rest/api/admin/admin_cancel_email_outbox.py new file mode 100644 index 0000000..6257ab1 --- /dev/null +++ b/openshock/rest/api/admin/admin_cancel_email_outbox.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/{id}/cancel".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = ProblemDetails.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_add.py b/openshock/rest/api/admin/admin_configuration_add.py new file mode 100644 index 0000000..4347d91 --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_add.py @@ -0,0 +1,174 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.configuration_add_item_request import ConfigurationAddItemRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ConfigurationAddItemRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/config", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Response[Any | OpenShockProblem]: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Any | OpenShockProblem | None: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Response[Any | OpenShockProblem]: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Any | OpenShockProblem | None: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_delete.py b/openshock/rest/api/admin/admin_configuration_delete.py new file mode 100644 index 0000000..7161385 --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_delete.py @@ -0,0 +1,169 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + name: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/config/{name}".format( + name=quote(str(name), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + name: str, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + name=name, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + name: str, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + name=name, + client=client, + ).parsed + + +async def asyncio_detailed( + name: str, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + name=name, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + name: str, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + name=name, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_list.py b/openshock/rest/api/admin/admin_configuration_list.py new file mode 100644 index 0000000..39dc4fd --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_list.py @@ -0,0 +1,138 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.configuration_item_dto import ConfigurationItemDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/config", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | list[ConfigurationItemDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = ConfigurationItemDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | list[ConfigurationItemDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[ConfigurationItemDto]]: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[ConfigurationItemDto]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | list[ConfigurationItemDto] | None: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[ConfigurationItemDto] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[ConfigurationItemDto]]: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[ConfigurationItemDto]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | list[ConfigurationItemDto] | None: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[ConfigurationItemDto] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_update.py b/openshock/rest/api/admin/admin_configuration_update.py new file mode 100644 index 0000000..93f5294 --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_update.py @@ -0,0 +1,191 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.configuration_update_item_request import ConfigurationUpdateItemRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ConfigurationUpdateItemRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/config", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Response[Any | OpenShockProblem]: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Any | OpenShockProblem | None: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Response[Any | OpenShockProblem]: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Any | OpenShockProblem | None: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_create_automation_token.py b/openshock/rest/api/admin/admin_create_automation_token.py new file mode 100644 index 0000000..8ebddfe --- /dev/null +++ b/openshock/rest/api/admin/admin_create_automation_token.py @@ -0,0 +1,161 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.create_automation_token_dto import CreateAutomationTokenDto +from ...models.created_automation_token_dto import CreatedAutomationTokenDto +from ...types import Response + + +def _get_kwargs( + *, + body: CreateAutomationTokenDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/automationTokens", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> CreatedAutomationTokenDto | None: + if response.status_code == 200: + response_200 = CreatedAutomationTokenDto.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[CreatedAutomationTokenDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> Response[CreatedAutomationTokenDto]: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> CreatedAutomationTokenDto | None: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> Response[CreatedAutomationTokenDto]: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> CreatedAutomationTokenDto | None: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_deactivate_user.py b/openshock/rest/api/admin/admin_deactivate_user.py new file mode 100644 index 0000000..fb92e0d --- /dev/null +++ b/openshock/rest/api/admin/admin_deactivate_user.py @@ -0,0 +1,127 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + user_id: UUID, + *, + delete_later: bool | Unset = UNSET, + reason: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["deleteLater"] = delete_later + + params["reason"] = reason + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/deactivate".format( + user_id=quote(str(user_id), safe=""), + ), + "params": params, + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + delete_later: bool | Unset = UNSET, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deactivates a user + + Args: + user_id (UUID): + delete_later (bool | Unset): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + delete_later=delete_later, + reason=reason, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + delete_later: bool | Unset = UNSET, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deactivates a user + + Args: + user_id (UUID): + delete_later (bool | Unset): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + delete_later=delete_later, + reason=reason, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_api_token.py b/openshock/rest/api/admin/admin_delete_api_token.py new file mode 100644 index 0000000..aa2c018 --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_api_token.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import Response + + +def _get_kwargs( + token_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/apitokens/{token_id}".format( + token_id=quote(str(token_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any]: + """Deletes an API token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any]: + """Deletes an API token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_automation_token.py b/openshock/rest/api/admin/admin_delete_automation_token.py new file mode 100644 index 0000000..0bc899c --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_automation_token.py @@ -0,0 +1,168 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/automationTokens/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = ProblemDetails.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_delete_email_outbox.py b/openshock/rest/api/admin/admin_delete_email_outbox.py new file mode 100644 index 0000000..6a9034d --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_email_outbox.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/email/outbox/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_delete_user.py b/openshock/rest/api/admin/admin_delete_user.py new file mode 100644 index 0000000..4de0110 --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_user.py @@ -0,0 +1,118 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + user_id: UUID, + *, + reason: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["reason"] = reason + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/users/{user_id}".format( + user_id=quote(str(user_id), safe=""), + ), + "params": params, + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deletes a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deletes a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_get_admin_audit_log.py b/openshock/rest/api/admin/admin_get_admin_audit_log.py new file mode 100644 index 0000000..55d480b --- /dev/null +++ b/openshock/rest/api/admin/admin_get_admin_audit_log.py @@ -0,0 +1,263 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse +from ...models.sort_direction import SortDirection +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["page"] = page + + params["pageSize"] = page_size + + params["search"] = search + + params["sort"] = sort + + json_sort_dir: str | Unset = UNSET + if not isinstance(sort_dir, Unset): + json_sort_dir = sort_dir.value + + params["sortDir"] = json_sort_dir + + json_user_id: str | Unset = UNSET + if not isinstance(user_id, Unset): + json_user_id = str(user_id) + params["userId"] = json_user_id + + json_actor_id: str | Unset = UNSET + if not isinstance(actor_id, Unset): + json_actor_id = str(actor_id) + params["actorId"] = json_actor_id + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/audit-log", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> PagedResultOfAuditLogEntryResponse | None: + if response.status_code == 200: + response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[PagedResultOfAuditLogEntryResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return sync_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return ( + await asyncio_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox.py b/openshock/rest/api/admin/admin_get_email_outbox.py new file mode 100644 index 0000000..af7ea09 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_email_outbox.py @@ -0,0 +1,218 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["$filter"] = filter_ + + params["$orderby"] = orderby + + params["$offset"] = offset + + params["$limit"] = limit + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/email/outbox", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | PaginatedOfEmailOutboxMessageDto | None: + if response.status_code == 200: + response_200 = PaginatedOfEmailOutboxMessageDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfEmailOutboxMessageDto] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfEmailOutboxMessageDto | None: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfEmailOutboxMessageDto + """ + + return sync_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfEmailOutboxMessageDto] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfEmailOutboxMessageDto | None: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfEmailOutboxMessageDto + """ + + return ( + await asyncio_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox_stats.py b/openshock/rest/api/admin/admin_get_email_outbox_stats.py new file mode 100644 index 0000000..1e97d6d --- /dev/null +++ b/openshock/rest/api/admin/admin_get_email_outbox_stats.py @@ -0,0 +1,133 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_stats_dto import EmailOutboxStatsDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/email/outbox/stats", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxStatsDto | None: + if response.status_code == 200: + response_200 = EmailOutboxStatsDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxStatsDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | EmailOutboxStatsDto]: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxStatsDto] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | EmailOutboxStatsDto | None: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxStatsDto + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | EmailOutboxStatsDto]: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxStatsDto] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | EmailOutboxStatsDto | None: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxStatsDto + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_devices.py b/openshock/rest/api/admin/admin_get_online_devices.py new file mode 100644 index 0000000..038a002 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_online_devices.py @@ -0,0 +1,135 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_admin_online_device_response import ( + LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, +) +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/monitoring/onlineDevices", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_gateways.py b/openshock/rest/api/admin/admin_get_online_gateways.py new file mode 100644 index 0000000..8e655a1 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_online_gateways.py @@ -0,0 +1,138 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.admin_online_gateway_response import AdminOnlineGatewayResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/monitoring/gateways", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | list[AdminOnlineGatewayResponse] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = AdminOnlineGatewayResponse.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | list[AdminOnlineGatewayResponse]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[AdminOnlineGatewayResponse]]: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[AdminOnlineGatewayResponse]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | list[AdminOnlineGatewayResponse] | None: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[AdminOnlineGatewayResponse] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[AdminOnlineGatewayResponse]]: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[AdminOnlineGatewayResponse]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | list[AdminOnlineGatewayResponse] | None: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[AdminOnlineGatewayResponse] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_user_by_id.py b/openshock/rest/api/admin/admin_get_user_by_id.py new file mode 100644 index 0000000..0cdfef5 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_user_by_id.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.admin_user_view import AdminUserView +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + user_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/users/{user_id}".format( + user_id=quote(str(user_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> AdminUserView | Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = AdminUserView.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[AdminUserView | Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[AdminUserView | Any | ProblemDetails]: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AdminUserView | Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> AdminUserView | Any | ProblemDetails | None: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AdminUserView | Any | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[AdminUserView | Any | ProblemDetails]: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AdminUserView | Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> AdminUserView | Any | ProblemDetails | None: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AdminUserView | Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_users.py b/openshock/rest/api/admin/admin_get_users.py new file mode 100644 index 0000000..87e1045 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_users.py @@ -0,0 +1,210 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paginated_of_admin_users_view import PaginatedOfAdminUsersView +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["$filter"] = filter_ + + params["$orderby"] = orderby + + params["$offset"] = offset + + params["$limit"] = limit + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/users", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | PaginatedOfAdminUsersView | None: + if response.status_code == 200: + response_200 = PaginatedOfAdminUsersView.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | PaginatedOfAdminUsersView]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfAdminUsersView]: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfAdminUsersView] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfAdminUsersView | None: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfAdminUsersView + """ + + return sync_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfAdminUsersView]: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfAdminUsersView] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfAdminUsersView | None: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfAdminUsersView + """ + + return ( + await asyncio_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_automation_tokens.py b/openshock/rest/api/admin/admin_list_automation_tokens.py new file mode 100644 index 0000000..23171a0 --- /dev/null +++ b/openshock/rest/api/admin/admin_list_automation_tokens.py @@ -0,0 +1,134 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.automation_token_dto import AutomationTokenDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/automationTokens", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[AutomationTokenDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = AutomationTokenDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[AutomationTokenDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[AutomationTokenDto]]: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[AutomationTokenDto]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[AutomationTokenDto] | None: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[AutomationTokenDto] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[AutomationTokenDto]]: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[AutomationTokenDto]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[AutomationTokenDto] | None: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[AutomationTokenDto] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_email_provider_blacklist.py b/openshock/rest/api/admin/admin_list_email_provider_blacklist.py new file mode 100644 index 0000000..f6011ba --- /dev/null +++ b/openshock/rest/api/admin/admin_list_email_provider_blacklist.py @@ -0,0 +1,162 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_provider_blacklist_dto import EmailProviderBlacklistDto +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + match: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["match"] = match + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/blacklist/emailProviders", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[EmailProviderBlacklistDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = EmailProviderBlacklistDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[EmailProviderBlacklistDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[EmailProviderBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[EmailProviderBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[EmailProviderBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[EmailProviderBlacklistDto] + """ + + return sync_detailed( + client=client, + match=match, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[EmailProviderBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[EmailProviderBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[EmailProviderBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[EmailProviderBlacklistDto] + """ + + return ( + await asyncio_detailed( + client=client, + match=match, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_username_blacklist.py b/openshock/rest/api/admin/admin_list_username_blacklist.py new file mode 100644 index 0000000..c1f1b45 --- /dev/null +++ b/openshock/rest/api/admin/admin_list_username_blacklist.py @@ -0,0 +1,162 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.user_name_blacklist_dto import UserNameBlacklistDto +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + match: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["match"] = match + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/blacklist/usernames", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[UserNameBlacklistDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = UserNameBlacklistDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[UserNameBlacklistDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[UserNameBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[UserNameBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[UserNameBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[UserNameBlacklistDto] + """ + + return sync_detailed( + client=client, + match=match, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[UserNameBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[UserNameBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[UserNameBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[UserNameBlacklistDto] + """ + + return ( + await asyncio_detailed( + client=client, + match=match, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_webhooks.py b/openshock/rest/api/admin/admin_list_webhooks.py new file mode 100644 index 0000000..87efc54 --- /dev/null +++ b/openshock/rest/api/admin/admin_list_webhooks.py @@ -0,0 +1,138 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.webhook_dto import WebhookDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/webhooks", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | list[WebhookDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = WebhookDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | list[WebhookDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[WebhookDto]]: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[WebhookDto]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | list[WebhookDto] | None: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[WebhookDto] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[WebhookDto]]: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[WebhookDto]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | list[WebhookDto] | None: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[WebhookDto] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_modify_user.py b/openshock/rest/api/admin/admin_modify_user.py new file mode 100644 index 0000000..fa09ec9 --- /dev/null +++ b/openshock/rest/api/admin/admin_modify_user.py @@ -0,0 +1,121 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.user_patch_dto import UserPatchDto +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: UserPatchDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/admin/users/{user_id}".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if response.status_code == 404: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: UserPatchDto, +) -> Response[Any]: + """Edits a user + + Args: + user_id (UUID): + body (UserPatchDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: UserPatchDto, +) -> Response[Any]: + """Edits a user + + Args: + user_id (UUID): + body (UserPatchDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_patch_automation_token.py b/openshock/rest/api/admin/admin_patch_automation_token.py new file mode 100644 index 0000000..53798c1 --- /dev/null +++ b/openshock/rest/api/admin/admin_patch_automation_token.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.automation_token_dto import AutomationTokenDto +from ...models.patch_automation_token_dto import PatchAutomationTokenDto +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, + *, + body: PatchAutomationTokenDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/admin/automationTokens/{id}".format( + id=quote(str(id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> AutomationTokenDto | ProblemDetails | None: + if response.status_code == 200: + response_200 = AutomationTokenDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[AutomationTokenDto | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> Response[AutomationTokenDto | ProblemDetails]: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> AutomationTokenDto | ProblemDetails | None: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AutomationTokenDto | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> Response[AutomationTokenDto | ProblemDetails]: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> AutomationTokenDto | ProblemDetails | None: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AutomationTokenDto | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_reactivate_user.py b/openshock/rest/api/admin/admin_reactivate_user.py new file mode 100644 index 0000000..8a950b1 --- /dev/null +++ b/openshock/rest/api/admin/admin_reactivate_user.py @@ -0,0 +1,118 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + user_id: UUID, + *, + reason: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["reason"] = reason + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/reactivate".format( + user_id=quote(str(user_id), safe=""), + ), + "params": params, + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Reactivates a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Reactivates a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py b/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py new file mode 100644 index 0000000..e38dd29 --- /dev/null +++ b/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py @@ -0,0 +1,155 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/blacklist/emailProviders/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_remove_username_blacklist.py b/openshock/rest/api/admin/admin_remove_username_blacklist.py new file mode 100644 index 0000000..c019ba9 --- /dev/null +++ b/openshock/rest/api/admin/admin_remove_username_blacklist.py @@ -0,0 +1,155 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/blacklist/usernames/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_remove_webhook.py b/openshock/rest/api/admin/admin_remove_webhook.py new file mode 100644 index 0000000..3248192 --- /dev/null +++ b/openshock/rest/api/admin/admin_remove_webhook.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/webhooks/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_requeue_email_outbox.py b/openshock/rest/api/admin/admin_requeue_email_outbox.py new file mode 100644 index 0000000..4922023 --- /dev/null +++ b/openshock/rest/api/admin/admin_requeue_email_outbox.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/{id}/requeue".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = ProblemDetails.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_rotate_automation_token.py b/openshock/rest/api/admin/admin_rotate_automation_token.py new file mode 100644 index 0000000..38a1b67 --- /dev/null +++ b/openshock/rest/api/admin/admin_rotate_automation_token.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.created_automation_token_dto import CreatedAutomationTokenDto +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/automationTokens/{id}/rotate".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> CreatedAutomationTokenDto | ProblemDetails | None: + if response.status_code == 200: + response_200 = CreatedAutomationTokenDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[CreatedAutomationTokenDto | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[CreatedAutomationTokenDto | ProblemDetails]: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> CreatedAutomationTokenDto | ProblemDetails | None: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[CreatedAutomationTokenDto | ProblemDetails]: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> CreatedAutomationTokenDto | ProblemDetails | None: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_send_test_email.py b/openshock/rest/api/admin/admin_send_test_email.py new file mode 100644 index 0000000..90bf759 --- /dev/null +++ b/openshock/rest/api/admin/admin_send_test_email.py @@ -0,0 +1,191 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_message_dto import EmailOutboxMessageDto +from ...models.problem_details import ProblemDetails +from ...models.send_test_email_dto import SendTestEmailDto +from ...types import Response + + +def _get_kwargs( + *, + body: SendTestEmailDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/test", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxMessageDto | ProblemDetails | None: + if response.status_code == 200: + response_200 = EmailOutboxMessageDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = ProblemDetails.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxMessageDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Any | EmailOutboxMessageDto | ProblemDetails | None: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxMessageDto | ProblemDetails + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxMessageDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Any | EmailOutboxMessageDto | ProblemDetails | None: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxMessageDto | ProblemDetails + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_email.py b/openshock/rest/api/admin/admin_set_user_email.py new file mode 100644 index 0000000..a8fee2d --- /dev/null +++ b/openshock/rest/api/admin/admin_set_user_email.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...models.set_user_email_request_body import SetUserEmailRequestBody +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: SetUserEmailRequestBody, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/email".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Response[Any | ProblemDetails]: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Any | ProblemDetails | None: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Response[Any | ProblemDetails]: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Any | ProblemDetails | None: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_name.py b/openshock/rest/api/admin/admin_set_user_name.py new file mode 100644 index 0000000..fc6ff10 --- /dev/null +++ b/openshock/rest/api/admin/admin_set_user_name.py @@ -0,0 +1,192 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.problem_details import ProblemDetails +from ...models.set_user_name_request_body import SetUserNameRequestBody +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: SetUserNameRequestBody, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/name".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_password.py b/openshock/rest/api/admin/admin_set_user_password.py new file mode 100644 index 0000000..60ab728 --- /dev/null +++ b/openshock/rest/api/admin/admin_set_user_password.py @@ -0,0 +1,192 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.problem_details import ProblemDetails +from ...models.set_user_password_request_body import SetUserPasswordRequestBody +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: SetUserPasswordRequestBody, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/password".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/__init__.py b/openshock/rest/api/api_tokens/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/api_tokens/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/api_tokens/token_delete_delete_token.py b/openshock/rest/api/api_tokens/token_delete_delete_token.py new file mode 100644 index 0000000..3093f99 --- /dev/null +++ b/openshock/rest/api/api_tokens/token_delete_delete_token.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + token_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/tokens/{token_id}".format( + token_id=quote(str(token_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 403: + response_403 = ProblemDetails.from_dict(response.json()) + + return response_403 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Revoke a token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Revoke a token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return sync_detailed( + token_id=token_id, + client=client, + ).parsed + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Revoke a token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Revoke a token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return ( + await asyncio_detailed( + token_id=token_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_create_token_v2.py b/openshock/rest/api/api_tokens/tokens_create_token_v2.py new file mode 100644 index 0000000..3c43d0b --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_create_token_v2.py @@ -0,0 +1,161 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.create_token_request_v2 import CreateTokenRequestV2 +from ...models.token_created_response_v2 import TokenCreatedResponseV2 +from ...types import Response + + +def _get_kwargs( + *, + body: CreateTokenRequestV2, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/tokens", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> TokenCreatedResponseV2 | None: + if response.status_code == 200: + response_200 = TokenCreatedResponseV2.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[TokenCreatedResponseV2]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> Response[TokenCreatedResponseV2]: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[TokenCreatedResponseV2] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> TokenCreatedResponseV2 | None: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + TokenCreatedResponseV2 + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> Response[TokenCreatedResponseV2]: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[TokenCreatedResponseV2] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> TokenCreatedResponseV2 | None: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + TokenCreatedResponseV2 + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_edit_token_v2.py b/openshock/rest/api/api_tokens/tokens_edit_token_v2.py new file mode 100644 index 0000000..6c71df2 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_edit_token_v2.py @@ -0,0 +1,182 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.edit_token_request_v2 import EditTokenRequestV2 +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + token_id: UUID, + *, + body: EditTokenRequestV2, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/2/tokens/{token_id}".format( + token_id=quote(str(token_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Response[Any | OpenShockProblem]: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Any | OpenShockProblem | None: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + token_id=token_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Response[Any | OpenShockProblem]: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Any | OpenShockProblem | None: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + token_id=token_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py b/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py new file mode 100644 index 0000000..651c565 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.token_response_v2 import TokenResponseV2 +from ...types import Response + + +def _get_kwargs( + token_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/tokens/{token_id}".format( + token_id=quote(str(token_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> OpenShockProblem | TokenResponseV2 | None: + if response.status_code == 200: + response_200 = TokenResponseV2.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[OpenShockProblem | TokenResponseV2]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[OpenShockProblem | TokenResponseV2]: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenResponseV2] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> OpenShockProblem | TokenResponseV2 | None: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenResponseV2 + """ + + return sync_detailed( + token_id=token_id, + client=client, + ).parsed + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[OpenShockProblem | TokenResponseV2]: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenResponseV2] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> OpenShockProblem | TokenResponseV2 | None: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenResponseV2 + """ + + return ( + await asyncio_detailed( + token_id=token_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py b/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py new file mode 100644 index 0000000..f0a4125 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py @@ -0,0 +1,132 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.token_response_v2 import TokenResponseV2 +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/tokens", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> list[TokenResponseV2] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = TokenResponseV2.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[TokenResponseV2]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[TokenResponseV2]]: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[TokenResponseV2]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[TokenResponseV2] | None: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[TokenResponseV2] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[TokenResponseV2]]: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[TokenResponseV2]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[TokenResponseV2] | None: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[TokenResponseV2] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_report_tokens.py b/openshock/rest/api/api_tokens/tokens_report_tokens.py new file mode 100644 index 0000000..b505c71 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_report_tokens.py @@ -0,0 +1,104 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.report_tokens_request import ReportTokensRequest +from ...types import Response + + +def _get_kwargs( + *, + body: ReportTokensRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/tokens/report", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ReportTokensRequest, +) -> Response[Any]: + """Endpoint to delete potentially compromised api tokens + + Args: + body (ReportTokensRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ReportTokensRequest, +) -> Response[Any]: + """Endpoint to delete potentially compromised api tokens + + Args: + body (ReportTokensRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/api_tokens/tokens_self_get_self_token_v2.py b/openshock/rest/api/api_tokens/tokens_self_get_self_token_v2.py new file mode 100644 index 0000000..a8223e2 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_self_get_self_token_v2.py @@ -0,0 +1,125 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.token_response_v2 import TokenResponseV2 +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/tokens/self", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> TokenResponseV2 | None: + if response.status_code == 200: + response_200 = TokenResponseV2.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[TokenResponseV2]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[TokenResponseV2]: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[TokenResponseV2] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> TokenResponseV2 | None: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + TokenResponseV2 + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[TokenResponseV2]: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[TokenResponseV2] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> TokenResponseV2 | None: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + TokenResponseV2 + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_set_token_paused.py b/openshock/rest/api/api_tokens/tokens_set_token_paused.py new file mode 100644 index 0000000..feefc15 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_set_token_paused.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.set_token_paused_request import SetTokenPausedRequest +from ...models.token_paused_response import TokenPausedResponse +from ...types import Response + + +def _get_kwargs( + token_id: UUID, + *, + body: SetTokenPausedRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/2/tokens/{token_id}/paused".format( + token_id=quote(str(token_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> OpenShockProblem | TokenPausedResponse | None: + if response.status_code == 200: + response_200 = TokenPausedResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[OpenShockProblem | TokenPausedResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> Response[OpenShockProblem | TokenPausedResponse]: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenPausedResponse] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> OpenShockProblem | TokenPausedResponse | None: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenPausedResponse + """ + + return sync_detailed( + token_id=token_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> Response[OpenShockProblem | TokenPausedResponse]: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenPausedResponse] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> OpenShockProblem | TokenPausedResponse | None: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenPausedResponse + """ + + return ( + await asyncio_detailed( + token_id=token_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/hub_endpoints/__init__.py b/openshock/rest/api/hub_endpoints/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/hub_endpoints/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/hub_endpoints/device_get_live_control_gateway_v2.py b/openshock/rest/api/hub_endpoints/device_get_live_control_gateway_v2.py new file mode 100644 index 0000000..f3d51ad --- /dev/null +++ b/openshock/rest/api/hub_endpoints/device_get_live_control_gateway_v2.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.lcg_node_response_v2 import LcgNodeResponseV2 +from ...models.open_shock_problem import OpenShockProblem +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + version: int | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["version"] = version + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/device/assignLCG", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LcgNodeResponseV2 | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LcgNodeResponseV2.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 503: + response_503 = OpenShockProblem.from_dict(response.json()) + + return response_503 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LcgNodeResponseV2 | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + version: int | Unset = UNSET, +) -> Response[LcgNodeResponseV2 | OpenShockProblem]: + """Gets the best suited LCG node for the client + + Args: + version (int | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LcgNodeResponseV2 | OpenShockProblem] + """ + + kwargs = _get_kwargs( + version=version, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + version: int | Unset = UNSET, +) -> LcgNodeResponseV2 | OpenShockProblem | None: + """Gets the best suited LCG node for the client + + Args: + version (int | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LcgNodeResponseV2 | OpenShockProblem + """ + + return sync_detailed( + client=client, + version=version, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + version: int | Unset = UNSET, +) -> Response[LcgNodeResponseV2 | OpenShockProblem]: + """Gets the best suited LCG node for the client + + Args: + version (int | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LcgNodeResponseV2 | OpenShockProblem] + """ + + kwargs = _get_kwargs( + version=version, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + version: int | Unset = UNSET, +) -> LcgNodeResponseV2 | OpenShockProblem | None: + """Gets the best suited LCG node for the client + + Args: + version (int | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LcgNodeResponseV2 | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + version=version, + ) + ).parsed diff --git a/openshock/rest/api/hub_endpoints/device_get_self.py b/openshock/rest/api/hub_endpoints/device_get_self.py new file mode 100644 index 0000000..993b2ca --- /dev/null +++ b/openshock/rest/api/hub_endpoints/device_get_self.py @@ -0,0 +1,129 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_device_self_response import LegacyDataResponseOfDeviceSelfResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/device/self", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfDeviceSelfResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfDeviceSelfResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfDeviceSelfResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfDeviceSelfResponse]: + """Gets information about the authenticated device. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfDeviceSelfResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfDeviceSelfResponse | None: + """Gets information about the authenticated device. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfDeviceSelfResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfDeviceSelfResponse]: + """Gets information about the authenticated device. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfDeviceSelfResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfDeviceSelfResponse | None: + """Gets information about the authenticated device. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfDeviceSelfResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_endpoints/device_pair.py b/openshock/rest/api/hub_endpoints/device_pair.py new file mode 100644 index 0000000..a42bb8b --- /dev/null +++ b/openshock/rest/api/hub_endpoints/device_pair.py @@ -0,0 +1,162 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_ofstring import LegacyDataResponseOfstring +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + pair_code: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/device/pair/{pair_code}".format( + pair_code=quote(str(pair_code), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfstring | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfstring.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfstring | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + pair_code: str, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfstring | OpenShockProblem]: + """Pair a device with a pair code. + + Args: + pair_code (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfstring | OpenShockProblem] + """ + + kwargs = _get_kwargs( + pair_code=pair_code, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + pair_code: str, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfstring | OpenShockProblem | None: + """Pair a device with a pair code. + + Args: + pair_code (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfstring | OpenShockProblem + """ + + return sync_detailed( + pair_code=pair_code, + client=client, + ).parsed + + +async def asyncio_detailed( + pair_code: str, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfstring | OpenShockProblem]: + """Pair a device with a pair code. + + Args: + pair_code (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfstring | OpenShockProblem] + """ + + kwargs = _get_kwargs( + pair_code=pair_code, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + pair_code: str, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfstring | OpenShockProblem | None: + """Pair a device with a pair code. + + Args: + pair_code (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfstring | OpenShockProblem + """ + + return ( + await asyncio_detailed( + pair_code=pair_code, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/__init__.py b/openshock/rest/api/hub_management/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/hub_management/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/hub_management/devices_create_device_v2.py b/openshock/rest/api/hub_management/devices_create_device_v2.py new file mode 100644 index 0000000..530151c --- /dev/null +++ b/openshock/rest/api/hub_management/devices_create_device_v2.py @@ -0,0 +1,157 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.hub_create_request import HubCreateRequest +from ...types import Response + + +def _get_kwargs( + *, + body: HubCreateRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/devices", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> UUID | None: + if response.status_code == 201: + response_201 = UUID(response.text) + + return response_201 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[UUID]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: HubCreateRequest, +) -> Response[UUID]: + """Create a new device for the current user + + Args: + body (HubCreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[UUID] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: HubCreateRequest, +) -> UUID | None: + """Create a new device for the current user + + Args: + body (HubCreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + UUID + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: HubCreateRequest, +) -> Response[UUID]: + """Create a new device for the current user + + Args: + body (HubCreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[UUID] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: HubCreateRequest, +) -> UUID | None: + """Create a new device for the current user + + Args: + body (HubCreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + UUID + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_edit_device.py b/openshock/rest/api/hub_management/devices_edit_device.py new file mode 100644 index 0000000..760ff21 --- /dev/null +++ b/openshock/rest/api/hub_management/devices_edit_device.py @@ -0,0 +1,182 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.hub_edit_request import HubEditRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, + *, + body: HubEditRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/devices/{device_id}".format( + device_id=quote(str(device_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, + body: HubEditRequest, +) -> Response[Any | OpenShockProblem]: + """Edit a device + + Args: + device_id (UUID): + body (HubEditRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, + body: HubEditRequest, +) -> Any | OpenShockProblem | None: + """Edit a device + + Args: + device_id (UUID): + body (HubEditRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, + body: HubEditRequest, +) -> Response[Any | OpenShockProblem]: + """Edit a device + + Args: + device_id (UUID): + body (HubEditRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, + body: HubEditRequest, +) -> Any | OpenShockProblem | None: + """Edit a device + + Args: + device_id (UUID): + body (HubEditRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_get_device_by_id.py b/openshock/rest/api/hub_management/devices_get_device_by_id.py new file mode 100644 index 0000000..05bf3e0 --- /dev/null +++ b/openshock/rest/api/hub_management/devices_get_device_by_id.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_device_with_token_response import LegacyDataResponseOfDeviceWithTokenResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/devices/{device_id}".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfDeviceWithTokenResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem]: + """Get a device by its id + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem | None: + """Get a device by its id + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem]: + """Get a device by its id + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem | None: + """Get a device by its id + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfDeviceWithTokenResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_get_live_control_gateway_info_v2.py b/openshock/rest/api/hub_management/devices_get_live_control_gateway_info_v2.py new file mode 100644 index 0000000..a5d183e --- /dev/null +++ b/openshock/rest/api/hub_management/devices_get_live_control_gateway_info_v2.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.lcg_response_v2 import LcgResponseV2 +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/devices/{device_id}/lcg".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LcgResponseV2 | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LcgResponseV2.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LcgResponseV2 | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LcgResponseV2 | OpenShockProblem]: + """Gets the live control gateway a hub is connected to, including its public port and the full + live-control WebSocket path (honoring the gateway's configured path prefix). + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LcgResponseV2 | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LcgResponseV2 | OpenShockProblem | None: + """Gets the live control gateway a hub is connected to, including its public port and the full + live-control WebSocket path (honoring the gateway's configured path prefix). + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LcgResponseV2 | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LcgResponseV2 | OpenShockProblem]: + """Gets the live control gateway a hub is connected to, including its public port and the full + live-control WebSocket path (honoring the gateway's configured path prefix). + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LcgResponseV2 | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LcgResponseV2 | OpenShockProblem | None: + """Gets the live control gateway a hub is connected to, including its public port and the full + live-control WebSocket path (honoring the gateway's configured path prefix). + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LcgResponseV2 | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_get_pair_code.py b/openshock/rest/api/hub_management/devices_get_pair_code.py new file mode 100644 index 0000000..8971ad3 --- /dev/null +++ b/openshock/rest/api/hub_management/devices_get_pair_code.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_ofstring import LegacyDataResponseOfstring +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/devices/{device_id}/pair".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfstring | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfstring.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfstring | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfstring | OpenShockProblem]: + """Get a pair code for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfstring | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfstring | OpenShockProblem | None: + """Get a pair code for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfstring | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfstring | OpenShockProblem]: + """Get a pair code for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfstring | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfstring | OpenShockProblem | None: + """Get a pair code for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfstring | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_get_shockers.py b/openshock/rest/api/hub_management/devices_get_shockers.py new file mode 100644 index 0000000..da79092 --- /dev/null +++ b/openshock/rest/api/hub_management/devices_get_shockers.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_shocker_response import LegacyDataResponseOfArrayOfShockerResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/devices/{device_id}/shockers".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfShockerResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem]: + """Get all shockers for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem | None: + """Get all shockers for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem]: + """Get all shockers for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem | None: + """Get all shockers for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfShockerResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_list_devices.py b/openshock/rest/api/hub_management/devices_list_devices.py new file mode 100644 index 0000000..30304db --- /dev/null +++ b/openshock/rest/api/hub_management/devices_list_devices.py @@ -0,0 +1,129 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_device_response import LegacyDataResponseOfArrayOfDeviceResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/devices", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfDeviceResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfDeviceResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfDeviceResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfDeviceResponse]: + """Get all devices for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfDeviceResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfDeviceResponse | None: + """Get all devices for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfDeviceResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfDeviceResponse]: + """Get all devices for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfDeviceResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfDeviceResponse | None: + """Get all devices for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfDeviceResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py b/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py new file mode 100644 index 0000000..ce2caf2 --- /dev/null +++ b/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py @@ -0,0 +1,165 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_i_read_only_collection_of_ota_item import ( + LegacyDataResponseOfIReadOnlyCollectionOfOtaItem, +) +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/devices/{device_id}/ota".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfIReadOnlyCollectionOfOtaItem.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_regenerate_device_token.py b/openshock/rest/api/hub_management/devices_regenerate_device_token.py new file mode 100644 index 0000000..99c8b2e --- /dev/null +++ b/openshock/rest/api/hub_management/devices_regenerate_device_token.py @@ -0,0 +1,165 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/devices/{device_id}".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | str | None: + if response.status_code == 200: + response_200 = response.text + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if response.status_code == 500: + response_500 = cast(Any, None) + return response_500 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem | str]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem | str]: + """Regenerate a device token + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | str] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | str | None: + """Regenerate a device token + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | str + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem | str]: + """Regenerate a device token + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | str] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | str | None: + """Regenerate a device token + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | str + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_remove_device.py b/openshock/rest/api/hub_management/devices_remove_device.py new file mode 100644 index 0000000..f01e1bd --- /dev/null +++ b/openshock/rest/api/hub_management/devices_remove_device.py @@ -0,0 +1,161 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/devices/{device_id}".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Remove a device from current user's account + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Remove a device from current user's account + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Remove a device from current user's account + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Remove a device from current user's account + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/integrations/__init__.py b/openshock/rest/api/integrations/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/integrations/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/integrations/integrations_get_control_stat_changes.py b/openshock/rest/api/integrations/integrations_get_control_stat_changes.py new file mode 100644 index 0000000..56c4d49 --- /dev/null +++ b/openshock/rest/api/integrations/integrations_get_control_stat_changes.py @@ -0,0 +1,195 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.control_stat_changes_request import ControlStatChangesRequest +from ...models.control_stat_changes_response import ControlStatChangesResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ControlStatChangesRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/integrations/control-stats/changes", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> ControlStatChangesResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = ControlStatChangesResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[ControlStatChangesResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, + body: ControlStatChangesRequest, +) -> Response[ControlStatChangesResponse | OpenShockProblem]: + """Lets a service holding many users keep their lifetime control stats in sync with a single call per + tick. + Returns the lifetime totals of every requested user whose stats changed since the given cursor. + + Requires an automation token granting `ControlStatsRead`. "Changed since" is answered from when each + control log was written, so late writes are still picked up. The lookback is widened by + TimeSpan IntegrationsController.ChangeOverlap, so a user can be reported again although nothing + changed. + + Args: + body (ControlStatChangesRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ControlStatChangesResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + body: ControlStatChangesRequest, +) -> ControlStatChangesResponse | OpenShockProblem | None: + """Lets a service holding many users keep their lifetime control stats in sync with a single call per + tick. + Returns the lifetime totals of every requested user whose stats changed since the given cursor. + + Requires an automation token granting `ControlStatsRead`. "Changed since" is answered from when each + control log was written, so late writes are still picked up. The lookback is widened by + TimeSpan IntegrationsController.ChangeOverlap, so a user can be reported again although nothing + changed. + + Args: + body (ControlStatChangesRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ControlStatChangesResponse | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: ControlStatChangesRequest, +) -> Response[ControlStatChangesResponse | OpenShockProblem]: + """Lets a service holding many users keep their lifetime control stats in sync with a single call per + tick. + Returns the lifetime totals of every requested user whose stats changed since the given cursor. + + Requires an automation token granting `ControlStatsRead`. "Changed since" is answered from when each + control log was written, so late writes are still picked up. The lookback is widened by + TimeSpan IntegrationsController.ChangeOverlap, so a user can be reported again although nothing + changed. + + Args: + body (ControlStatChangesRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ControlStatChangesResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + body: ControlStatChangesRequest, +) -> ControlStatChangesResponse | OpenShockProblem | None: + """Lets a service holding many users keep their lifetime control stats in sync with a single call per + tick. + Returns the lifetime totals of every requested user whose stats changed since the given cursor. + + Requires an automation token granting `ControlStatsRead`. "Changed since" is answered from when each + control log was written, so late writes are still picked up. The lookback is widened by + TimeSpan IntegrationsController.ChangeOverlap, so a user can be reported again although nothing + changed. + + Args: + body (ControlStatChangesRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ControlStatChangesResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/meta/__init__.py b/openshock/rest/api/meta/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/meta/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/meta/public_get_online_devices_statistics.py b/openshock/rest/api/meta/public_get_online_devices_statistics.py new file mode 100644 index 0000000..7a4735f --- /dev/null +++ b/openshock/rest/api/meta/public_get_online_devices_statistics.py @@ -0,0 +1,129 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_stats_response import LegacyDataResponseOfStatsResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/public/stats", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfStatsResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfStatsResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfStatsResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyDataResponseOfStatsResponse]: + """Gets online devices statistics + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfStatsResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, +) -> LegacyDataResponseOfStatsResponse | None: + """Gets online devices statistics + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfStatsResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyDataResponseOfStatsResponse]: + """Gets online devices statistics + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfStatsResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, +) -> LegacyDataResponseOfStatsResponse | None: + """Gets online devices statistics + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfStatsResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/meta/version_get_backend_info.py b/openshock/rest/api/meta/version_get_backend_info.py new file mode 100644 index 0000000..bf8bc73 --- /dev/null +++ b/openshock/rest/api/meta/version_get_backend_info.py @@ -0,0 +1,129 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_backend_info_response import LegacyDataResponseOfBackendInfoResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfBackendInfoResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfBackendInfoResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfBackendInfoResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyDataResponseOfBackendInfoResponse]: + """Gets the version of the OpenShock backend. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfBackendInfoResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, +) -> LegacyDataResponseOfBackendInfoResponse | None: + """Gets the version of the OpenShock backend. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfBackendInfoResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyDataResponseOfBackendInfoResponse]: + """Gets the version of the OpenShock backend. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfBackendInfoResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, +) -> LegacyDataResponseOfBackendInfoResponse | None: + """Gets the version of the OpenShock backend. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfBackendInfoResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/__init__.py b/openshock/rest/api/public_shocker_shares/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/public_shocker_shares/public_get_public_share.py b/openshock/rest/api/public_shocker_shares/public_get_public_share.py new file mode 100644 index 0000000..300e186 --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/public_get_public_share.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_public_share_response import LegacyDataResponseOfPublicShareResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + public_share_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/public/shares/links/{public_share_id}".format( + public_share_id=quote(str(public_share_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfPublicShareResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + public_share_id: UUID, + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: + """Gets information about a public share. + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + public_share_id: UUID, + *, + client: AuthenticatedClient | Client, +) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: + """Gets information about a public share. + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfPublicShareResponse | OpenShockProblem + """ + + return sync_detailed( + public_share_id=public_share_id, + client=client, + ).parsed + + +async def asyncio_detailed( + public_share_id: UUID, + *, + client: AuthenticatedClient | Client, +) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: + """Gets information about a public share. + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + public_share_id: UUID, + *, + client: AuthenticatedClient | Client, +) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: + """Gets information about a public share. + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfPublicShareResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + public_share_id=public_share_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/share_links_add_shocker.py b/openshock/rest/api/public_shocker_shares/share_links_add_shocker.py new file mode 100644 index 0000000..ae134d6 --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/share_links_add_shocker.py @@ -0,0 +1,182 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + public_share_id: UUID, + shocker_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shares/links/{public_share_id}/{shocker_id}".format( + public_share_id=quote(str(public_share_id), safe=""), + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Add a shocker to a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Add a shocker to a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + ).parsed + + +async def asyncio_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Add a shocker to a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Add a shocker to a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/share_links_create_public_share.py b/openshock/rest/api/public_shocker_shares/share_links_create_public_share.py new file mode 100644 index 0000000..8e7e04b --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/share_links_create_public_share.py @@ -0,0 +1,161 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_guid import LegacyDataResponseOfGuid +from ...models.public_share_create import PublicShareCreate +from ...types import Response + + +def _get_kwargs( + *, + body: PublicShareCreate, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shares/links", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfGuid | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfGuid.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfGuid]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: PublicShareCreate, +) -> Response[LegacyDataResponseOfGuid]: + """Create a new public share + + Args: + body (PublicShareCreate): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfGuid] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: PublicShareCreate, +) -> LegacyDataResponseOfGuid | None: + """Create a new public share + + Args: + body (PublicShareCreate): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfGuid + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: PublicShareCreate, +) -> Response[LegacyDataResponseOfGuid]: + """Create a new public share + + Args: + body (PublicShareCreate): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfGuid] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: PublicShareCreate, +) -> LegacyDataResponseOfGuid | None: + """Create a new public share + + Args: + body (PublicShareCreate): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfGuid + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/share_links_delete_public_share.py b/openshock/rest/api/public_shocker_shares/share_links_delete_public_share.py new file mode 100644 index 0000000..ae47859 --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/share_links_delete_public_share.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + public_share_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/shares/links/{public_share_id}".format( + public_share_id=quote(str(public_share_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + public_share_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Deletes a public share + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + public_share_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Deletes a public share + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + public_share_id=public_share_id, + client=client, + ).parsed + + +async def asyncio_detailed( + public_share_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Deletes a public share + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + public_share_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Deletes a public share + + Args: + public_share_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + public_share_id=public_share_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/share_links_edit_shocker.py b/openshock/rest/api/public_shocker_shares/share_links_edit_shocker.py new file mode 100644 index 0000000..3a66744 --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/share_links_edit_shocker.py @@ -0,0 +1,200 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.public_share_edit_shocker import PublicShareEditShocker +from ...types import Response + + +def _get_kwargs( + public_share_id: UUID, + shocker_id: UUID, + *, + body: PublicShareEditShocker, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/shares/links/{public_share_id}/{shocker_id}".format( + public_share_id=quote(str(public_share_id), safe=""), + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | str | None: + if response.status_code == 200: + response_200 = response.text + return response_200 + + if response.status_code == 400: + response_400 = cast(Any, None) + return response_400 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem | str]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PublicShareEditShocker, +) -> Response[Any | OpenShockProblem | str]: + """Edit a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PublicShareEditShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | str] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PublicShareEditShocker, +) -> Any | OpenShockProblem | str | None: + """Edit a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PublicShareEditShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | str + """ + + return sync_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PublicShareEditShocker, +) -> Response[Any | OpenShockProblem | str]: + """Edit a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PublicShareEditShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | str] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PublicShareEditShocker, +) -> Any | OpenShockProblem | str | None: + """Edit a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PublicShareEditShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | str + """ + + return ( + await asyncio_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/share_links_list.py b/openshock/rest/api/public_shocker_shares/share_links_list.py new file mode 100644 index 0000000..0fc2e5e --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/share_links_list.py @@ -0,0 +1,131 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_own_public_share_response import ( + LegacyDataResponseOfArrayOfOwnPublicShareResponse, +) +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shares/links", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfOwnPublicShareResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfOwnPublicShareResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfOwnPublicShareResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfOwnPublicShareResponse]: + """Get all public shares for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfOwnPublicShareResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfOwnPublicShareResponse | None: + """Get all public shares for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfOwnPublicShareResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfOwnPublicShareResponse]: + """Get all public shares for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfOwnPublicShareResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfOwnPublicShareResponse | None: + """Get all public shares for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfOwnPublicShareResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/share_links_pause_shocker.py b/openshock/rest/api/public_shocker_shares/share_links_pause_shocker.py new file mode 100644 index 0000000..4215934 --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/share_links_pause_shocker.py @@ -0,0 +1,202 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_pause_reason import LegacyDataResponseOfPauseReason +from ...models.open_shock_problem import OpenShockProblem +from ...models.pause_request import PauseRequest +from ...types import Response + + +def _get_kwargs( + public_share_id: UUID, + shocker_id: UUID, + *, + body: PauseRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shares/links/{public_share_id}/{shocker_id}/pause".format( + public_share_id=quote(str(public_share_id), safe=""), + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | LegacyDataResponseOfPauseReason | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfPauseReason.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = cast(Any, None) + return response_400 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | LegacyDataResponseOfPauseReason | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Response[Any | LegacyDataResponseOfPauseReason | OpenShockProblem]: + """Pause a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyDataResponseOfPauseReason | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Any | LegacyDataResponseOfPauseReason | OpenShockProblem | None: + """Pause a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyDataResponseOfPauseReason | OpenShockProblem + """ + + return sync_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Response[Any | LegacyDataResponseOfPauseReason | OpenShockProblem]: + """Pause a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyDataResponseOfPauseReason | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Any | LegacyDataResponseOfPauseReason | OpenShockProblem | None: + """Pause a shocker in a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyDataResponseOfPauseReason | OpenShockProblem + """ + + return ( + await asyncio_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/public_shocker_shares/share_links_remove_shocker.py b/openshock/rest/api/public_shocker_shares/share_links_remove_shocker.py new file mode 100644 index 0000000..53964f9 --- /dev/null +++ b/openshock/rest/api/public_shocker_shares/share_links_remove_shocker.py @@ -0,0 +1,181 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + public_share_id: UUID, + shocker_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/shares/links/{public_share_id}/{shocker_id}".format( + public_share_id=quote(str(public_share_id), safe=""), + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = cast(Any, None) + return response_400 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + """Remove a shocker from a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + """Remove a shocker from a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + ).parsed + + +async def asyncio_detailed( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + """Remove a shocker from a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + public_share_id=public_share_id, + shocker_id=shocker_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + public_share_id: UUID, + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + """Remove a shocker from a public share + + Args: + public_share_id (UUID): + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + public_share_id=public_share_id, + shocker_id=shocker_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/sessions/__init__.py b/openshock/rest/api/sessions/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/sessions/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/sessions/sessions_delete_session.py b/openshock/rest/api/sessions/sessions_delete_session.py new file mode 100644 index 0000000..f5f1179 --- /dev/null +++ b/openshock/rest/api/sessions/sessions_delete_session.py @@ -0,0 +1,157 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + session_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/sessions/{session_id}".format( + session_id=quote(str(session_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + session_id=session_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + session_id=session_id, + client=client, + ).parsed + + +async def asyncio_detailed( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + session_id=session_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + session_id=session_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/sessions/sessions_get_self_session.py b/openshock/rest/api/sessions/sessions_get_self_session.py new file mode 100644 index 0000000..70302aa --- /dev/null +++ b/openshock/rest/api/sessions/sessions_get_self_session.py @@ -0,0 +1,127 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.login_session_response import LoginSessionResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/sessions/self", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> LoginSessionResponse | None: + if response.status_code == 200: + response_200 = LoginSessionResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LoginSessionResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LoginSessionResponse]: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LoginSessionResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LoginSessionResponse | None: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LoginSessionResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LoginSessionResponse]: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LoginSessionResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LoginSessionResponse | None: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LoginSessionResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/sessions/sessions_list_sessions.py b/openshock/rest/api/sessions/sessions_list_sessions.py new file mode 100644 index 0000000..48a8244 --- /dev/null +++ b/openshock/rest/api/sessions/sessions_list_sessions.py @@ -0,0 +1,130 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.login_session_response import LoginSessionResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/sessions", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[LoginSessionResponse] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = LoginSessionResponse.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[LoginSessionResponse]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[LoginSessionResponse]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[LoginSessionResponse]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[LoginSessionResponse] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[LoginSessionResponse] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[LoginSessionResponse]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[LoginSessionResponse]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[LoginSessionResponse] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[LoginSessionResponse] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shocker_shares/__init__.py b/openshock/rest/api/shocker_shares/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/shocker_shares/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/shocker_shares/shares_delete_share_code.py b/openshock/rest/api/shocker_shares/shares_delete_share_code.py new file mode 100644 index 0000000..4f89f58 --- /dev/null +++ b/openshock/rest/api/shocker_shares/shares_delete_share_code.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + share_code_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/shares/code/{share_code_id}".format( + share_code_id=quote(str(share_code_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + share_code_id=share_code_id, + client=client, + ).parsed + + +async def asyncio_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + share_code_id=share_code_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shocker_shares/shares_link_share_code.py b/openshock/rest/api/shocker_shares/shares_link_share_code.py new file mode 100644 index 0000000..a6463ae --- /dev/null +++ b/openshock/rest/api/shocker_shares/shares_link_share_code.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + share_code_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shares/code/{share_code_id}".format( + share_code_id=quote(str(share_code_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if response.status_code == 500: + response_500 = cast(Any, None) + return response_500 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + share_code_id=share_code_id, + client=client, + ).parsed + + +async def asyncio_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + share_code_id=share_code_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shockers/__init__.py b/openshock/rest/api/shockers/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/shockers/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/shockers/shocker_edit_shocker.py b/openshock/rest/api/shockers/shocker_edit_shocker.py new file mode 100644 index 0000000..3138de5 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_edit_shocker.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.new_shocker import NewShocker +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, + *, + body: NewShocker, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/shockers/{shocker_id}".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: NewShocker, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Edit a shocker + + Args: + shocker_id (UUID): + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: NewShocker, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Edit a shocker + + Args: + shocker_id (UUID): + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: NewShocker, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Edit a shocker + + Args: + shocker_id (UUID): + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: NewShocker, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Edit a shocker + + Args: + shocker_id (UUID): + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_get_all_shocker_logs.py b/openshock/rest/api/shockers/shocker_get_all_shocker_logs.py new file mode 100644 index 0000000..f3aa3f2 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_get_all_shocker_logs.py @@ -0,0 +1,249 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paged_result_of_log_entry_with_hub import PagedResultOfLogEntryWithHub +from ...models.sort_direction import SortDirection +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + shocker_ids: list[UUID] | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["page"] = page + + params["pageSize"] = page_size + + params["search"] = search + + params["sort"] = sort + + json_sort_dir: str | Unset = UNSET + if not isinstance(sort_dir, Unset): + json_sort_dir = sort_dir.value + + params["sortDir"] = json_sort_dir + + json_shocker_ids: list[str] | Unset = UNSET + if not isinstance(shocker_ids, Unset): + json_shocker_ids = [] + for shocker_ids_item_data in shocker_ids: + shocker_ids_item = str(shocker_ids_item_data) + json_shocker_ids.append(shocker_ids_item) + + params["shockerIds"] = json_shocker_ids + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shockers/logs", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> PagedResultOfLogEntryWithHub | None: + if response.status_code == 200: + response_200 = PagedResultOfLogEntryWithHub.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[PagedResultOfLogEntryWithHub]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + shocker_ids: list[UUID] | Unset = UNSET, +) -> Response[PagedResultOfLogEntryWithHub]: + """Get a paged set of control logs across the caller's shockers. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + shocker_ids (list[UUID] | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfLogEntryWithHub] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + shocker_ids=shocker_ids, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + shocker_ids: list[UUID] | Unset = UNSET, +) -> PagedResultOfLogEntryWithHub | None: + """Get a paged set of control logs across the caller's shockers. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + shocker_ids (list[UUID] | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfLogEntryWithHub + """ + + return sync_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + shocker_ids=shocker_ids, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + shocker_ids: list[UUID] | Unset = UNSET, +) -> Response[PagedResultOfLogEntryWithHub]: + """Get a paged set of control logs across the caller's shockers. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + shocker_ids (list[UUID] | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfLogEntryWithHub] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + shocker_ids=shocker_ids, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + shocker_ids: list[UUID] | Unset = UNSET, +) -> PagedResultOfLogEntryWithHub | None: + """Get a paged set of control logs across the caller's shockers. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + shocker_ids (list[UUID] | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfLogEntryWithHub + """ + + return ( + await asyncio_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + shocker_ids=shocker_ids, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_get_shocker_by_id.py b/openshock/rest/api/shockers/shocker_get_shocker_by_id.py new file mode 100644 index 0000000..4df67fc --- /dev/null +++ b/openshock/rest/api/shockers/shocker_get_shocker_by_id.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_shocker_with_device import LegacyDataResponseOfShockerWithDevice +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shockers/{shocker_id}".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfShockerWithDevice | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfShockerWithDevice.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfShockerWithDevice | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfShockerWithDevice | OpenShockProblem]: + """Get information about a shocker. + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfShockerWithDevice | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfShockerWithDevice | OpenShockProblem | None: + """Get information about a shocker. + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfShockerWithDevice | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfShockerWithDevice | OpenShockProblem]: + """Get information about a shocker. + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfShockerWithDevice | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfShockerWithDevice | OpenShockProblem | None: + """Get information about a shocker. + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfShockerWithDevice | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_get_shocker_logs.py b/openshock/rest/api/shockers/shocker_get_shocker_logs.py new file mode 100644 index 0000000..2910a9a --- /dev/null +++ b/openshock/rest/api/shockers/shocker_get_shocker_logs.py @@ -0,0 +1,199 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_log_entry import LegacyDataResponseOfArrayOfLogEntry +from ...models.open_shock_problem import OpenShockProblem +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + shocker_id: UUID, + *, + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["offset"] = offset + + params["limit"] = limit + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shockers/{shocker_id}/logs".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfLogEntry.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem]: + """Get the logs for a shocker + + Args: + shocker_id (UUID): + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + offset=offset, + limit=limit, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem | None: + """Get the logs for a shocker + + Args: + shocker_id (UUID): + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + offset=offset, + limit=limit, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem]: + """Get the logs for a shocker + + Args: + shocker_id (UUID): + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + offset=offset, + limit=limit, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem | None: + """Get the logs for a shocker + + Args: + shocker_id (UUID): + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfLogEntry | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + offset=offset, + limit=limit, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_get_user_shares.py b/openshock/rest/api/shockers/shocker_get_user_shares.py new file mode 100644 index 0000000..814b444 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_get_user_shares.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_share_info import LegacyDataResponseOfArrayOfShareInfo +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shockers/{shocker_id}/shares".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfShareInfo.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem]: + """Get all user shares for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem | None: + """Get all user shares for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem]: + """Get all user shares for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem | None: + """Get all user shares for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfShareInfo | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_list_shared_shockers.py b/openshock/rest/api/shockers/shocker_list_shared_shockers.py new file mode 100644 index 0000000..a11c49c --- /dev/null +++ b/openshock/rest/api/shockers/shocker_list_shared_shockers.py @@ -0,0 +1,131 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_owner_shocker_response import ( + LegacyDataResponseOfArrayOfOwnerShockerResponse, +) +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shockers/shared", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfOwnerShockerResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfOwnerShockerResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfOwnerShockerResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfOwnerShockerResponse]: + """List all shockers shared with the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfOwnerShockerResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfOwnerShockerResponse | None: + """List all shockers shared with the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfOwnerShockerResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfOwnerShockerResponse]: + """List all shockers shared with the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfOwnerShockerResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfOwnerShockerResponse | None: + """List all shockers shared with the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfOwnerShockerResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_list_shockers.py b/openshock/rest/api/shockers/shocker_list_shockers.py new file mode 100644 index 0000000..bcb53a5 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_list_shockers.py @@ -0,0 +1,131 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_device_with_shockers_response import ( + LegacyDataResponseOfArrayOfDeviceWithShockersResponse, +) +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shockers/own", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfDeviceWithShockersResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfDeviceWithShockersResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfDeviceWithShockersResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfDeviceWithShockersResponse]: + """List all shockers belonging to the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfDeviceWithShockersResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfDeviceWithShockersResponse | None: + """List all shockers belonging to the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfDeviceWithShockersResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfDeviceWithShockersResponse]: + """List all shockers belonging to the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfDeviceWithShockersResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfDeviceWithShockersResponse | None: + """List all shockers belonging to the authenticated user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfDeviceWithShockersResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_pause_shocker.py b/openshock/rest/api/shockers/shocker_pause_shocker.py new file mode 100644 index 0000000..18271bf --- /dev/null +++ b/openshock/rest/api/shockers/shocker_pause_shocker.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_ofboolean import LegacyDataResponseOfboolean +from ...models.open_shock_problem import OpenShockProblem +from ...models.pause_request import PauseRequest +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, + *, + body: PauseRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shockers/{shocker_id}/pause".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfboolean | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfboolean.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfboolean | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Response[LegacyDataResponseOfboolean | OpenShockProblem]: + """Pause or unpause a shocker + + Args: + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfboolean | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> LegacyDataResponseOfboolean | OpenShockProblem | None: + """Pause or unpause a shocker + + Args: + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfboolean | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Response[LegacyDataResponseOfboolean | OpenShockProblem]: + """Pause or unpause a shocker + + Args: + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfboolean | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> LegacyDataResponseOfboolean | OpenShockProblem | None: + """Pause or unpause a shocker + + Args: + shocker_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfboolean | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_register_shocker.py b/openshock/rest/api/shockers/shocker_register_shocker.py new file mode 100644 index 0000000..a47fff2 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_register_shocker.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_guid import LegacyDataResponseOfGuid +from ...models.new_shocker import NewShocker +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: NewShocker, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shockers", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: + if response.status_code == 201: + response_201 = LegacyDataResponseOfGuid.from_dict(response.json()) + + return response_201 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: NewShocker, +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: + """Register a shocker + + Args: + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfGuid | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: NewShocker, +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: + """Register a shocker + + Args: + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfGuid | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: NewShocker, +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: + """Register a shocker + + Args: + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfGuid | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: NewShocker, +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: + """Register a shocker + + Args: + body (NewShocker): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfGuid | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_remove_shocker.py b/openshock/rest/api/shockers/shocker_remove_shocker.py new file mode 100644 index 0000000..6c4dcc3 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_remove_shocker.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/shockers/{shocker_id}".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Remove a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Remove a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Remove a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Remove a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_send_control.py b/openshock/rest/api/shockers/shocker_send_control.py new file mode 100644 index 0000000..1b55940 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_send_control.py @@ -0,0 +1,177 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.control_request import ControlRequest +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ControlRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/shockers/control", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if response.status_code == 412: + response_412 = OpenShockProblem.from_dict(response.json()) + + return response_412 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ControlRequest, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Send a control message to shockers + + Args: + body (ControlRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ControlRequest, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Send a control message to shockers + + Args: + body (ControlRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ControlRequest, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Send a control message to shockers + + Args: + body (ControlRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ControlRequest, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Send a control message to shockers + + Args: + body (ControlRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_shocker_share_code_create.py b/openshock/rest/api/shockers/shocker_shocker_share_code_create.py new file mode 100644 index 0000000..db4bd4d --- /dev/null +++ b/openshock/rest/api/shockers/shocker_shocker_share_code_create.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_guid import LegacyDataResponseOfGuid +from ...models.open_shock_problem import OpenShockProblem +from ...models.shocker_perm_limit_pair import ShockerPermLimitPair +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, + *, + body: ShockerPermLimitPair, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shockers/{shocker_id}/shares".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfGuid.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: + """Create a share code for a shocker + + Args: + shocker_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfGuid | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: + """Create a share code for a shocker + + Args: + shocker_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfGuid | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: + """Create a share code for a shocker + + Args: + shocker_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfGuid | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: + """Create a share code for a shocker + + Args: + shocker_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfGuid | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_shocker_share_code_list.py b/openshock/rest/api/shockers/shocker_shocker_share_code_list.py new file mode 100644 index 0000000..8d232b0 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_shocker_share_code_list.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_share_code_info import LegacyDataResponseOfArrayOfShareCodeInfo +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/shockers/{shocker_id}/shareCodes".format( + shocker_id=quote(str(shocker_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfShareCodeInfo.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem]: + """List all share codes for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem | None: + """List all share codes for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + client=client, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem]: + """List all share codes for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem | None: + """List all share codes for a shocker + + Args: + shocker_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfArrayOfShareCodeInfo | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_shocker_share_code_pause.py b/openshock/rest/api/shockers/shocker_shocker_share_code_pause.py new file mode 100644 index 0000000..6567354 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_shocker_share_code_pause.py @@ -0,0 +1,198 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_ofboolean import LegacyDataResponseOfboolean +from ...models.open_shock_problem import OpenShockProblem +from ...models.pause_request import PauseRequest +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + body: PauseRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shockers/{shocker_id}/shares/{shared_with_user_id}/pause".format( + shocker_id=quote(str(shocker_id), safe=""), + shared_with_user_id=quote(str(shared_with_user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfboolean | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfboolean.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfboolean | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Response[LegacyDataResponseOfboolean | OpenShockProblem]: + """Pause/Unpause a share code for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfboolean | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> LegacyDataResponseOfboolean | OpenShockProblem | None: + """Pause/Unpause a share code for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfboolean | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> Response[LegacyDataResponseOfboolean | OpenShockProblem]: + """Pause/Unpause a share code for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfboolean | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseRequest, +) -> LegacyDataResponseOfboolean | OpenShockProblem | None: + """Pause/Unpause a share code for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (PauseRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfboolean | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_shocker_share_code_update.py b/openshock/rest/api/shockers/shocker_shocker_share_code_update.py new file mode 100644 index 0000000..9d5d312 --- /dev/null +++ b/openshock/rest/api/shockers/shocker_shocker_share_code_update.py @@ -0,0 +1,196 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.shocker_perm_limit_pair import ShockerPermLimitPair +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + body: ShockerPermLimitPair, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/shockers/{shocker_id}/shares/{shared_with_user_id}".format( + shocker_id=quote(str(shocker_id), safe=""), + shared_with_user_id=quote(str(shared_with_user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> Response[Any | OpenShockProblem]: + """Update a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> Any | OpenShockProblem | None: + """Update a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> Response[Any | OpenShockProblem]: + """Update a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, + body: ShockerPermLimitPair, +) -> Any | OpenShockProblem | None: + """Update a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + body (ShockerPermLimitPair): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/shockers/shocker_shocker_share_remove.py b/openshock/rest/api/shockers/shocker_shocker_share_remove.py new file mode 100644 index 0000000..3aa02cc --- /dev/null +++ b/openshock/rest/api/shockers/shocker_shocker_share_remove.py @@ -0,0 +1,175 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + shocker_id: UUID, + shared_with_user_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/shockers/{shocker_id}/shares/{shared_with_user_id}".format( + shocker_id=quote(str(shocker_id), safe=""), + shared_with_user_id=quote(str(shared_with_user_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Remove a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Remove a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + client=client, + ).parsed + + +async def asyncio_detailed( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Remove a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + shocker_id: UUID, + shared_with_user_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Remove a share for a shocker + + Args: + shocker_id (UUID): + shared_with_user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + shocker_id=shocker_id, + shared_with_user_id=shared_with_user_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/__init__.py b/openshock/rest/api/user_shocker_shares/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/user_shocker_shares/user_shares_bulk_pause_user_share_shockers.py b/openshock/rest/api/user_shocker_shares/user_shares_bulk_pause_user_share_shockers.py new file mode 100644 index 0000000..6b80a0f --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_bulk_pause_user_share_shockers.py @@ -0,0 +1,174 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.pause_user_share_shockers_request import PauseUserShareShockersRequest +from ...models.pause_user_share_shockers_response import PauseUserShareShockersResponse +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: PauseUserShareShockersRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/shares/user/{user_id}/shockers/pause".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> PauseUserShareShockersResponse | None: + if response.status_code == 200: + response_200 = PauseUserShareShockersResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[PauseUserShareShockersResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseUserShareShockersRequest, +) -> Response[PauseUserShareShockersResponse]: + """ + Args: + user_id (UUID): + body (PauseUserShareShockersRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PauseUserShareShockersResponse] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseUserShareShockersRequest, +) -> PauseUserShareShockersResponse | None: + """ + Args: + user_id (UUID): + body (PauseUserShareShockersRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PauseUserShareShockersResponse + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseUserShareShockersRequest, +) -> Response[PauseUserShareShockersResponse]: + """ + Args: + user_id (UUID): + body (PauseUserShareShockersRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PauseUserShareShockersResponse] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: PauseUserShareShockersRequest, +) -> PauseUserShareShockersResponse | None: + """ + Args: + user_id (UUID): + body (PauseUserShareShockersRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PauseUserShareShockersResponse + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_bulk_remove_user_share_shockers.py b/openshock/rest/api/user_shocker_shares/user_shares_bulk_remove_user_share_shockers.py new file mode 100644 index 0000000..c78c3de --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_bulk_remove_user_share_shockers.py @@ -0,0 +1,176 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.remove_user_shares_response import RemoveUserSharesResponse +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: list[UUID], +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/2/shares/user/{user_id}/shockers".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = [] + for body_item_data in body: + body_item = str(body_item_data) + _kwargs["json"].append(body_item) + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> RemoveUserSharesResponse | None: + if response.status_code == 200: + response_200 = RemoveUserSharesResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[RemoveUserSharesResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: list[UUID], +) -> Response[RemoveUserSharesResponse]: + """ + Args: + user_id (UUID): + body (list[UUID]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[RemoveUserSharesResponse] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: list[UUID], +) -> RemoveUserSharesResponse | None: + """ + Args: + user_id (UUID): + body (list[UUID]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + RemoveUserSharesResponse + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: list[UUID], +) -> Response[RemoveUserSharesResponse]: + """ + Args: + user_id (UUID): + body (list[UUID]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[RemoveUserSharesResponse] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: list[UUID], +) -> RemoveUserSharesResponse | None: + """ + Args: + user_id (UUID): + body (list[UUID]): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + RemoveUserSharesResponse + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_bulk_user_share_shockers_update.py b/openshock/rest/api/user_shocker_shares/user_shares_bulk_user_share_shockers_update.py new file mode 100644 index 0000000..af733c4 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_bulk_user_share_shockers_update.py @@ -0,0 +1,182 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.bulk_user_share_shockers_update_request import BulkUserShareShockersUpdateRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: BulkUserShareShockersUpdateRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/2/shares/user/{user_id}/shockers".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: BulkUserShareShockersUpdateRequest, +) -> Response[Any | OpenShockProblem]: + """Update user shares for a shocker + + Args: + user_id (UUID): + body (BulkUserShareShockersUpdateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: BulkUserShareShockersUpdateRequest, +) -> Any | OpenShockProblem | None: + """Update user shares for a shocker + + Args: + user_id (UUID): + body (BulkUserShareShockersUpdateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: BulkUserShareShockersUpdateRequest, +) -> Response[Any | OpenShockProblem]: + """Update user shares for a shocker + + Args: + user_id (UUID): + body (BulkUserShareShockersUpdateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: BulkUserShareShockersUpdateRequest, +) -> Any | OpenShockProblem | None: + """Update user shares for a shocker + + Args: + user_id (UUID): + body (BulkUserShareShockersUpdateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_create_share_invite.py b/openshock/rest/api/user_shocker_shares/user_shares_create_share_invite.py new file mode 100644 index 0000000..490e0b2 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_create_share_invite.py @@ -0,0 +1,168 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.create_share_request import CreateShareRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: CreateShareRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/shares/user/invites", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> OpenShockProblem | UUID | None: + if response.status_code == 200: + response_200 = UUID(response.text) + + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[OpenShockProblem | UUID]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: CreateShareRequest, +) -> Response[OpenShockProblem | UUID]: + """ + Args: + body (CreateShareRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | UUID] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: CreateShareRequest, +) -> OpenShockProblem | UUID | None: + """ + Args: + body (CreateShareRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | UUID + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: CreateShareRequest, +) -> Response[OpenShockProblem | UUID]: + """ + Args: + body (CreateShareRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | UUID] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: CreateShareRequest, +) -> OpenShockProblem | UUID | None: + """ + Args: + body (CreateShareRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | UUID + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_delete_outgoing_invite.py b/openshock/rest/api/user_shocker_shares/user_shares_delete_outgoing_invite.py new file mode 100644 index 0000000..6c1b122 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_delete_outgoing_invite.py @@ -0,0 +1,157 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + invite_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/2/shares/user/invites/outgoing/{invite_id}".format( + invite_id=quote(str(invite_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + invite_id=invite_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + invite_id=invite_id, + client=client, + ).parsed + + +async def asyncio_detailed( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + invite_id=invite_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + invite_id=invite_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_deny_incoming_invite.py b/openshock/rest/api/user_shocker_shares/user_shares_deny_incoming_invite.py new file mode 100644 index 0000000..3a829af --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_deny_incoming_invite.py @@ -0,0 +1,157 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + invite_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/2/shares/user/invites/incoming/{invite_id}".format( + invite_id=quote(str(invite_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + invite_id=invite_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + invite_id=invite_id, + client=client, + ).parsed + + +async def asyncio_detailed( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + invite_id=invite_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + invite_id=invite_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_get_incoming_invites_list.py b/openshock/rest/api/user_shocker_shares/user_shares_get_incoming_invites_list.py new file mode 100644 index 0000000..53e61a9 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_get_incoming_invites_list.py @@ -0,0 +1,130 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.share_invite_base_details import ShareInviteBaseDetails +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/shares/user/invites/incoming", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[ShareInviteBaseDetails] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = ShareInviteBaseDetails.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[ShareInviteBaseDetails]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[ShareInviteBaseDetails]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[ShareInviteBaseDetails]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[ShareInviteBaseDetails] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[ShareInviteBaseDetails] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[ShareInviteBaseDetails]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[ShareInviteBaseDetails]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[ShareInviteBaseDetails] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[ShareInviteBaseDetails] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_get_outgoing_invites_list.py b/openshock/rest/api/user_shocker_shares/user_shares_get_outgoing_invites_list.py new file mode 100644 index 0000000..ef20183 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_get_outgoing_invites_list.py @@ -0,0 +1,130 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.share_invite_base_details import ShareInviteBaseDetails +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/shares/user/invites/outgoing", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[ShareInviteBaseDetails] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = ShareInviteBaseDetails.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[ShareInviteBaseDetails]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[ShareInviteBaseDetails]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[ShareInviteBaseDetails]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[ShareInviteBaseDetails] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[ShareInviteBaseDetails] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[ShareInviteBaseDetails]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[ShareInviteBaseDetails]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[ShareInviteBaseDetails] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[ShareInviteBaseDetails] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_get_shares_by_users.py b/openshock/rest/api/user_shocker_shares/user_shares_get_shares_by_users.py new file mode 100644 index 0000000..3b27ad5 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_get_shares_by_users.py @@ -0,0 +1,121 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.v2_user_shares import V2UserShares +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/shares/user", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> V2UserShares | None: + if response.status_code == 200: + response_200 = V2UserShares.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[V2UserShares]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[V2UserShares]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[V2UserShares] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> V2UserShares | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + V2UserShares + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[V2UserShares]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[V2UserShares] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> V2UserShares | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + V2UserShares + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py b/openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py new file mode 100644 index 0000000..0e71870 --- /dev/null +++ b/openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.v2_user_shares_list_item import V2UserSharesListItem +from ...types import Response + + +def _get_kwargs( + invite_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/shares/user/invites/incoming/{invite_id}".format( + invite_id=quote(str(invite_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> OpenShockProblem | V2UserSharesListItem | None: + if response.status_code == 200: + response_200 = V2UserSharesListItem.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[OpenShockProblem | V2UserSharesListItem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[OpenShockProblem | V2UserSharesListItem]: + """Accept a share request and share the shockers with the current user. + + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | V2UserSharesListItem] + """ + + kwargs = _get_kwargs( + invite_id=invite_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> OpenShockProblem | V2UserSharesListItem | None: + """Accept a share request and share the shockers with the current user. + + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | V2UserSharesListItem + """ + + return sync_detailed( + invite_id=invite_id, + client=client, + ).parsed + + +async def asyncio_detailed( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[OpenShockProblem | V2UserSharesListItem]: + """Accept a share request and share the shockers with the current user. + + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | V2UserSharesListItem] + """ + + kwargs = _get_kwargs( + invite_id=invite_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + invite_id: UUID, + *, + client: AuthenticatedClient, +) -> OpenShockProblem | V2UserSharesListItem | None: + """Accept a share request and share the shockers with the current user. + + Args: + invite_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | V2UserSharesListItem + """ + + return ( + await asyncio_detailed( + invite_id=invite_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/users/__init__.py b/openshock/rest/api/users/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/users/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/users/users_get_by_name.py b/openshock/rest/api/users/users_get_by_name.py new file mode 100644 index 0000000..d6025be --- /dev/null +++ b/openshock/rest/api/users/users_get_by_name.py @@ -0,0 +1,158 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.basic_user_info import BasicUserInfo +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + username: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/users/by-name/{username}".format( + username=quote(str(username), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> BasicUserInfo | OpenShockProblem | None: + if response.status_code == 200: + response_200 = BasicUserInfo.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[BasicUserInfo | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + username: str, + *, + client: AuthenticatedClient, +) -> Response[BasicUserInfo | OpenShockProblem]: + """ + Args: + username (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[BasicUserInfo | OpenShockProblem] + """ + + kwargs = _get_kwargs( + username=username, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + username: str, + *, + client: AuthenticatedClient, +) -> BasicUserInfo | OpenShockProblem | None: + """ + Args: + username (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + BasicUserInfo | OpenShockProblem + """ + + return sync_detailed( + username=username, + client=client, + ).parsed + + +async def asyncio_detailed( + username: str, + *, + client: AuthenticatedClient, +) -> Response[BasicUserInfo | OpenShockProblem]: + """ + Args: + username (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[BasicUserInfo | OpenShockProblem] + """ + + kwargs = _get_kwargs( + username=username, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + username: str, + *, + client: AuthenticatedClient, +) -> BasicUserInfo | OpenShockProblem | None: + """ + Args: + username (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + BasicUserInfo | OpenShockProblem + """ + + return ( + await asyncio_detailed( + username=username, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/users/users_get_self.py b/openshock/rest/api/users/users_get_self.py new file mode 100644 index 0000000..40d3be8 --- /dev/null +++ b/openshock/rest/api/users/users_get_self.py @@ -0,0 +1,129 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_legacy_user_self_response import LegacyDataResponseOfLegacyUserSelfResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/users/self", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfLegacyUserSelfResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfLegacyUserSelfResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfLegacyUserSelfResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfLegacyUserSelfResponse]: + """Get the current user's information. Deprecated: use GET /1/account instead. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfLegacyUserSelfResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfLegacyUserSelfResponse | None: + """Get the current user's information. Deprecated: use GET /1/account instead. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfLegacyUserSelfResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfLegacyUserSelfResponse]: + """Get the current user's information. Deprecated: use GET /1/account instead. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfLegacyUserSelfResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfLegacyUserSelfResponse | None: + """Get the current user's information. Deprecated: use GET /1/account instead. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfLegacyUserSelfResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/users/users_get_self_control_stats.py b/openshock/rest/api/users/users_get_self_control_stats.py new file mode 100644 index 0000000..e8fbccf --- /dev/null +++ b/openshock/rest/api/users/users_get_self_control_stats.py @@ -0,0 +1,204 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +import datetime +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.control_stats_response import ControlStatsResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + tz: str | Unset = UNSET, + from_: datetime.date | Unset = UNSET, + to: datetime.date | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["tz"] = tz + + json_from_: str | Unset = UNSET + if not isinstance(from_, Unset): + json_from_ = from_.isoformat() + params["from"] = json_from_ + + json_to: str | Unset = UNSET + if not isinstance(to, Unset): + json_to = to.isoformat() + params["to"] = json_to + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/users/self/control-stats", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> ControlStatsResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = ControlStatsResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[ControlStatsResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + tz: str | Unset = UNSET, + from_: datetime.date | Unset = UNSET, + to: datetime.date | Unset = UNSET, +) -> Response[ControlStatsResponse | OpenShockProblem]: + """Get control statistics for the current user, both for their own shockers and for controls they sent. + + Args: + tz (str | Unset): + from_ (datetime.date | Unset): + to (datetime.date | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ControlStatsResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + tz=tz, + from_=from_, + to=to, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + tz: str | Unset = UNSET, + from_: datetime.date | Unset = UNSET, + to: datetime.date | Unset = UNSET, +) -> ControlStatsResponse | OpenShockProblem | None: + """Get control statistics for the current user, both for their own shockers and for controls they sent. + + Args: + tz (str | Unset): + from_ (datetime.date | Unset): + to (datetime.date | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ControlStatsResponse | OpenShockProblem + """ + + return sync_detailed( + client=client, + tz=tz, + from_=from_, + to=to, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + tz: str | Unset = UNSET, + from_: datetime.date | Unset = UNSET, + to: datetime.date | Unset = UNSET, +) -> Response[ControlStatsResponse | OpenShockProblem]: + """Get control statistics for the current user, both for their own shockers and for controls they sent. + + Args: + tz (str | Unset): + from_ (datetime.date | Unset): + to (datetime.date | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[ControlStatsResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + tz=tz, + from_=from_, + to=to, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + tz: str | Unset = UNSET, + from_: datetime.date | Unset = UNSET, + to: datetime.date | Unset = UNSET, +) -> ControlStatsResponse | OpenShockProblem | None: + """Get control statistics for the current user, both for their own shockers and for controls they sent. + + Args: + tz (str | Unset): + from_ (datetime.date | Unset): + to (datetime.date | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + ControlStatsResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + tz=tz, + from_=from_, + to=to, + ) + ).parsed diff --git a/openshock/rest/client.py b/openshock/rest/client.py new file mode 100644 index 0000000..5296be5 --- /dev/null +++ b/openshock/rest/client.py @@ -0,0 +1,269 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +import ssl +from typing import Any, Self + +import httpx2 +from attrs import define, evolve, field + + +@define +class Client: + """A class for keeping track of data related to the API + + The following are accepted as keyword arguments and will be used to construct httpx2 Clients internally: + + ``base_url``: The base URL for the API, all requests are made to a relative path to this URL + + ``cookies``: A dictionary of cookies to be sent with every request + + ``headers``: A dictionary of headers to be sent with every request + + ``timeout``: The maximum amount of a time a request can take. API functions will raise + httpx2.TimeoutException if this is exceeded. + + ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production, + but can be set to False for testing purposes. + + ``follow_redirects``: Whether or not to follow redirects. Default value is False. + + ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx2.Client`` and ``httpx2.AsyncClient`` constructor. + + + Attributes: + raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a + status code that was not documented in the source OpenAPI document. Can also be provided as a keyword + argument to the constructor. + """ + + raise_on_unexpected_status: bool = field(default=False, kw_only=True) + _base_url: str = field(alias="base_url") + _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies") + _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers") + _timeout: httpx2.Timeout | None = field(default=None, kw_only=True, alias="timeout") + _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl") + _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects") + _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args") + _client: httpx2.Client | None = field(default=None, init=False) + _async_client: httpx2.AsyncClient | None = field(default=None, init=False) + + def with_headers(self, headers: dict[str, str]) -> "Client": + """Get a new client matching this one with additional headers""" + if self._client is not None: + self._client.headers.update(headers) + if self._async_client is not None: + self._async_client.headers.update(headers) + return evolve(self, headers={**self._headers, **headers}) + + def with_cookies(self, cookies: dict[str, str]) -> "Client": + """Get a new client matching this one with additional cookies""" + if self._client is not None: + self._client.cookies.update(cookies) + if self._async_client is not None: + self._async_client.cookies.update(cookies) + return evolve(self, cookies={**self._cookies, **cookies}) + + def with_timeout(self, timeout: httpx2.Timeout) -> "Client": + """Get a new client matching this one with a new timeout configuration""" + if self._client is not None: + self._client.timeout = timeout + if self._async_client is not None: + self._async_client.timeout = timeout + return evolve(self, timeout=timeout) + + def set_httpx_client(self, client: httpx2.Client) -> Self: + """Manually set the underlying httpx2.Client + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._client = client + return self + + def get_httpx_client(self) -> httpx2.Client: + """Get the underlying httpx2.Client, constructing a new one if not previously set""" + if self._client is None: + self._client = httpx2.Client( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._client + + def __enter__(self) -> Self: + """Enter a context manager for self.client—you cannot enter twice (see httpx2 docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx2.Client (see httpx2 docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx2.AsyncClient) -> Self: + """Manually set the underlying httpx2.AsyncClient + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._async_client = async_client + return self + + def get_async_httpx_client(self) -> httpx2.AsyncClient: + """Get the underlying httpx2.AsyncClient, constructing a new one if not previously set""" + if self._async_client is None: + self._async_client = httpx2.AsyncClient( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._async_client + + async def __aenter__(self) -> Self: + """Enter a context manager for underlying httpx2.AsyncClient—you cannot enter twice (see httpx2 docs)""" + await self.get_async_httpx_client().__aenter__() + return self + + async def __aexit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for underlying httpx2.AsyncClient (see httpx2 docs)""" + await self.get_async_httpx_client().__aexit__(*args, **kwargs) + + +@define +class AuthenticatedClient: + """A Client which has been authenticated for use on secured endpoints + + The following are accepted as keyword arguments and will be used to construct httpx2 Clients internally: + + ``base_url``: The base URL for the API, all requests are made to a relative path to this URL + + ``cookies``: A dictionary of cookies to be sent with every request + + ``headers``: A dictionary of headers to be sent with every request + + ``timeout``: The maximum amount of a time a request can take. API functions will raise + httpx2.TimeoutException if this is exceeded. + + ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production, + but can be set to False for testing purposes. + + ``follow_redirects``: Whether or not to follow redirects. Default value is False. + + ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx2.Client`` and ``httpx2.AsyncClient`` constructor. + + + Attributes: + raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a + status code that was not documented in the source OpenAPI document. Can also be provided as a keyword + argument to the constructor. + token: The token to use for authentication + prefix: The prefix to use for the Authorization header + auth_header_name: The name of the Authorization header + """ + + raise_on_unexpected_status: bool = field(default=False, kw_only=True) + _base_url: str = field(alias="base_url") + _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies") + _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers") + _timeout: httpx2.Timeout | None = field(default=None, kw_only=True, alias="timeout") + _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl") + _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects") + _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args") + _client: httpx2.Client | None = field(default=None, init=False) + _async_client: httpx2.AsyncClient | None = field(default=None, init=False) + + token: str + prefix: str = "Bearer" + auth_header_name: str = "Authorization" + + def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient": + """Get a new client matching this one with additional headers""" + if self._client is not None: + self._client.headers.update(headers) + if self._async_client is not None: + self._async_client.headers.update(headers) + return evolve(self, headers={**self._headers, **headers}) + + def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient": + """Get a new client matching this one with additional cookies""" + if self._client is not None: + self._client.cookies.update(cookies) + if self._async_client is not None: + self._async_client.cookies.update(cookies) + return evolve(self, cookies={**self._cookies, **cookies}) + + def with_timeout(self, timeout: httpx2.Timeout) -> "AuthenticatedClient": + """Get a new client matching this one with a new timeout configuration""" + if self._client is not None: + self._client.timeout = timeout + if self._async_client is not None: + self._async_client.timeout = timeout + return evolve(self, timeout=timeout) + + def set_httpx_client(self, client: httpx2.Client) -> Self: + """Manually set the underlying httpx2.Client + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._client = client + return self + + def get_httpx_client(self) -> httpx2.Client: + """Get the underlying httpx2.Client, constructing a new one if not previously set""" + if self._client is None: + self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token + self._client = httpx2.Client( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._client + + def __enter__(self) -> Self: + """Enter a context manager for self.client—you cannot enter twice (see httpx2 docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx2.Client (see httpx2 docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx2.AsyncClient) -> Self: + """Manually set the underlying httpx2.AsyncClient + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._async_client = async_client + return self + + def get_async_httpx_client(self) -> httpx2.AsyncClient: + """Get the underlying httpx2.AsyncClient, constructing a new one if not previously set""" + if self._async_client is None: + self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token + self._async_client = httpx2.AsyncClient( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._async_client + + async def __aenter__(self) -> Self: + """Enter a context manager for underlying httpx2.AsyncClient—you cannot enter twice (see httpx2 docs)""" + await self.get_async_httpx_client().__aenter__() + return self + + async def __aexit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for underlying httpx2.AsyncClient (see httpx2 docs)""" + await self.get_async_httpx_client().__aexit__(*args, **kwargs) diff --git a/openshock/rest/errors.py b/openshock/rest/errors.py new file mode 100644 index 0000000..ad4f1c1 --- /dev/null +++ b/openshock/rest/errors.py @@ -0,0 +1,17 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains shared errors types that can be raised from API functions""" + + +class UnexpectedStatus(Exception): + """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True""" + + def __init__(self, status_code: int, content: bytes): + self.status_code = status_code + self.content = content + + super().__init__( + f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}" + ) + + +__all__ = ["UnexpectedStatus"] diff --git a/openshock/rest/models/__init__.py b/openshock/rest/models/__init__.py new file mode 100644 index 0000000..ab386b7 --- /dev/null +++ b/openshock/rest/models/__init__.py @@ -0,0 +1,394 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains all the data models used in inputs/outputs""" + +from .add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto +from .add_username_blacklist_dto import AddUsernameBlacklistDto +from .add_webhook_dto import AddWebhookDto +from .admin_online_device_response import AdminOnlineDeviceResponse +from .admin_online_gateway_response import AdminOnlineGatewayResponse +from .admin_user_view import AdminUserView +from .admin_user_view_api_token import AdminUserViewApiToken +from .admin_user_view_email_change import AdminUserViewEmailChange +from .admin_user_view_hub import AdminUserViewHub +from .admin_user_view_name_change import AdminUserViewNameChange +from .admin_user_view_password_reset import AdminUserViewPasswordReset +from .admin_user_view_shocker import AdminUserViewShocker +from .admin_user_view_user_activation_request import AdminUserViewUserActivationRequest +from .admin_user_view_user_deactivation import AdminUserViewUserDeactivation +from .admin_user_view_user_ref import AdminUserViewUserRef +from .admin_users_view import AdminUsersView +from .audit_action import AuditAction +from .audit_log_entry_response import AuditLogEntryResponse +from .audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata +from .audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT +from .audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata +from .audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT +from .audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata +from .audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT +from .audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata +from .audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT +from .audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata +from .audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT +from .audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata +from .audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT +from .audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata +from .audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT +from .audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata +from .audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT +from .audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata +from .audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT +from .audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata +from .audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT +from .audit_metadata_login_metadata import AuditMetadataLoginMetadata +from .audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT +from .audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata +from .audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT +from .audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata +from .audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT +from .audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata +from .audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT +from .automation_token_dto import AutomationTokenDto +from .automation_token_type import AutomationTokenType +from .backend_info_response import BackendInfoResponse +from .basic_user_info import BasicUserInfo +from .bulk_user_share_shockers_update_request import BulkUserShareShockersUpdateRequest +from .change_email_request import ChangeEmailRequest +from .change_password_request import ChangePasswordRequest +from .change_username_request import ChangeUsernameRequest +from .configuration_add_item_request import ConfigurationAddItemRequest +from .configuration_item_dto import ConfigurationItemDto +from .configuration_update_item_request import ConfigurationUpdateItemRequest +from .configuration_value_type import ConfigurationValueType +from .control import Control +from .control_limit_mode import ControlLimitMode +from .control_log_sender_light import ControlLogSenderLight +from .control_request import ControlRequest +from .control_stat_changes_request import ControlStatChangesRequest +from .control_stat_changes_response import ControlStatChangesResponse +from .control_stat_totals import ControlStatTotals +from .control_stats_response import ControlStatsResponse +from .control_type import ControlType +from .create_automation_token_dto import CreateAutomationTokenDto +from .create_share_request import CreateShareRequest +from .create_token_request_v2 import CreateTokenRequestV2 +from .created_automation_token_dto import CreatedAutomationTokenDto +from .daily_control_stats import DailyControlStats +from .device_response import DeviceResponse +from .device_self_response import DeviceSelfResponse +from .device_with_shockers_response import DeviceWithShockersResponse +from .device_with_token_response import DeviceWithTokenResponse +from .duration_limit_settings import DurationLimitSettings +from .edit_token_request_v2 import EditTokenRequestV2 +from .email_outbox_bulk_request import EmailOutboxBulkRequest +from .email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from .email_outbox_message_dto import EmailOutboxMessageDto +from .email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload +from .email_outbox_stats_dto import EmailOutboxStatsDto +from .email_provider_blacklist_dto import EmailProviderBlacklistDto +from .email_status import EmailStatus +from .email_type import EmailType +from .given_control_stats import GivenControlStats +from .hub_create_request import HubCreateRequest +from .hub_edit_request import HubEditRequest +from .intensity_limit_settings import IntensityLimitSettings +from .lcg_node_response_v2 import LcgNodeResponseV2 +from .lcg_response_v2 import LcgResponseV2 +from .legacy_data_response_of_array_of_admin_online_device_response import ( + LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, +) +from .legacy_data_response_of_array_of_device_response import LegacyDataResponseOfArrayOfDeviceResponse +from .legacy_data_response_of_array_of_device_with_shockers_response import ( + LegacyDataResponseOfArrayOfDeviceWithShockersResponse, +) +from .legacy_data_response_of_array_of_log_entry import LegacyDataResponseOfArrayOfLogEntry +from .legacy_data_response_of_array_of_own_public_share_response import ( + LegacyDataResponseOfArrayOfOwnPublicShareResponse, +) +from .legacy_data_response_of_array_of_owner_shocker_response import LegacyDataResponseOfArrayOfOwnerShockerResponse +from .legacy_data_response_of_array_of_share_code_info import LegacyDataResponseOfArrayOfShareCodeInfo +from .legacy_data_response_of_array_of_share_info import LegacyDataResponseOfArrayOfShareInfo +from .legacy_data_response_of_array_of_shocker_response import LegacyDataResponseOfArrayOfShockerResponse +from .legacy_data_response_of_backend_info_response import LegacyDataResponseOfBackendInfoResponse +from .legacy_data_response_of_device_self_response import LegacyDataResponseOfDeviceSelfResponse +from .legacy_data_response_of_device_with_token_response import LegacyDataResponseOfDeviceWithTokenResponse +from .legacy_data_response_of_guid import LegacyDataResponseOfGuid +from .legacy_data_response_of_i_read_only_collection_of_ota_item import LegacyDataResponseOfIReadOnlyCollectionOfOtaItem +from .legacy_data_response_of_legacy_user_self_response import LegacyDataResponseOfLegacyUserSelfResponse +from .legacy_data_response_of_pause_reason import LegacyDataResponseOfPauseReason +from .legacy_data_response_of_public_share_response import LegacyDataResponseOfPublicShareResponse +from .legacy_data_response_of_shocker_with_device import LegacyDataResponseOfShockerWithDevice +from .legacy_data_response_of_stats_response import LegacyDataResponseOfStatsResponse +from .legacy_data_response_ofboolean import LegacyDataResponseOfboolean +from .legacy_data_response_ofstring import LegacyDataResponseOfstring +from .legacy_empty_response import LegacyEmptyResponse +from .legacy_user_self_response import LegacyUserSelfResponse +from .log_entry import LogEntry +from .log_entry_with_hub import LogEntryWithHub +from .login_session_response import LoginSessionResponse +from .login_v2 import LoginV2 +from .login_v2_ok_response import LoginV2OkResponse +from .match_type_enum import MatchTypeEnum +from .minimal_shocker import MinimalShocker +from .new_shocker import NewShocker +from .o_auth_connection_response import OAuthConnectionResponse +from .open_shock_problem import OpenShockProblem +from .ota_item import OtaItem +from .ota_update_status import OtaUpdateStatus +from .own_public_share_response import OwnPublicShareResponse +from .owner_shocker_response import OwnerShockerResponse +from .paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse +from .paged_result_of_log_entry_with_hub import PagedResultOfLogEntryWithHub +from .paginated_of_admin_users_view import PaginatedOfAdminUsersView +from .paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto +from .password_hashing_algorithm import PasswordHashingAlgorithm +from .password_reset_process_data import PasswordResetProcessData +from .password_reset_request_v2 import PasswordResetRequestV2 +from .patch_automation_token_dto import PatchAutomationTokenDto +from .pause_request import PauseRequest +from .pause_user_share_shockers_request import PauseUserShareShockersRequest +from .pause_user_share_shockers_response import PauseUserShareShockersResponse +from .pause_user_share_shockers_response_pause_states import PauseUserShareShockersResponsePauseStates +from .permission_type import PermissionType +from .problem_details import ProblemDetails +from .public_share_create import PublicShareCreate +from .public_share_device import PublicShareDevice +from .public_share_edit_shocker import PublicShareEditShocker +from .public_share_response import PublicShareResponse +from .public_share_shocker import PublicShareShocker +from .received_control_stats import ReceivedControlStats +from .remove_user_shares_response import RemoveUserSharesResponse +from .report_tokens_request import ReportTokensRequest +from .role_type import RoleType +from .send_test_email_dto import SendTestEmailDto +from .set_token_paused_request import SetTokenPausedRequest +from .set_user_email_request_body import SetUserEmailRequestBody +from .set_user_name_request_body import SetUserNameRequestBody +from .set_user_password_request_body import SetUserPasswordRequestBody +from .share_code_info import ShareCodeInfo +from .share_info import ShareInfo +from .share_invite_base_details import ShareInviteBaseDetails +from .shared_device import SharedDevice +from .shared_shocker import SharedShocker +from .shocker_control_settings import ShockerControlSettings +from .shocker_control_stats import ShockerControlStats +from .shocker_limits import ShockerLimits +from .shocker_model_type import ShockerModelType +from .shocker_perm_limit_pair import ShockerPermLimitPair +from .shocker_perm_limit_pair_with_id import ShockerPermLimitPairWithId +from .shocker_perm_limit_pair_with_id_and_name import ShockerPermLimitPairWithIdAndName +from .shocker_permissions import ShockerPermissions +from .shocker_response import ShockerResponse +from .shocker_with_device import ShockerWithDevice +from .sign_up_v2 import SignUpV2 +from .sort_direction import SortDirection +from .stats_response import StatsResponse +from .token_created_response_v2 import TokenCreatedResponseV2 +from .token_paused_response import TokenPausedResponse +from .token_response_v2 import TokenResponseV2 +from .user_control_stat_totals import UserControlStatTotals +from .user_control_stats import UserControlStats +from .user_name_blacklist_dto import UserNameBlacklistDto +from .user_patch_dto import UserPatchDto +from .user_self_response import UserSelfResponse +from .user_share_info import UserShareInfo +from .username_availability import UsernameAvailability +from .username_check_response import UsernameCheckResponse +from .username_error import UsernameError +from .username_error_type import UsernameErrorType +from .v2_user_shares import V2UserShares +from .v2_user_shares_list_item import V2UserSharesListItem +from .webhook_dto import WebhookDto + +__all__ = ( + "AddEmailProviderBlacklistDto", + "AddUsernameBlacklistDto", + "AddWebhookDto", + "AdminOnlineDeviceResponse", + "AdminOnlineGatewayResponse", + "AdminUsersView", + "AdminUserView", + "AdminUserViewApiToken", + "AdminUserViewEmailChange", + "AdminUserViewHub", + "AdminUserViewNameChange", + "AdminUserViewPasswordReset", + "AdminUserViewShocker", + "AdminUserViewUserActivationRequest", + "AdminUserViewUserDeactivation", + "AdminUserViewUserRef", + "AuditAction", + "AuditLogEntryResponse", + "AuditMetadataAccountDeactivatedMetadata", + "AuditMetadataAccountDeactivatedMetadataT", + "AuditMetadataApiTokenCreatedMetadata", + "AuditMetadataApiTokenCreatedMetadataT", + "AuditMetadataApiTokenDeletedMetadata", + "AuditMetadataApiTokenDeletedMetadataT", + "AuditMetadataAutomationTokenCreatedMetadata", + "AuditMetadataAutomationTokenCreatedMetadataT", + "AuditMetadataAutomationTokenDeletedMetadata", + "AuditMetadataAutomationTokenDeletedMetadataT", + "AuditMetadataAutomationTokenRotatedMetadata", + "AuditMetadataAutomationTokenRotatedMetadataT", + "AuditMetadataAutomationTokenUpdatedMetadata", + "AuditMetadataAutomationTokenUpdatedMetadataT", + "AuditMetadataAutomationTokenUsedMetadata", + "AuditMetadataAutomationTokenUsedMetadataT", + "AuditMetadataEmailChangedMetadata", + "AuditMetadataEmailChangedMetadataT", + "AuditMetadataEmailChangeRequestedMetadata", + "AuditMetadataEmailChangeRequestedMetadataT", + "AuditMetadataLoginMetadata", + "AuditMetadataLoginMetadataT", + "AuditMetadataOAuthConnectedMetadata", + "AuditMetadataOAuthConnectedMetadataT", + "AuditMetadataOAuthDisconnectedMetadata", + "AuditMetadataOAuthDisconnectedMetadataT", + "AuditMetadataUsernameChangedMetadata", + "AuditMetadataUsernameChangedMetadataT", + "AutomationTokenDto", + "AutomationTokenType", + "BackendInfoResponse", + "BasicUserInfo", + "BulkUserShareShockersUpdateRequest", + "ChangeEmailRequest", + "ChangePasswordRequest", + "ChangeUsernameRequest", + "ConfigurationAddItemRequest", + "ConfigurationItemDto", + "ConfigurationUpdateItemRequest", + "ConfigurationValueType", + "Control", + "ControlLimitMode", + "ControlLogSenderLight", + "ControlRequest", + "ControlStatChangesRequest", + "ControlStatChangesResponse", + "ControlStatsResponse", + "ControlStatTotals", + "ControlType", + "CreateAutomationTokenDto", + "CreatedAutomationTokenDto", + "CreateShareRequest", + "CreateTokenRequestV2", + "DailyControlStats", + "DeviceResponse", + "DeviceSelfResponse", + "DeviceWithShockersResponse", + "DeviceWithTokenResponse", + "DurationLimitSettings", + "EditTokenRequestV2", + "EmailOutboxBulkRequest", + "EmailOutboxBulkResultDto", + "EmailOutboxMessageDto", + "EmailOutboxMessageDtoPayload", + "EmailOutboxStatsDto", + "EmailProviderBlacklistDto", + "EmailStatus", + "EmailType", + "GivenControlStats", + "HubCreateRequest", + "HubEditRequest", + "IntensityLimitSettings", + "LcgNodeResponseV2", + "LcgResponseV2", + "LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse", + "LegacyDataResponseOfArrayOfDeviceResponse", + "LegacyDataResponseOfArrayOfDeviceWithShockersResponse", + "LegacyDataResponseOfArrayOfLogEntry", + "LegacyDataResponseOfArrayOfOwnerShockerResponse", + "LegacyDataResponseOfArrayOfOwnPublicShareResponse", + "LegacyDataResponseOfArrayOfShareCodeInfo", + "LegacyDataResponseOfArrayOfShareInfo", + "LegacyDataResponseOfArrayOfShockerResponse", + "LegacyDataResponseOfBackendInfoResponse", + "LegacyDataResponseOfboolean", + "LegacyDataResponseOfDeviceSelfResponse", + "LegacyDataResponseOfDeviceWithTokenResponse", + "LegacyDataResponseOfGuid", + "LegacyDataResponseOfIReadOnlyCollectionOfOtaItem", + "LegacyDataResponseOfLegacyUserSelfResponse", + "LegacyDataResponseOfPauseReason", + "LegacyDataResponseOfPublicShareResponse", + "LegacyDataResponseOfShockerWithDevice", + "LegacyDataResponseOfStatsResponse", + "LegacyDataResponseOfstring", + "LegacyEmptyResponse", + "LegacyUserSelfResponse", + "LogEntry", + "LogEntryWithHub", + "LoginSessionResponse", + "LoginV2", + "LoginV2OkResponse", + "MatchTypeEnum", + "MinimalShocker", + "NewShocker", + "OAuthConnectionResponse", + "OpenShockProblem", + "OtaItem", + "OtaUpdateStatus", + "OwnerShockerResponse", + "OwnPublicShareResponse", + "PagedResultOfAuditLogEntryResponse", + "PagedResultOfLogEntryWithHub", + "PaginatedOfAdminUsersView", + "PaginatedOfEmailOutboxMessageDto", + "PasswordHashingAlgorithm", + "PasswordResetProcessData", + "PasswordResetRequestV2", + "PatchAutomationTokenDto", + "PauseRequest", + "PauseUserShareShockersRequest", + "PauseUserShareShockersResponse", + "PauseUserShareShockersResponsePauseStates", + "PermissionType", + "ProblemDetails", + "PublicShareCreate", + "PublicShareDevice", + "PublicShareEditShocker", + "PublicShareResponse", + "PublicShareShocker", + "ReceivedControlStats", + "RemoveUserSharesResponse", + "ReportTokensRequest", + "RoleType", + "SendTestEmailDto", + "SetTokenPausedRequest", + "SetUserEmailRequestBody", + "SetUserNameRequestBody", + "SetUserPasswordRequestBody", + "ShareCodeInfo", + "SharedDevice", + "SharedShocker", + "ShareInfo", + "ShareInviteBaseDetails", + "ShockerControlSettings", + "ShockerControlStats", + "ShockerLimits", + "ShockerModelType", + "ShockerPermissions", + "ShockerPermLimitPair", + "ShockerPermLimitPairWithId", + "ShockerPermLimitPairWithIdAndName", + "ShockerResponse", + "ShockerWithDevice", + "SignUpV2", + "SortDirection", + "StatsResponse", + "TokenCreatedResponseV2", + "TokenPausedResponse", + "TokenResponseV2", + "UserControlStats", + "UserControlStatTotals", + "UsernameAvailability", + "UserNameBlacklistDto", + "UsernameCheckResponse", + "UsernameError", + "UsernameErrorType", + "UserPatchDto", + "UserSelfResponse", + "UserShareInfo", + "V2UserShares", + "V2UserSharesListItem", + "WebhookDto", +) diff --git a/openshock/rest/models/add_email_provider_blacklist_dto.py b/openshock/rest/models/add_email_provider_blacklist_dto.py new file mode 100644 index 0000000..fb17ea7 --- /dev/null +++ b/openshock/rest/models/add_email_provider_blacklist_dto.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AddEmailProviderBlacklistDto") + + +@_attrs_define +class AddEmailProviderBlacklistDto: + """ + Attributes: + domains (list[str]): + """ + + domains: list[str] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + domains = self.domains + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "domains": domains, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + domains = cast(list[str], d.pop("domains")) + + add_email_provider_blacklist_dto = cls( + domains=domains, + ) + + add_email_provider_blacklist_dto.additional_properties = d + return add_email_provider_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/add_username_blacklist_dto.py b/openshock/rest/models/add_username_blacklist_dto.py new file mode 100644 index 0000000..e962cb9 --- /dev/null +++ b/openshock/rest/models/add_username_blacklist_dto.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.match_type_enum import MatchTypeEnum + +T = TypeVar("T", bound="AddUsernameBlacklistDto") + + +@_attrs_define +class AddUsernameBlacklistDto: + """ + Attributes: + value (str): + match_type (MatchTypeEnum): + """ + + value: str + match_type: MatchTypeEnum + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + value = self.value + + match_type = self.match_type.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "value": value, + "matchType": match_type, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + value = d.pop("value") + + match_type = MatchTypeEnum(d.pop("matchType")) + + add_username_blacklist_dto = cls( + value=value, + match_type=match_type, + ) + + add_username_blacklist_dto.additional_properties = d + return add_username_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/add_webhook_dto.py b/openshock/rest/models/add_webhook_dto.py new file mode 100644 index 0000000..de3ff55 --- /dev/null +++ b/openshock/rest/models/add_webhook_dto.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AddWebhookDto") + + +@_attrs_define +class AddWebhookDto: + """ + Attributes: + name (str): + url (str): + """ + + name: str + url: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + url = self.url + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "url": url, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + url = d.pop("url") + + add_webhook_dto = cls( + name=name, + url=url, + ) + + add_webhook_dto.additional_properties = d + return add_webhook_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_device_response.py b/openshock/rest/models/admin_online_device_response.py new file mode 100644 index 0000000..5a60cd5 --- /dev/null +++ b/openshock/rest/models/admin_online_device_response.py @@ -0,0 +1,216 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.basic_user_info import BasicUserInfo + + +T = TypeVar("T", bound="AdminOnlineDeviceResponse") + + +@_attrs_define +class AdminOnlineDeviceResponse: + """ + Attributes: + id (UUID): + name (str): + owner (BasicUserInfo): + firmware_version (str): + gateway (str): + connected_at (datetime.datetime): + user_agent (None | str): + booted_at (datetime.datetime): + latency_ms (int | None): + rssi (int | None): + country (None | str): + ip (None | str): An IPv4 or IPv6 address in its textual form. + asn (int | None): + asn_org (None | str): + """ + + id: UUID + name: str + owner: BasicUserInfo + firmware_version: str + gateway: str + connected_at: datetime.datetime + user_agent: None | str + booted_at: datetime.datetime + latency_ms: int | None + rssi: int | None + country: None | str + ip: None | str + asn: int | None + asn_org: None | str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + owner = self.owner.to_dict() + + firmware_version = self.firmware_version + + gateway = self.gateway + + connected_at = self.connected_at.isoformat() + + user_agent: None | str + user_agent = self.user_agent + + booted_at = self.booted_at.isoformat() + + latency_ms: int | None + latency_ms = self.latency_ms + + rssi: int | None + rssi = self.rssi + + country: None | str + country = self.country + + ip: None | str + ip = self.ip + + asn: int | None + asn = self.asn + + asn_org: None | str + asn_org = self.asn_org + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "owner": owner, + "firmwareVersion": firmware_version, + "gateway": gateway, + "connectedAt": connected_at, + "userAgent": user_agent, + "bootedAt": booted_at, + "latencyMs": latency_ms, + "rssi": rssi, + "country": country, + "ip": ip, + "asn": asn, + "asnOrg": asn_org, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + owner = BasicUserInfo.from_dict(d.pop("owner")) + + firmware_version = d.pop("firmwareVersion") + + gateway = d.pop("gateway") + + connected_at = datetime.datetime.fromisoformat(d.pop("connectedAt")) + + def _parse_user_agent(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + user_agent = _parse_user_agent(d.pop("userAgent")) + + booted_at = datetime.datetime.fromisoformat(d.pop("bootedAt")) + + def _parse_latency_ms(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + latency_ms = _parse_latency_ms(d.pop("latencyMs")) + + def _parse_rssi(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + rssi = _parse_rssi(d.pop("rssi")) + + def _parse_country(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + country = _parse_country(d.pop("country")) + + def _parse_ip(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + ip = _parse_ip(d.pop("ip")) + + def _parse_asn(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + asn = _parse_asn(d.pop("asn")) + + def _parse_asn_org(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + asn_org = _parse_asn_org(d.pop("asnOrg")) + + admin_online_device_response = cls( + id=id, + name=name, + owner=owner, + firmware_version=firmware_version, + gateway=gateway, + connected_at=connected_at, + user_agent=user_agent, + booted_at=booted_at, + latency_ms=latency_ms, + rssi=rssi, + country=country, + ip=ip, + asn=asn, + asn_org=asn_org, + ) + + admin_online_device_response.additional_properties = d + return admin_online_device_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_gateway_response.py b/openshock/rest/models/admin_online_gateway_response.py new file mode 100644 index 0000000..e4452ad --- /dev/null +++ b/openshock/rest/models/admin_online_gateway_response.py @@ -0,0 +1,146 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminOnlineGatewayResponse") + + +@_attrs_define +class AdminOnlineGatewayResponse: + """ + Attributes: + id (str): + host (str): + port (int): + path_prefix (str): + country (str): + latitude (float | None): + longitude (float | None): + load (int): Load the gateway advertises for hub assignment, in percent + environment (str): + connected_hubs (int): + """ + + id: str + host: str + port: int + path_prefix: str + country: str + latitude: float | None + longitude: float | None + load: int + environment: str + connected_hubs: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = self.id + + host = self.host + + port = self.port + + path_prefix = self.path_prefix + + country = self.country + + latitude: float | None + latitude = self.latitude + + longitude: float | None + longitude = self.longitude + + load = self.load + + environment = self.environment + + connected_hubs = self.connected_hubs + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "host": host, + "port": port, + "pathPrefix": path_prefix, + "country": country, + "latitude": latitude, + "longitude": longitude, + "load": load, + "environment": environment, + "connectedHubs": connected_hubs, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = d.pop("id") + + host = d.pop("host") + + port = d.pop("port") + + path_prefix = d.pop("pathPrefix") + + country = d.pop("country") + + def _parse_latitude(data: object) -> float | None: + if data is None: + return data + return cast(float | None, data) + + latitude = _parse_latitude(d.pop("latitude")) + + def _parse_longitude(data: object) -> float | None: + if data is None: + return data + return cast(float | None, data) + + longitude = _parse_longitude(d.pop("longitude")) + + load = d.pop("load") + + environment = d.pop("environment") + + connected_hubs = d.pop("connectedHubs") + + admin_online_gateway_response = cls( + id=id, + host=host, + port=port, + path_prefix=path_prefix, + country=country, + latitude=latitude, + longitude=longitude, + load=load, + environment=environment, + connected_hubs=connected_hubs, + ) + + admin_online_gateway_response.additional_properties = d + return admin_online_gateway_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view.py b/openshock/rest/models/admin_user_view.py new file mode 100644 index 0000000..f173c58 --- /dev/null +++ b/openshock/rest/models/admin_user_view.py @@ -0,0 +1,324 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.password_hashing_algorithm import PasswordHashingAlgorithm +from ..models.role_type import RoleType + +if TYPE_CHECKING: + from ..models.admin_user_view_api_token import AdminUserViewApiToken + from ..models.admin_user_view_email_change import AdminUserViewEmailChange + from ..models.admin_user_view_hub import AdminUserViewHub + from ..models.admin_user_view_name_change import AdminUserViewNameChange + from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset + from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest + from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation + + +T = TypeVar("T", bound="AdminUserView") + + +@_attrs_define +class AdminUserView: + """ + Attributes: + id (UUID): + name (str): + email (str): + password_hash_type (PasswordHashingAlgorithm): + roles (list[RoleType]): + created_at (datetime.datetime): + activated_at (datetime.datetime | None): + created_by_automation_token_id (None | UUID): + activation_request (AdminUserViewUserActivationRequest | None): + deactivation (AdminUserViewUserDeactivation | None): + hubs (list[AdminUserViewHub]): + api_tokens (list[AdminUserViewApiToken]): + users_name_changes (list[AdminUserViewNameChange]): + users_email_changes (list[AdminUserViewEmailChange]): + password_resets (list[AdminUserViewPasswordReset]): + shocker_control_logs_count (int): + """ + + id: UUID + name: str + email: str + password_hash_type: PasswordHashingAlgorithm + roles: list[RoleType] + created_at: datetime.datetime + activated_at: datetime.datetime | None + created_by_automation_token_id: None | UUID + activation_request: AdminUserViewUserActivationRequest | None + deactivation: AdminUserViewUserDeactivation | None + hubs: list[AdminUserViewHub] + api_tokens: list[AdminUserViewApiToken] + users_name_changes: list[AdminUserViewNameChange] + users_email_changes: list[AdminUserViewEmailChange] + password_resets: list[AdminUserViewPasswordReset] + shocker_control_logs_count: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 + from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 + + id = str(self.id) + + name = self.name + + email = self.email + + password_hash_type = self.password_hash_type.value + + roles = [] + for roles_item_data in self.roles: + roles_item = roles_item_data.value + roles.append(roles_item) + + created_at = self.created_at.isoformat() + + activated_at: None | str + if isinstance(self.activated_at, datetime.datetime): + activated_at = self.activated_at.isoformat() + else: + activated_at = self.activated_at + + created_by_automation_token_id: None | str + if isinstance(self.created_by_automation_token_id, UUID): + created_by_automation_token_id = str(self.created_by_automation_token_id) + else: + created_by_automation_token_id = self.created_by_automation_token_id + + activation_request: dict[str, Any] | None + if isinstance(self.activation_request, AdminUserViewUserActivationRequest): + activation_request = self.activation_request.to_dict() + else: + activation_request = self.activation_request + + deactivation: dict[str, Any] | None + if isinstance(self.deactivation, AdminUserViewUserDeactivation): + deactivation = self.deactivation.to_dict() + else: + deactivation = self.deactivation + + hubs = [] + for hubs_item_data in self.hubs: + hubs_item = hubs_item_data.to_dict() + hubs.append(hubs_item) + + api_tokens = [] + for api_tokens_item_data in self.api_tokens: + api_tokens_item = api_tokens_item_data.to_dict() + api_tokens.append(api_tokens_item) + + users_name_changes = [] + for users_name_changes_item_data in self.users_name_changes: + users_name_changes_item = users_name_changes_item_data.to_dict() + users_name_changes.append(users_name_changes_item) + + users_email_changes = [] + for users_email_changes_item_data in self.users_email_changes: + users_email_changes_item = users_email_changes_item_data.to_dict() + users_email_changes.append(users_email_changes_item) + + password_resets = [] + for password_resets_item_data in self.password_resets: + password_resets_item = password_resets_item_data.to_dict() + password_resets.append(password_resets_item) + + shocker_control_logs_count = self.shocker_control_logs_count + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "email": email, + "passwordHashType": password_hash_type, + "roles": roles, + "createdAt": created_at, + "activatedAt": activated_at, + "createdByAutomationTokenId": created_by_automation_token_id, + "activationRequest": activation_request, + "deactivation": deactivation, + "hubs": hubs, + "apiTokens": api_tokens, + "usersNameChanges": users_name_changes, + "usersEmailChanges": users_email_changes, + "passwordResets": password_resets, + "shockerControlLogsCount": shocker_control_logs_count, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_user_view_api_token import AdminUserViewApiToken # noqa: PLC0415 + from ..models.admin_user_view_email_change import AdminUserViewEmailChange # noqa: PLC0415 + from ..models.admin_user_view_hub import AdminUserViewHub # noqa: PLC0415 + from ..models.admin_user_view_name_change import AdminUserViewNameChange # noqa: PLC0415 + from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset # noqa: PLC0415 + from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 + from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + email = d.pop("email") + + password_hash_type = PasswordHashingAlgorithm(d.pop("passwordHashType")) + + roles = [] + _roles = d.pop("roles") + for roles_item_data in _roles: + roles_item = RoleType(roles_item_data) + + roles.append(roles_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_activated_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + activated_at_type_1 = datetime.datetime.fromisoformat(data) + + return activated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + activated_at = _parse_activated_at(d.pop("activatedAt")) + + def _parse_created_by_automation_token_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + created_by_automation_token_id_type_1 = UUID(data) + + return created_by_automation_token_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) + + def _parse_activation_request(data: object) -> AdminUserViewUserActivationRequest | None: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + activation_request_type_1 = AdminUserViewUserActivationRequest.from_dict(data) + + return activation_request_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(AdminUserViewUserActivationRequest | None, data) + + activation_request = _parse_activation_request(d.pop("activationRequest")) + + def _parse_deactivation(data: object) -> AdminUserViewUserDeactivation | None: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + deactivation_type_1 = AdminUserViewUserDeactivation.from_dict(data) + + return deactivation_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(AdminUserViewUserDeactivation | None, data) + + deactivation = _parse_deactivation(d.pop("deactivation")) + + hubs = [] + _hubs = d.pop("hubs") + for hubs_item_data in _hubs: + hubs_item = AdminUserViewHub.from_dict(hubs_item_data) + + hubs.append(hubs_item) + + api_tokens = [] + _api_tokens = d.pop("apiTokens") + for api_tokens_item_data in _api_tokens: + api_tokens_item = AdminUserViewApiToken.from_dict(api_tokens_item_data) + + api_tokens.append(api_tokens_item) + + users_name_changes = [] + _users_name_changes = d.pop("usersNameChanges") + for users_name_changes_item_data in _users_name_changes: + users_name_changes_item = AdminUserViewNameChange.from_dict(users_name_changes_item_data) + + users_name_changes.append(users_name_changes_item) + + users_email_changes = [] + _users_email_changes = d.pop("usersEmailChanges") + for users_email_changes_item_data in _users_email_changes: + users_email_changes_item = AdminUserViewEmailChange.from_dict(users_email_changes_item_data) + + users_email_changes.append(users_email_changes_item) + + password_resets = [] + _password_resets = d.pop("passwordResets") + for password_resets_item_data in _password_resets: + password_resets_item = AdminUserViewPasswordReset.from_dict(password_resets_item_data) + + password_resets.append(password_resets_item) + + shocker_control_logs_count = d.pop("shockerControlLogsCount") + + admin_user_view = cls( + id=id, + name=name, + email=email, + password_hash_type=password_hash_type, + roles=roles, + created_at=created_at, + activated_at=activated_at, + created_by_automation_token_id=created_by_automation_token_id, + activation_request=activation_request, + deactivation=deactivation, + hubs=hubs, + api_tokens=api_tokens, + users_name_changes=users_name_changes, + users_email_changes=users_email_changes, + password_resets=password_resets, + shocker_control_logs_count=shocker_control_logs_count, + ) + + admin_user_view.additional_properties = d + return admin_user_view + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_api_token.py b/openshock/rest/models/admin_user_view_api_token.py new file mode 100644 index 0000000..ca254d6 --- /dev/null +++ b/openshock/rest/models/admin_user_view_api_token.py @@ -0,0 +1,156 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType + +T = TypeVar("T", bound="AdminUserViewApiToken") + + +@_attrs_define +class AdminUserViewApiToken: + """ + Attributes: + id (UUID): + name (str): + permissions (list[PermissionType]): + valid_until (datetime.datetime | None): + last_used (datetime.datetime | None): + created_at (datetime.datetime): + created_by_ip (str): An IPv4 or IPv6 address in its textual form. + """ + + id: UUID + name: str + permissions: list[PermissionType] + valid_until: datetime.datetime | None + last_used: datetime.datetime | None + created_at: datetime.datetime + created_by_ip: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + valid_until: None | str + if isinstance(self.valid_until, datetime.datetime): + valid_until = self.valid_until.isoformat() + else: + valid_until = self.valid_until + + last_used: None | str + if isinstance(self.last_used, datetime.datetime): + last_used = self.last_used.isoformat() + else: + last_used = self.last_used + + created_at = self.created_at.isoformat() + + created_by_ip = self.created_by_ip + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "permissions": permissions, + "validUntil": valid_until, + "lastUsed": last_used, + "createdAt": created_at, + "createdByIp": created_by_ip, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + def _parse_valid_until(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + valid_until_type_1 = datetime.datetime.fromisoformat(data) + + return valid_until_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + valid_until = _parse_valid_until(d.pop("validUntil")) + + def _parse_last_used(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + last_used = _parse_last_used(d.pop("lastUsed")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + created_by_ip = d.pop("createdByIp") + + admin_user_view_api_token = cls( + id=id, + name=name, + permissions=permissions, + valid_until=valid_until, + last_used=last_used, + created_at=created_at, + created_by_ip=created_by_ip, + ) + + admin_user_view_api_token.additional_properties = d + return admin_user_view_api_token + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_email_change.py b/openshock/rest/models/admin_user_view_email_change.py new file mode 100644 index 0000000..a43a754 --- /dev/null +++ b/openshock/rest/models/admin_user_view_email_change.py @@ -0,0 +1,105 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewEmailChange") + + +@_attrs_define +class AdminUserViewEmailChange: + """ + Attributes: + id (UUID): + email (str): + created_at (datetime.datetime): + used_at (datetime.datetime | None): + """ + + id: UUID + email: str + created_at: datetime.datetime + used_at: datetime.datetime | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + email = self.email + + created_at = self.created_at.isoformat() + + used_at: None | str + if isinstance(self.used_at, datetime.datetime): + used_at = self.used_at.isoformat() + else: + used_at = self.used_at + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "email": email, + "createdAt": created_at, + "usedAt": used_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + email = d.pop("email") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_used_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + used_at_type_1 = datetime.datetime.fromisoformat(data) + + return used_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + used_at = _parse_used_at(d.pop("usedAt")) + + admin_user_view_email_change = cls( + id=id, + email=email, + created_at=created_at, + used_at=used_at, + ) + + admin_user_view_email_change.additional_properties = d + return admin_user_view_email_change + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_hub.py b/openshock/rest/models/admin_user_view_hub.py new file mode 100644 index 0000000..e7620b7 --- /dev/null +++ b/openshock/rest/models/admin_user_view_hub.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_user_view_shocker import AdminUserViewShocker + + +T = TypeVar("T", bound="AdminUserViewHub") + + +@_attrs_define +class AdminUserViewHub: + """ + Attributes: + id (UUID): + name (str): + created_at (datetime.datetime): + shockers (list[AdminUserViewShocker]): + """ + + id: UUID + name: str + created_at: datetime.datetime + shockers: list[AdminUserViewShocker] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_at = self.created_at.isoformat() + + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdAt": created_at, + "shockers": shockers, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_user_view_shocker import AdminUserViewShocker # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = AdminUserViewShocker.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + admin_user_view_hub = cls( + id=id, + name=name, + created_at=created_at, + shockers=shockers, + ) + + admin_user_view_hub.additional_properties = d + return admin_user_view_hub + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_name_change.py b/openshock/rest/models/admin_user_view_name_change.py new file mode 100644 index 0000000..00eb2fb --- /dev/null +++ b/openshock/rest/models/admin_user_view_name_change.py @@ -0,0 +1,79 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewNameChange") + + +@_attrs_define +class AdminUserViewNameChange: + """ + Attributes: + id (int): + old_name (str): + created_at (datetime.datetime): + """ + + id: int + old_name: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = self.id + + old_name = self.old_name + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "oldName": old_name, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = d.pop("id") + + old_name = d.pop("oldName") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + admin_user_view_name_change = cls( + id=id, + old_name=old_name, + created_at=created_at, + ) + + admin_user_view_name_change.additional_properties = d + return admin_user_view_name_change + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_password_reset.py b/openshock/rest/models/admin_user_view_password_reset.py new file mode 100644 index 0000000..4f0cc60 --- /dev/null +++ b/openshock/rest/models/admin_user_view_password_reset.py @@ -0,0 +1,97 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewPasswordReset") + + +@_attrs_define +class AdminUserViewPasswordReset: + """ + Attributes: + id (UUID): + created_at (datetime.datetime): + used_at (datetime.datetime | None): + """ + + id: UUID + created_at: datetime.datetime + used_at: datetime.datetime | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + created_at = self.created_at.isoformat() + + used_at: None | str + if isinstance(self.used_at, datetime.datetime): + used_at = self.used_at.isoformat() + else: + used_at = self.used_at + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "createdAt": created_at, + "usedAt": used_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_used_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + used_at_type_1 = datetime.datetime.fromisoformat(data) + + return used_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + used_at = _parse_used_at(d.pop("usedAt")) + + admin_user_view_password_reset = cls( + id=id, + created_at=created_at, + used_at=used_at, + ) + + admin_user_view_password_reset.additional_properties = d + return admin_user_view_password_reset + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_shocker.py b/openshock/rest/models/admin_user_view_shocker.py new file mode 100644 index 0000000..996decd --- /dev/null +++ b/openshock/rest/models/admin_user_view_shocker.py @@ -0,0 +1,80 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewShocker") + + +@_attrs_define +class AdminUserViewShocker: + """ + Attributes: + id (UUID): + name (str): + created_at (datetime.datetime): + """ + + id: UUID + name: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + admin_user_view_shocker = cls( + id=id, + name=name, + created_at=created_at, + ) + + admin_user_view_shocker.additional_properties = d + return admin_user_view_shocker + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_activation_request.py b/openshock/rest/models/admin_user_view_user_activation_request.py new file mode 100644 index 0000000..89a85c8 --- /dev/null +++ b/openshock/rest/models/admin_user_view_user_activation_request.py @@ -0,0 +1,71 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewUserActivationRequest") + + +@_attrs_define +class AdminUserViewUserActivationRequest: + """ + Attributes: + email_send_attempts (int): + created_at (datetime.datetime): + """ + + email_send_attempts: int + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + email_send_attempts = self.email_send_attempts + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "emailSendAttempts": email_send_attempts, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + email_send_attempts = d.pop("emailSendAttempts") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + admin_user_view_user_activation_request = cls( + email_send_attempts=email_send_attempts, + created_at=created_at, + ) + + admin_user_view_user_activation_request.additional_properties = d + return admin_user_view_user_activation_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_deactivation.py b/openshock/rest/models/admin_user_view_user_deactivation.py new file mode 100644 index 0000000..a73d1b5 --- /dev/null +++ b/openshock/rest/models/admin_user_view_user_deactivation.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_user_view_user_ref import AdminUserViewUserRef + + +T = TypeVar("T", bound="AdminUserViewUserDeactivation") + + +@_attrs_define +class AdminUserViewUserDeactivation: + """ + Attributes: + deactivated_by (AdminUserViewUserRef): + scheduled_deletion_time (datetime.datetime | None): + deactivated_at (datetime.datetime): + """ + + deactivated_by: AdminUserViewUserRef + scheduled_deletion_time: datetime.datetime | None + deactivated_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + deactivated_by = self.deactivated_by.to_dict() + + scheduled_deletion_time: None | str + if isinstance(self.scheduled_deletion_time, datetime.datetime): + scheduled_deletion_time = self.scheduled_deletion_time.isoformat() + else: + scheduled_deletion_time = self.scheduled_deletion_time + + deactivated_at = self.deactivated_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "deactivatedBy": deactivated_by, + "scheduledDeletionTime": scheduled_deletion_time, + "deactivatedAt": deactivated_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_user_view_user_ref import AdminUserViewUserRef # noqa: PLC0415 + + d = dict(src_dict) + deactivated_by = AdminUserViewUserRef.from_dict(d.pop("deactivatedBy")) + + def _parse_scheduled_deletion_time(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + scheduled_deletion_time_type_1 = datetime.datetime.fromisoformat(data) + + return scheduled_deletion_time_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + scheduled_deletion_time = _parse_scheduled_deletion_time(d.pop("scheduledDeletionTime")) + + deactivated_at = datetime.datetime.fromisoformat(d.pop("deactivatedAt")) + + admin_user_view_user_deactivation = cls( + deactivated_by=deactivated_by, + scheduled_deletion_time=scheduled_deletion_time, + deactivated_at=deactivated_at, + ) + + admin_user_view_user_deactivation.additional_properties = d + return admin_user_view_user_deactivation + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_ref.py b/openshock/rest/models/admin_user_view_user_ref.py new file mode 100644 index 0000000..0faa90f --- /dev/null +++ b/openshock/rest/models/admin_user_view_user_ref.py @@ -0,0 +1,71 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewUserRef") + + +@_attrs_define +class AdminUserViewUserRef: + """ + Attributes: + id (UUID): + name (str): + """ + + id: UUID + name: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + admin_user_view_user_ref = cls( + id=id, + name=name, + ) + + admin_user_view_user_ref.additional_properties = d + return admin_user_view_user_ref + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_users_view.py b/openshock/rest/models/admin_users_view.py new file mode 100644 index 0000000..2dc3109 --- /dev/null +++ b/openshock/rest/models/admin_users_view.py @@ -0,0 +1,304 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.password_hashing_algorithm import PasswordHashingAlgorithm +from ..models.role_type import RoleType + +T = TypeVar("T", bound="AdminUsersView") + + +@_attrs_define +class AdminUsersView: + """ + Attributes: + id (UUID): + name (str): + email (str): + password_hash_type (None | PasswordHashingAlgorithm): + roles (list[RoleType]): + created_at (datetime.datetime): + activated_at (datetime.datetime | None): + created_by_automation_token_id (None | UUID): + deactivated_at (datetime.datetime | None): + deactivated_by_user_id (None | UUID): + api_token_count (int): + password_reset_count (int): + shocker_user_share_count (int): + shocker_public_share_count (int): + email_change_request_count (int): + name_change_request_count (int): + device_count (int): + shocker_count (int): + shocker_control_log_count (int): + """ + + id: UUID + name: str + email: str + password_hash_type: None | PasswordHashingAlgorithm + roles: list[RoleType] + created_at: datetime.datetime + activated_at: datetime.datetime | None + created_by_automation_token_id: None | UUID + deactivated_at: datetime.datetime | None + deactivated_by_user_id: None | UUID + api_token_count: int + password_reset_count: int + shocker_user_share_count: int + shocker_public_share_count: int + email_change_request_count: int + name_change_request_count: int + device_count: int + shocker_count: int + shocker_control_log_count: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + email = self.email + + password_hash_type: None | str + if isinstance(self.password_hash_type, PasswordHashingAlgorithm): + password_hash_type = self.password_hash_type.value + else: + password_hash_type = self.password_hash_type + + roles = [] + for roles_item_data in self.roles: + roles_item = roles_item_data.value + roles.append(roles_item) + + created_at = self.created_at.isoformat() + + activated_at: None | str + if isinstance(self.activated_at, datetime.datetime): + activated_at = self.activated_at.isoformat() + else: + activated_at = self.activated_at + + created_by_automation_token_id: None | str + if isinstance(self.created_by_automation_token_id, UUID): + created_by_automation_token_id = str(self.created_by_automation_token_id) + else: + created_by_automation_token_id = self.created_by_automation_token_id + + deactivated_at: None | str + if isinstance(self.deactivated_at, datetime.datetime): + deactivated_at = self.deactivated_at.isoformat() + else: + deactivated_at = self.deactivated_at + + deactivated_by_user_id: None | str + if isinstance(self.deactivated_by_user_id, UUID): + deactivated_by_user_id = str(self.deactivated_by_user_id) + else: + deactivated_by_user_id = self.deactivated_by_user_id + + api_token_count = self.api_token_count + + password_reset_count = self.password_reset_count + + shocker_user_share_count = self.shocker_user_share_count + + shocker_public_share_count = self.shocker_public_share_count + + email_change_request_count = self.email_change_request_count + + name_change_request_count = self.name_change_request_count + + device_count = self.device_count + + shocker_count = self.shocker_count + + shocker_control_log_count = self.shocker_control_log_count + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "email": email, + "passwordHashType": password_hash_type, + "roles": roles, + "createdAt": created_at, + "activatedAt": activated_at, + "createdByAutomationTokenId": created_by_automation_token_id, + "deactivatedAt": deactivated_at, + "deactivatedByUserId": deactivated_by_user_id, + "apiTokenCount": api_token_count, + "passwordResetCount": password_reset_count, + "shockerUserShareCount": shocker_user_share_count, + "shockerPublicShareCount": shocker_public_share_count, + "emailChangeRequestCount": email_change_request_count, + "nameChangeRequestCount": name_change_request_count, + "deviceCount": device_count, + "shockerCount": shocker_count, + "shockerControlLogCount": shocker_control_log_count, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + email = d.pop("email") + + def _parse_password_hash_type(data: object) -> None | PasswordHashingAlgorithm: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + password_hash_type_type_1 = PasswordHashingAlgorithm(data) + + return password_hash_type_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | PasswordHashingAlgorithm, data) + + password_hash_type = _parse_password_hash_type(d.pop("passwordHashType")) + + roles = [] + _roles = d.pop("roles") + for roles_item_data in _roles: + roles_item = RoleType(roles_item_data) + + roles.append(roles_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_activated_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + activated_at_type_1 = datetime.datetime.fromisoformat(data) + + return activated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + activated_at = _parse_activated_at(d.pop("activatedAt")) + + def _parse_created_by_automation_token_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + created_by_automation_token_id_type_1 = UUID(data) + + return created_by_automation_token_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) + + def _parse_deactivated_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + deactivated_at_type_1 = datetime.datetime.fromisoformat(data) + + return deactivated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + deactivated_at = _parse_deactivated_at(d.pop("deactivatedAt")) + + def _parse_deactivated_by_user_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + deactivated_by_user_id_type_1 = UUID(data) + + return deactivated_by_user_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + deactivated_by_user_id = _parse_deactivated_by_user_id(d.pop("deactivatedByUserId")) + + api_token_count = d.pop("apiTokenCount") + + password_reset_count = d.pop("passwordResetCount") + + shocker_user_share_count = d.pop("shockerUserShareCount") + + shocker_public_share_count = d.pop("shockerPublicShareCount") + + email_change_request_count = d.pop("emailChangeRequestCount") + + name_change_request_count = d.pop("nameChangeRequestCount") + + device_count = d.pop("deviceCount") + + shocker_count = d.pop("shockerCount") + + shocker_control_log_count = d.pop("shockerControlLogCount") + + admin_users_view = cls( + id=id, + name=name, + email=email, + password_hash_type=password_hash_type, + roles=roles, + created_at=created_at, + activated_at=activated_at, + created_by_automation_token_id=created_by_automation_token_id, + deactivated_at=deactivated_at, + deactivated_by_user_id=deactivated_by_user_id, + api_token_count=api_token_count, + password_reset_count=password_reset_count, + shocker_user_share_count=shocker_user_share_count, + shocker_public_share_count=shocker_public_share_count, + email_change_request_count=email_change_request_count, + name_change_request_count=name_change_request_count, + device_count=device_count, + shocker_count=shocker_count, + shocker_control_log_count=shocker_control_log_count, + ) + + admin_users_view.additional_properties = d + return admin_users_view + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_action.py b/openshock/rest/models/audit_action.py new file mode 100644 index 0000000..e7bcff5 --- /dev/null +++ b/openshock/rest/models/audit_action.py @@ -0,0 +1,26 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditAction(StrEnum): + ACCOUNTDEACTIVATED = "AccountDeactivated" + ACCOUNTDELETED = "AccountDeleted" + ACCOUNTREACTIVATED = "AccountReactivated" + APITOKENCREATED = "ApiTokenCreated" + APITOKENDELETED = "ApiTokenDeleted" + AUTOMATIONTOKENCREATED = "AutomationTokenCreated" + AUTOMATIONTOKENDELETED = "AutomationTokenDeleted" + AUTOMATIONTOKENROTATED = "AutomationTokenRotated" + AUTOMATIONTOKENUPDATED = "AutomationTokenUpdated" + AUTOMATIONTOKENUSED = "AutomationTokenUsed" + EMAILCHANGED = "EmailChanged" + EMAILCHANGEREQUESTED = "EmailChangeRequested" + LOGIN = "Login" + LOGOUT = "Logout" + OAUTHCONNECTED = "OAuthConnected" + OAUTHDISCONNECTED = "OAuthDisconnected" + PASSWORDCHANGED = "PasswordChanged" + USERNAMECHANGED = "UsernameChanged" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_log_entry_response.py b/openshock/rest/models/audit_log_entry_response.py new file mode 100644 index 0000000..382f07a --- /dev/null +++ b/openshock/rest/models/audit_log_entry_response.py @@ -0,0 +1,432 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_action import AuditAction + +if TYPE_CHECKING: + from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata + from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata + from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata + from ..models.audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata + from ..models.audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata + from ..models.audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata + from ..models.audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata + from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata + from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata + from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata + from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata + from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata + from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata + from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata + + +T = TypeVar("T", bound="AuditLogEntryResponse") + + +@_attrs_define +class AuditLogEntryResponse: + """ + Attributes: + id (UUID): + user_id (UUID): + actor_id (None | UUID): + action (AuditAction): + reason (None | str): + ip_address (None | str): An IPv4 or IPv6 address in its textual form. + user_agent (None | str): + metadata (AuditMetadataAccountDeactivatedMetadata | AuditMetadataApiTokenCreatedMetadata | + AuditMetadataApiTokenDeletedMetadata | AuditMetadataAutomationTokenCreatedMetadata | + AuditMetadataAutomationTokenDeletedMetadata | AuditMetadataAutomationTokenRotatedMetadata | + AuditMetadataAutomationTokenUpdatedMetadata | AuditMetadataAutomationTokenUsedMetadata | + AuditMetadataEmailChangedMetadata | AuditMetadataEmailChangeRequestedMetadata | AuditMetadataLoginMetadata | + AuditMetadataOAuthConnectedMetadata | AuditMetadataOAuthDisconnectedMetadata | + AuditMetadataUsernameChangedMetadata | None): + created_at (datetime.datetime): + """ + + id: UUID + user_id: UUID + actor_id: None | UUID + action: AuditAction + reason: None | str + ip_address: None | str + user_agent: None | str + metadata: ( + AuditMetadataAccountDeactivatedMetadata + | AuditMetadataApiTokenCreatedMetadata + | AuditMetadataApiTokenDeletedMetadata + | AuditMetadataAutomationTokenCreatedMetadata + | AuditMetadataAutomationTokenDeletedMetadata + | AuditMetadataAutomationTokenRotatedMetadata + | AuditMetadataAutomationTokenUpdatedMetadata + | AuditMetadataAutomationTokenUsedMetadata + | AuditMetadataEmailChangedMetadata + | AuditMetadataEmailChangeRequestedMetadata + | AuditMetadataLoginMetadata + | AuditMetadataOAuthConnectedMetadata + | AuditMetadataOAuthDisconnectedMetadata + | AuditMetadataUsernameChangedMetadata + | None + ) + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 + from ..models.audit_metadata_automation_token_created_metadata import ( + AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_deleted_metadata import ( + AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_rotated_metadata import ( + AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_updated_metadata import ( + AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 + from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 + + id = str(self.id) + + user_id = str(self.user_id) + + actor_id: None | str + if isinstance(self.actor_id, UUID): + actor_id = str(self.actor_id) + else: + actor_id = self.actor_id + + action = self.action.value + + reason: None | str + reason = self.reason + + ip_address: None | str + ip_address = self.ip_address + + user_agent: None | str + user_agent = self.user_agent + + metadata: dict[str, Any] | None + if isinstance(self.metadata, AuditMetadataLoginMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataUsernameChangedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataEmailChangeRequestedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataEmailChangedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataApiTokenCreatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataApiTokenDeletedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataOAuthConnectedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataOAuthDisconnectedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAccountDeactivatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenCreatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenUpdatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenRotatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenDeletedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenUsedMetadata): + metadata = self.metadata.to_dict() + else: + metadata = self.metadata + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "userId": user_id, + "actorId": actor_id, + "action": action, + "reason": reason, + "ipAddress": ip_address, + "userAgent": user_agent, + "metadata": metadata, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 + from ..models.audit_metadata_automation_token_created_metadata import ( + AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_deleted_metadata import ( + AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_rotated_metadata import ( + AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_updated_metadata import ( + AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 + from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + user_id = UUID(d.pop("userId")) + + def _parse_actor_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + actor_id_type_1 = UUID(data) + + return actor_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + actor_id = _parse_actor_id(d.pop("actorId")) + + action = AuditAction(d.pop("action")) + + def _parse_reason(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + reason = _parse_reason(d.pop("reason")) + + def _parse_ip_address(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + ip_address = _parse_ip_address(d.pop("ipAddress")) + + def _parse_user_agent(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + user_agent = _parse_user_agent(d.pop("userAgent")) + + def _parse_metadata( + data: object, + ) -> ( + AuditMetadataAccountDeactivatedMetadata + | AuditMetadataApiTokenCreatedMetadata + | AuditMetadataApiTokenDeletedMetadata + | AuditMetadataAutomationTokenCreatedMetadata + | AuditMetadataAutomationTokenDeletedMetadata + | AuditMetadataAutomationTokenRotatedMetadata + | AuditMetadataAutomationTokenUpdatedMetadata + | AuditMetadataAutomationTokenUsedMetadata + | AuditMetadataEmailChangedMetadata + | AuditMetadataEmailChangeRequestedMetadata + | AuditMetadataLoginMetadata + | AuditMetadataOAuthConnectedMetadata + | AuditMetadataOAuthDisconnectedMetadata + | AuditMetadataUsernameChangedMetadata + | None + ): + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_0 = AuditMetadataLoginMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_1 = AuditMetadataUsernameChangedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_2 = AuditMetadataEmailChangeRequestedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_2 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_3 = AuditMetadataEmailChangedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_3 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_4 = AuditMetadataApiTokenCreatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_4 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_5 = AuditMetadataApiTokenDeletedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_5 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_6 = AuditMetadataOAuthConnectedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_6 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_7 = AuditMetadataOAuthDisconnectedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_7 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_8 = AuditMetadataAccountDeactivatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_8 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_9 = AuditMetadataAutomationTokenCreatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_9 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_10 = AuditMetadataAutomationTokenUpdatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_10 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_11 = AuditMetadataAutomationTokenRotatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_11 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_12 = AuditMetadataAutomationTokenDeletedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_12 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_13 = AuditMetadataAutomationTokenUsedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_13 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast( + AuditMetadataAccountDeactivatedMetadata + | AuditMetadataApiTokenCreatedMetadata + | AuditMetadataApiTokenDeletedMetadata + | AuditMetadataAutomationTokenCreatedMetadata + | AuditMetadataAutomationTokenDeletedMetadata + | AuditMetadataAutomationTokenRotatedMetadata + | AuditMetadataAutomationTokenUpdatedMetadata + | AuditMetadataAutomationTokenUsedMetadata + | AuditMetadataEmailChangedMetadata + | AuditMetadataEmailChangeRequestedMetadata + | AuditMetadataLoginMetadata + | AuditMetadataOAuthConnectedMetadata + | AuditMetadataOAuthDisconnectedMetadata + | AuditMetadataUsernameChangedMetadata + | None, + data, + ) + + metadata = _parse_metadata(d.pop("metadata")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + audit_log_entry_response = cls( + id=id, + user_id=user_id, + actor_id=actor_id, + action=action, + reason=reason, + ip_address=ip_address, + user_agent=user_agent, + metadata=metadata, + created_at=created_at, + ) + + audit_log_entry_response.additional_properties = d + return audit_log_entry_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata.py new file mode 100644 index 0000000..0c04186 --- /dev/null +++ b/openshock/rest/models/audit_metadata_account_deactivated_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAccountDeactivatedMetadata") + + +@_attrs_define +class AuditMetadataAccountDeactivatedMetadata: + """ + Attributes: + delete_later (bool): + t (AuditMetadataAccountDeactivatedMetadataT | Unset): + """ + + delete_later: bool + t: AuditMetadataAccountDeactivatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + delete_later = self.delete_later + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "deleteLater": delete_later, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + delete_later = d.pop("deleteLater") + + _t = d.pop("t", UNSET) + t: AuditMetadataAccountDeactivatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAccountDeactivatedMetadataT(_t) + + audit_metadata_account_deactivated_metadata = cls( + delete_later=delete_later, + t=t, + ) + + audit_metadata_account_deactivated_metadata.additional_properties = d + return audit_metadata_account_deactivated_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py new file mode 100644 index 0000000..f5a287d --- /dev/null +++ b/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAccountDeactivatedMetadataT(StrEnum): + ACCOUNTDEACTIVATED = "accountDeactivated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata.py b/openshock/rest/models/audit_metadata_api_token_created_metadata.py new file mode 100644 index 0000000..f813d7f --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_created_metadata.py @@ -0,0 +1,98 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataApiTokenCreatedMetadata") + + +@_attrs_define +class AuditMetadataApiTokenCreatedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + permissions (list[str]): + t (AuditMetadataApiTokenCreatedMetadataT | Unset): + """ + + token_id: UUID + name: str + permissions: list[str] + t: AuditMetadataApiTokenCreatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + permissions = self.permissions + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "permissions": permissions, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + permissions = cast(list[str], d.pop("permissions")) + + _t = d.pop("t", UNSET) + t: AuditMetadataApiTokenCreatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataApiTokenCreatedMetadataT(_t) + + audit_metadata_api_token_created_metadata = cls( + token_id=token_id, + name=name, + permissions=permissions, + t=t, + ) + + audit_metadata_api_token_created_metadata.additional_properties = d + return audit_metadata_api_token_created_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py new file mode 100644 index 0000000..59024ee --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataApiTokenCreatedMetadataT(StrEnum): + APITOKENCREATED = "apiTokenCreated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py new file mode 100644 index 0000000..1087190 --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py @@ -0,0 +1,90 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataApiTokenDeletedMetadata") + + +@_attrs_define +class AuditMetadataApiTokenDeletedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + t (AuditMetadataApiTokenDeletedMetadataT | Unset): + """ + + token_id: UUID + name: str + t: AuditMetadataApiTokenDeletedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + _t = d.pop("t", UNSET) + t: AuditMetadataApiTokenDeletedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataApiTokenDeletedMetadataT(_t) + + audit_metadata_api_token_deleted_metadata = cls( + token_id=token_id, + name=name, + t=t, + ) + + audit_metadata_api_token_deleted_metadata.additional_properties = d + return audit_metadata_api_token_deleted_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py new file mode 100644 index 0000000..de49448 --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataApiTokenDeletedMetadataT(StrEnum): + APITOKENDELETED = "apiTokenDeleted" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata.py new file mode 100644 index 0000000..78c3add --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_created_metadata.py @@ -0,0 +1,120 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenCreatedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenCreatedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + types (list[str]): + auto_cleanup_users (bool): + auto_cleanup_after (None | str): + t (AuditMetadataAutomationTokenCreatedMetadataT | Unset): + """ + + token_id: UUID + name: str + types: list[str] + auto_cleanup_users: bool + auto_cleanup_after: None | str + t: AuditMetadataAutomationTokenCreatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + types = self.types + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str + auto_cleanup_after = self.auto_cleanup_after + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "types": types, + "autoCleanupUsers": auto_cleanup_users, + "autoCleanupAfter": auto_cleanup_after, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + types = cast(list[str], d.pop("types")) + + auto_cleanup_users = d.pop("autoCleanupUsers") + + def _parse_auto_cleanup_after(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenCreatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenCreatedMetadataT(_t) + + audit_metadata_automation_token_created_metadata = cls( + token_id=token_id, + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + t=t, + ) + + audit_metadata_automation_token_created_metadata.additional_properties = d + return audit_metadata_automation_token_created_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py new file mode 100644 index 0000000..71728a5 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenCreatedMetadataT(StrEnum): + AUTOMATIONTOKENCREATED = "automationTokenCreated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py new file mode 100644 index 0000000..98e47b2 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py @@ -0,0 +1,99 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenDeletedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenDeletedMetadata: + """The token was deleted together with the int AutomationTokenDeletedMetadata.DeletedAccountCount accounts it created. + + Attributes: + token_id (UUID): + name (str): + deleted_account_count (int): + t (AuditMetadataAutomationTokenDeletedMetadataT | Unset): + """ + + token_id: UUID + name: str + deleted_account_count: int + t: AuditMetadataAutomationTokenDeletedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + deleted_account_count = self.deleted_account_count + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "deletedAccountCount": deleted_account_count, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + deleted_account_count = d.pop("deletedAccountCount") + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenDeletedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenDeletedMetadataT(_t) + + audit_metadata_automation_token_deleted_metadata = cls( + token_id=token_id, + name=name, + deleted_account_count=deleted_account_count, + t=t, + ) + + audit_metadata_automation_token_deleted_metadata.additional_properties = d + return audit_metadata_automation_token_deleted_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py new file mode 100644 index 0000000..6e81913 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenDeletedMetadataT(StrEnum): + AUTOMATIONTOKENDELETED = "automationTokenDeleted" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py new file mode 100644 index 0000000..86b917e --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py @@ -0,0 +1,90 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenRotatedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenRotatedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + t (AuditMetadataAutomationTokenRotatedMetadataT | Unset): + """ + + token_id: UUID + name: str + t: AuditMetadataAutomationTokenRotatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenRotatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenRotatedMetadataT(_t) + + audit_metadata_automation_token_rotated_metadata = cls( + token_id=token_id, + name=name, + t=t, + ) + + audit_metadata_automation_token_rotated_metadata.additional_properties = d + return audit_metadata_automation_token_rotated_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py new file mode 100644 index 0000000..b9df839 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenRotatedMetadataT(StrEnum): + AUTOMATIONTOKENROTATED = "automationTokenRotated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py new file mode 100644 index 0000000..083f9d7 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py @@ -0,0 +1,121 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenUpdatedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenUpdatedMetadata: + """The token's settings after the update. + + Attributes: + token_id (UUID): + name (str): + types (list[str]): + auto_cleanup_users (bool): + auto_cleanup_after (None | str): + t (AuditMetadataAutomationTokenUpdatedMetadataT | Unset): + """ + + token_id: UUID + name: str + types: list[str] + auto_cleanup_users: bool + auto_cleanup_after: None | str + t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + types = self.types + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str + auto_cleanup_after = self.auto_cleanup_after + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "types": types, + "autoCleanupUsers": auto_cleanup_users, + "autoCleanupAfter": auto_cleanup_after, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + types = cast(list[str], d.pop("types")) + + auto_cleanup_users = d.pop("autoCleanupUsers") + + def _parse_auto_cleanup_after(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenUpdatedMetadataT(_t) + + audit_metadata_automation_token_updated_metadata = cls( + token_id=token_id, + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + t=t, + ) + + audit_metadata_automation_token_updated_metadata.additional_properties = d + return audit_metadata_automation_token_updated_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py new file mode 100644 index 0000000..e47bd5e --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenUpdatedMetadataT(StrEnum): + AUTOMATIONTOKENUPDATED = "automationTokenUpdated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata.py new file mode 100644 index 0000000..d9bba52 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_used_metadata.py @@ -0,0 +1,100 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenUsedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenUsedMetadata: + """An automation token was used on this account. string AutomationTokenUsedMetadata.Flow is a `AutomationTokenFlow` + name. + + Attributes: + token_id (UUID): + name (str): + flow (str): + t (AuditMetadataAutomationTokenUsedMetadataT | Unset): + """ + + token_id: UUID + name: str + flow: str + t: AuditMetadataAutomationTokenUsedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + flow = self.flow + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "flow": flow, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + flow = d.pop("flow") + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenUsedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenUsedMetadataT(_t) + + audit_metadata_automation_token_used_metadata = cls( + token_id=token_id, + name=name, + flow=flow, + t=t, + ) + + audit_metadata_automation_token_used_metadata.additional_properties = d + return audit_metadata_automation_token_used_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py new file mode 100644 index 0000000..591cb62 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenUsedMetadataT(StrEnum): + AUTOMATIONTOKENUSED = "automationTokenUsed" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata.py new file mode 100644 index 0000000..c1e7b8a --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_change_requested_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataEmailChangeRequestedMetadata") + + +@_attrs_define +class AuditMetadataEmailChangeRequestedMetadata: + """ + Attributes: + new_email (str): + t (AuditMetadataEmailChangeRequestedMetadataT | Unset): + """ + + new_email: str + t: AuditMetadataEmailChangeRequestedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + new_email = self.new_email + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "newEmail": new_email, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + new_email = d.pop("newEmail") + + _t = d.pop("t", UNSET) + t: AuditMetadataEmailChangeRequestedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataEmailChangeRequestedMetadataT(_t) + + audit_metadata_email_change_requested_metadata = cls( + new_email=new_email, + t=t, + ) + + audit_metadata_email_change_requested_metadata.additional_properties = d + return audit_metadata_email_change_requested_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py new file mode 100644 index 0000000..5cf3cd0 --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataEmailChangeRequestedMetadataT(StrEnum): + EMAILCHANGEREQUESTED = "emailChangeRequested" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata.py b/openshock/rest/models/audit_metadata_email_changed_metadata.py new file mode 100644 index 0000000..59f2ac4 --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_changed_metadata.py @@ -0,0 +1,89 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataEmailChangedMetadata") + + +@_attrs_define +class AuditMetadataEmailChangedMetadata: + """ + Attributes: + old (str): + new (str): + t (AuditMetadataEmailChangedMetadataT | Unset): + """ + + old: str + new: str + t: AuditMetadataEmailChangedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + old = self.old + + new = self.new + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "old": old, + "new": new, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + old = d.pop("old") + + new = d.pop("new") + + _t = d.pop("t", UNSET) + t: AuditMetadataEmailChangedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataEmailChangedMetadataT(_t) + + audit_metadata_email_changed_metadata = cls( + old=old, + new=new, + t=t, + ) + + audit_metadata_email_changed_metadata.additional_properties = d + return audit_metadata_email_changed_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata_t.py b/openshock/rest/models/audit_metadata_email_changed_metadata_t.py new file mode 100644 index 0000000..1bcee56 --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_changed_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataEmailChangedMetadataT(StrEnum): + EMAILCHANGED = "emailChanged" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_login_metadata.py b/openshock/rest/models/audit_metadata_login_metadata.py new file mode 100644 index 0000000..56879d2 --- /dev/null +++ b/openshock/rest/models/audit_metadata_login_metadata.py @@ -0,0 +1,82 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataLoginMetadata") + + +@_attrs_define +class AuditMetadataLoginMetadata: + """ + Attributes: + session_id (UUID): + t (AuditMetadataLoginMetadataT | Unset): + """ + + session_id: UUID + t: AuditMetadataLoginMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + session_id = str(self.session_id) + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "sessionId": session_id, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + session_id = UUID(d.pop("sessionId")) + + _t = d.pop("t", UNSET) + t: AuditMetadataLoginMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataLoginMetadataT(_t) + + audit_metadata_login_metadata = cls( + session_id=session_id, + t=t, + ) + + audit_metadata_login_metadata.additional_properties = d + return audit_metadata_login_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_login_metadata_t.py b/openshock/rest/models/audit_metadata_login_metadata_t.py new file mode 100644 index 0000000..d98a11a --- /dev/null +++ b/openshock/rest/models/audit_metadata_login_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataLoginMetadataT(StrEnum): + LOGIN = "login" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py new file mode 100644 index 0000000..96f4469 --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataOAuthConnectedMetadata") + + +@_attrs_define +class AuditMetadataOAuthConnectedMetadata: + """ + Attributes: + provider (str): + t (AuditMetadataOAuthConnectedMetadataT | Unset): + """ + + provider: str + t: AuditMetadataOAuthConnectedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + provider = self.provider + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "provider": provider, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + provider = d.pop("provider") + + _t = d.pop("t", UNSET) + t: AuditMetadataOAuthConnectedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataOAuthConnectedMetadataT(_t) + + audit_metadata_o_auth_connected_metadata = cls( + provider=provider, + t=t, + ) + + audit_metadata_o_auth_connected_metadata.additional_properties = d + return audit_metadata_o_auth_connected_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py new file mode 100644 index 0000000..6d80bfc --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataOAuthConnectedMetadataT(StrEnum): + OAUTHCONNECTED = "oauthConnected" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py new file mode 100644 index 0000000..b7ee896 --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataOAuthDisconnectedMetadata") + + +@_attrs_define +class AuditMetadataOAuthDisconnectedMetadata: + """ + Attributes: + provider (str): + t (AuditMetadataOAuthDisconnectedMetadataT | Unset): + """ + + provider: str + t: AuditMetadataOAuthDisconnectedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + provider = self.provider + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "provider": provider, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + provider = d.pop("provider") + + _t = d.pop("t", UNSET) + t: AuditMetadataOAuthDisconnectedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataOAuthDisconnectedMetadataT(_t) + + audit_metadata_o_auth_disconnected_metadata = cls( + provider=provider, + t=t, + ) + + audit_metadata_o_auth_disconnected_metadata.additional_properties = d + return audit_metadata_o_auth_disconnected_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py new file mode 100644 index 0000000..c528f73 --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataOAuthDisconnectedMetadataT(StrEnum): + OAUTHDISCONNECTED = "oauthDisconnected" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata.py b/openshock/rest/models/audit_metadata_username_changed_metadata.py new file mode 100644 index 0000000..a1ee8ea --- /dev/null +++ b/openshock/rest/models/audit_metadata_username_changed_metadata.py @@ -0,0 +1,89 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataUsernameChangedMetadata") + + +@_attrs_define +class AuditMetadataUsernameChangedMetadata: + """ + Attributes: + old (str): + new (str): + t (AuditMetadataUsernameChangedMetadataT | Unset): + """ + + old: str + new: str + t: AuditMetadataUsernameChangedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + old = self.old + + new = self.new + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "old": old, + "new": new, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + old = d.pop("old") + + new = d.pop("new") + + _t = d.pop("t", UNSET) + t: AuditMetadataUsernameChangedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataUsernameChangedMetadataT(_t) + + audit_metadata_username_changed_metadata = cls( + old=old, + new=new, + t=t, + ) + + audit_metadata_username_changed_metadata.additional_properties = d + return audit_metadata_username_changed_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata_t.py b/openshock/rest/models/audit_metadata_username_changed_metadata_t.py new file mode 100644 index 0000000..84465c1 --- /dev/null +++ b/openshock/rest/models/audit_metadata_username_changed_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataUsernameChangedMetadataT(StrEnum): + USERNAMECHANGED = "usernameChanged" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/automation_token_dto.py b/openshock/rest/models/automation_token_dto.py new file mode 100644 index 0000000..224cf7a --- /dev/null +++ b/openshock/rest/models/automation_token_dto.py @@ -0,0 +1,197 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AutomationTokenDto") + + +@_attrs_define +class AutomationTokenDto: + """ + Attributes: + id (UUID): + name (str): + types (list[AutomationTokenType]): + created_at (datetime.datetime): + last_used_at (datetime.datetime | None | Unset): + last_rotated_at (datetime.datetime | None | Unset): + use_count (int | Unset): + auto_cleanup_users (bool | Unset): + auto_cleanup_after (None | str | Unset): + """ + + id: UUID + name: str + types: list[AutomationTokenType] + created_at: datetime.datetime + last_used_at: datetime.datetime | None | Unset = UNSET + last_rotated_at: datetime.datetime | None | Unset = UNSET + use_count: int | Unset = UNSET + auto_cleanup_users: bool | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + types = [] + for types_item_data in self.types: + types_item = types_item_data.value + types.append(types_item) + + created_at = self.created_at.isoformat() + + last_used_at: None | str | Unset + if isinstance(self.last_used_at, Unset): + last_used_at = UNSET + elif isinstance(self.last_used_at, datetime.datetime): + last_used_at = self.last_used_at.isoformat() + else: + last_used_at = self.last_used_at + + last_rotated_at: None | str | Unset + if isinstance(self.last_rotated_at, Unset): + last_rotated_at = UNSET + elif isinstance(self.last_rotated_at, datetime.datetime): + last_rotated_at = self.last_rotated_at.isoformat() + else: + last_rotated_at = self.last_rotated_at + + use_count = self.use_count + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "types": types, + "createdAt": created_at, + } + ) + if last_used_at is not UNSET: + field_dict["lastUsedAt"] = last_used_at + if last_rotated_at is not UNSET: + field_dict["lastRotatedAt"] = last_rotated_at + if use_count is not UNSET: + field_dict["useCount"] = use_count + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + types = [] + _types = d.pop("types") + for types_item_data in _types: + types_item = AutomationTokenType(types_item_data) + + types.append(types_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_last_used_at(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_at_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + last_used_at = _parse_last_used_at(d.pop("lastUsedAt", UNSET)) + + def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) + + return last_rotated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) + + use_count = d.pop("useCount", UNSET) + + auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + automation_token_dto = cls( + id=id, + name=name, + types=types, + created_at=created_at, + last_used_at=last_used_at, + last_rotated_at=last_rotated_at, + use_count=use_count, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + automation_token_dto.additional_properties = d + return automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/automation_token_type.py b/openshock/rest/models/automation_token_type.py new file mode 100644 index 0000000..b270e30 --- /dev/null +++ b/openshock/rest/models/automation_token_type.py @@ -0,0 +1,11 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AutomationTokenType(StrEnum): + CONTROLSTATSREAD = "ControlStatsRead" + RATELIMIT = "RateLimit" + TURNSTILE = "Turnstile" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/backend_info_response.py b/openshock/rest/models/backend_info_response.py new file mode 100644 index 0000000..b54d693 --- /dev/null +++ b/openshock/rest/models/backend_info_response.py @@ -0,0 +1,135 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="BackendInfoResponse") + + +@_attrs_define +class BackendInfoResponse: + """ + Attributes: + version (str): + commit (str): + current_time (datetime.datetime): + frontend_url (str): + short_link_url (str): + turnstile_site_key (None | str): + o_auth_providers (list[str]): + is_mail_enabled (bool): False when the instance has no mail provider configured. Accounts are then activated on + creation, and no flow that relies on an emailed link (activation, password reset, email + change) can complete. + is_user_authenticated (bool): + """ + + version: str + commit: str + current_time: datetime.datetime + frontend_url: str + short_link_url: str + turnstile_site_key: None | str + o_auth_providers: list[str] + is_mail_enabled: bool + is_user_authenticated: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + version = self.version + + commit = self.commit + + current_time = self.current_time.isoformat() + + frontend_url = self.frontend_url + + short_link_url = self.short_link_url + + turnstile_site_key: None | str + turnstile_site_key = self.turnstile_site_key + + o_auth_providers = self.o_auth_providers + + is_mail_enabled = self.is_mail_enabled + + is_user_authenticated = self.is_user_authenticated + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "version": version, + "commit": commit, + "currentTime": current_time, + "frontendUrl": frontend_url, + "shortLinkUrl": short_link_url, + "turnstileSiteKey": turnstile_site_key, + "oAuthProviders": o_auth_providers, + "isMailEnabled": is_mail_enabled, + "isUserAuthenticated": is_user_authenticated, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + version = d.pop("version") + + commit = d.pop("commit") + + current_time = datetime.datetime.fromisoformat(d.pop("currentTime")) + + frontend_url = d.pop("frontendUrl") + + short_link_url = d.pop("shortLinkUrl") + + def _parse_turnstile_site_key(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + turnstile_site_key = _parse_turnstile_site_key(d.pop("turnstileSiteKey")) + + o_auth_providers = cast(list[str], d.pop("oAuthProviders")) + + is_mail_enabled = d.pop("isMailEnabled") + + is_user_authenticated = d.pop("isUserAuthenticated") + + backend_info_response = cls( + version=version, + commit=commit, + current_time=current_time, + frontend_url=frontend_url, + short_link_url=short_link_url, + turnstile_site_key=turnstile_site_key, + o_auth_providers=o_auth_providers, + is_mail_enabled=is_mail_enabled, + is_user_authenticated=is_user_authenticated, + ) + + backend_info_response.additional_properties = d + return backend_info_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/basic_user_info.py b/openshock/rest/models/basic_user_info.py new file mode 100644 index 0000000..05eb4d2 --- /dev/null +++ b/openshock/rest/models/basic_user_info.py @@ -0,0 +1,79 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="BasicUserInfo") + + +@_attrs_define +class BasicUserInfo: + """ + Attributes: + id (UUID): + name (str): + image (str): + """ + + id: UUID + name: str + image: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + image = self.image + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "image": image, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + image = d.pop("image") + + basic_user_info = cls( + id=id, + name=name, + image=image, + ) + + basic_user_info.additional_properties = d + return basic_user_info + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/bulk_user_share_shockers_update_request.py b/openshock/rest/models/bulk_user_share_shockers_update_request.py new file mode 100644 index 0000000..4bce848 --- /dev/null +++ b/openshock/rest/models/bulk_user_share_shockers_update_request.py @@ -0,0 +1,95 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="BulkUserShareShockersUpdateRequest") + + +@_attrs_define +class BulkUserShareShockersUpdateRequest: + """ + Attributes: + shockers (list[UUID]): + permissions (ShockerPermissions): + limits (ShockerLimits): + """ + + shockers: list[UUID] + permissions: ShockerPermissions + limits: ShockerLimits + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = str(shockers_item_data) + shockers.append(shockers_item) + + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "shockers": shockers, + "permissions": permissions, + "limits": limits, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = UUID(shockers_item_data) + + shockers.append(shockers_item) + + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + bulk_user_share_shockers_update_request = cls( + shockers=shockers, + permissions=permissions, + limits=limits, + ) + + bulk_user_share_shockers_update_request.additional_properties = d + return bulk_user_share_shockers_update_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/change_email_request.py b/openshock/rest/models/change_email_request.py new file mode 100644 index 0000000..918e9c6 --- /dev/null +++ b/openshock/rest/models/change_email_request.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ChangeEmailRequest") + + +@_attrs_define +class ChangeEmailRequest: + """ + Attributes: + current_password (str): + email (str): + """ + + current_password: str + email: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + current_password = self.current_password + + email = self.email + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "currentPassword": current_password, + "email": email, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + current_password = d.pop("currentPassword") + + email = d.pop("email") + + change_email_request = cls( + current_password=current_password, + email=email, + ) + + change_email_request.additional_properties = d + return change_email_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/change_password_request.py b/openshock/rest/models/change_password_request.py new file mode 100644 index 0000000..6337c0e --- /dev/null +++ b/openshock/rest/models/change_password_request.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ChangePasswordRequest") + + +@_attrs_define +class ChangePasswordRequest: + """ + Attributes: + current_password (str): + new_password (str): + """ + + current_password: str + new_password: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + current_password = self.current_password + + new_password = self.new_password + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "currentPassword": current_password, + "newPassword": new_password, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + current_password = d.pop("currentPassword") + + new_password = d.pop("newPassword") + + change_password_request = cls( + current_password=current_password, + new_password=new_password, + ) + + change_password_request.additional_properties = d + return change_password_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/change_username_request.py b/openshock/rest/models/change_username_request.py new file mode 100644 index 0000000..348e9c1 --- /dev/null +++ b/openshock/rest/models/change_username_request.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ChangeUsernameRequest") + + +@_attrs_define +class ChangeUsernameRequest: + """ + Attributes: + username (str): + """ + + username: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + username = self.username + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "username": username, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + username = d.pop("username") + + change_username_request = cls( + username=username, + ) + + change_username_request.additional_properties = d + return change_username_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_add_item_request.py b/openshock/rest/models/configuration_add_item_request.py new file mode 100644 index 0000000..a2650e7 --- /dev/null +++ b/openshock/rest/models/configuration_add_item_request.py @@ -0,0 +1,91 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.configuration_value_type import ConfigurationValueType + +T = TypeVar("T", bound="ConfigurationAddItemRequest") + + +@_attrs_define +class ConfigurationAddItemRequest: + """Request DTO for adding a new configuration item. + + Attributes: + name (str): The unique name of the configuration item. + Must consist of uppercase letters and underscores only. + description (str): A human-readable description of the configuration item’s purpose. + type_ (ConfigurationValueType): + value (str): The initial value for the configuration item, serialized as a string. + Must conform to the format required by ConfigurationValueType ConfigurationAddItemRequest.Type. + """ + + name: str + description: str + type_: ConfigurationValueType + value: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + description = self.description + + type_ = self.type_.value + + value = self.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "description": description, + "type": type_, + "value": value, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + description = d.pop("description") + + type_ = ConfigurationValueType(d.pop("type")) + + value = d.pop("value") + + configuration_add_item_request = cls( + name=name, + description=description, + type_=type_, + value=value, + ) + + configuration_add_item_request.additional_properties = d + return configuration_add_item_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_item_dto.py b/openshock/rest/models/configuration_item_dto.py new file mode 100644 index 0000000..428129b --- /dev/null +++ b/openshock/rest/models/configuration_item_dto.py @@ -0,0 +1,106 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.configuration_value_type import ConfigurationValueType + +T = TypeVar("T", bound="ConfigurationItemDto") + + +@_attrs_define +class ConfigurationItemDto: + """Data transfer object representing a configuration item. + + Attributes: + name (str): The unique name of the configuration item. + description (str): A human-readable description of what this configuration item controls. + type_ (ConfigurationValueType): + value (str): The current value of the configuration item, serialized as a string. + updated_at (datetime.datetime): The timestamp when the configuration was last updated. + created_at (datetime.datetime): The timestamp when the configuration was originally created. + """ + + name: str + description: str + type_: ConfigurationValueType + value: str + updated_at: datetime.datetime + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + description = self.description + + type_ = self.type_.value + + value = self.value + + updated_at = self.updated_at.isoformat() + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "description": description, + "type": type_, + "value": value, + "updatedAt": updated_at, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + description = d.pop("description") + + type_ = ConfigurationValueType(d.pop("type")) + + value = d.pop("value") + + updated_at = datetime.datetime.fromisoformat(d.pop("updatedAt")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + configuration_item_dto = cls( + name=name, + description=description, + type_=type_, + value=value, + updated_at=updated_at, + created_at=created_at, + ) + + configuration_item_dto.additional_properties = d + return configuration_item_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_update_item_request.py b/openshock/rest/models/configuration_update_item_request.py new file mode 100644 index 0000000..a2bb38b --- /dev/null +++ b/openshock/rest/models/configuration_update_item_request.py @@ -0,0 +1,110 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="ConfigurationUpdateItemRequest") + + +@_attrs_define +class ConfigurationUpdateItemRequest: + """Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? ConfigurationUpdateItemRequest.Value (or both) + may be provided. + If both are null, no update action is performed. + + Attributes: + name (str): The name of the configuration item to update. + Must consist only of uppercase letters and underscores. + description (None | str | Unset): (Optional) New description for the configuration item. + value (None | str | Unset): (Optional) New value for the configuration item. + Must match the format expected by its existing ConfigurationValueType. + """ + + name: str + description: None | str | Unset = UNSET + value: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + description: None | str | Unset + if isinstance(self.description, Unset): + description = UNSET + else: + description = self.description + + value: None | str | Unset + if isinstance(self.value, Unset): + value = UNSET + else: + value = self.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + } + ) + if description is not UNSET: + field_dict["description"] = description + if value is not UNSET: + field_dict["value"] = value + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + def _parse_description(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + description = _parse_description(d.pop("description", UNSET)) + + def _parse_value(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + value = _parse_value(d.pop("value", UNSET)) + + configuration_update_item_request = cls( + name=name, + description=description, + value=value, + ) + + configuration_update_item_request.additional_properties = d + return configuration_update_item_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_value_type.py b/openshock/rest/models/configuration_value_type.py new file mode 100644 index 0000000..b809802 --- /dev/null +++ b/openshock/rest/models/configuration_value_type.py @@ -0,0 +1,13 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class ConfigurationValueType(StrEnum): + BOOL = "Bool" + FLOAT = "Float" + INT = "Int" + JSON = "Json" + STRING = "String" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/control.py b/openshock/rest/models/control.py new file mode 100644 index 0000000..7d3c43b --- /dev/null +++ b/openshock/rest/models/control.py @@ -0,0 +1,99 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.control_type import ControlType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="Control") + + +@_attrs_define +class Control: + """ + Attributes: + id (UUID): + type_ (ControlType): + intensity (int): + duration (int): + exclusive (bool | Unset): If true, overrides livecontrol + """ + + id: UUID + type_: ControlType + intensity: int + duration: int + exclusive: bool | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + type_ = self.type_.value + + intensity = self.intensity + + duration = self.duration + + exclusive = self.exclusive + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "type": type_, + "intensity": intensity, + "duration": duration, + } + ) + if exclusive is not UNSET: + field_dict["exclusive"] = exclusive + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + type_ = ControlType(d.pop("type")) + + intensity = d.pop("intensity") + + duration = d.pop("duration") + + exclusive = d.pop("exclusive", UNSET) + + control = cls( + id=id, + type_=type_, + intensity=intensity, + duration=duration, + exclusive=exclusive, + ) + + control.additional_properties = d + return control + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/control_limit_mode.py b/openshock/rest/models/control_limit_mode.py new file mode 100644 index 0000000..003b114 --- /dev/null +++ b/openshock/rest/models/control_limit_mode.py @@ -0,0 +1,10 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class ControlLimitMode(StrEnum): + CLAMP = "Clamp" + LERP = "Lerp" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/control_log_sender_light.py b/openshock/rest/models/control_log_sender_light.py new file mode 100644 index 0000000..aaa306f --- /dev/null +++ b/openshock/rest/models/control_log_sender_light.py @@ -0,0 +1,93 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ControlLogSenderLight") + + +@_attrs_define +class ControlLogSenderLight: + """ + Attributes: + id (UUID): + name (str): + image (str): + custom_name (None | str): + """ + + id: UUID + name: str + image: str + custom_name: None | str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + image = self.image + + custom_name: None | str + custom_name = self.custom_name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "image": image, + "customName": custom_name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + image = d.pop("image") + + def _parse_custom_name(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + custom_name = _parse_custom_name(d.pop("customName")) + + control_log_sender_light = cls( + id=id, + name=name, + image=image, + custom_name=custom_name, + ) + + control_log_sender_light.additional_properties = d + return control_log_sender_light + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/control_request.py b/openshock/rest/models/control_request.py new file mode 100644 index 0000000..9373f5f --- /dev/null +++ b/openshock/rest/models/control_request.py @@ -0,0 +1,98 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.control import Control + + +T = TypeVar("T", bound="ControlRequest") + + +@_attrs_define +class ControlRequest: + """ + Attributes: + shocks (list[Control]): + custom_name (None | str | Unset): + """ + + shocks: list[Control] + custom_name: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + shocks = [] + for shocks_item_data in self.shocks: + shocks_item = shocks_item_data.to_dict() + shocks.append(shocks_item) + + custom_name: None | str | Unset + if isinstance(self.custom_name, Unset): + custom_name = UNSET + else: + custom_name = self.custom_name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "shocks": shocks, + } + ) + if custom_name is not UNSET: + field_dict["customName"] = custom_name + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control import Control # noqa: PLC0415 + + d = dict(src_dict) + shocks = [] + _shocks = d.pop("shocks") + for shocks_item_data in _shocks: + shocks_item = Control.from_dict(shocks_item_data) + + shocks.append(shocks_item) + + def _parse_custom_name(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + custom_name = _parse_custom_name(d.pop("customName", UNSET)) + + control_request = cls( + shocks=shocks, + custom_name=custom_name, + ) + + control_request.additional_properties = d + return control_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/control_stat_changes_request.py b/openshock/rest/models/control_stat_changes_request.py new file mode 100644 index 0000000..0c825af --- /dev/null +++ b/openshock/rest/models/control_stat_changes_request.py @@ -0,0 +1,105 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="ControlStatChangesRequest") + + +@_attrs_define +class ControlStatChangesRequest: + """ + Attributes: + user_ids (list[UUID]): The users the caller is interested in, only these are ever reported. + since (datetime.datetime | None | Unset): The cursor returned by the previous call, omit for an initial sync of + every requested user. + """ + + user_ids: list[UUID] + since: datetime.datetime | None | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + user_ids = [] + for user_ids_item_data in self.user_ids: + user_ids_item = str(user_ids_item_data) + user_ids.append(user_ids_item) + + since: None | str | Unset + if isinstance(self.since, Unset): + since = UNSET + elif isinstance(self.since, datetime.datetime): + since = self.since.isoformat() + else: + since = self.since + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "userIds": user_ids, + } + ) + if since is not UNSET: + field_dict["since"] = since + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + user_ids = [] + _user_ids = d.pop("userIds") + for user_ids_item_data in _user_ids: + user_ids_item = UUID(user_ids_item_data) + + user_ids.append(user_ids_item) + + def _parse_since(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + since_type_1 = datetime.datetime.fromisoformat(data) + + return since_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + since = _parse_since(d.pop("since", UNSET)) + + control_stat_changes_request = cls( + user_ids=user_ids, + since=since, + ) + + control_stat_changes_request.additional_properties = d + return control_stat_changes_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/control_stat_changes_response.py b/openshock/rest/models/control_stat_changes_response.py new file mode 100644 index 0000000..8b62481 --- /dev/null +++ b/openshock/rest/models/control_stat_changes_response.py @@ -0,0 +1,85 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.user_control_stat_totals import UserControlStatTotals + + +T = TypeVar("T", bound="ControlStatChangesResponse") + + +@_attrs_define +class ControlStatChangesResponse: + """ + Attributes: + cursor (datetime.datetime): Pass as `since` on the next call. + users (list[UserControlStatTotals]): + """ + + cursor: datetime.datetime + users: list[UserControlStatTotals] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + cursor = self.cursor.isoformat() + + users = [] + for users_item_data in self.users: + users_item = users_item_data.to_dict() + users.append(users_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "cursor": cursor, + "users": users, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.user_control_stat_totals import UserControlStatTotals # noqa: PLC0415 + + d = dict(src_dict) + cursor = datetime.datetime.fromisoformat(d.pop("cursor")) + + users = [] + _users = d.pop("users") + for users_item_data in _users: + users_item = UserControlStatTotals.from_dict(users_item_data) + + users.append(users_item) + + control_stat_changes_response = cls( + cursor=cursor, + users=users, + ) + + control_stat_changes_response.additional_properties = d + return control_stat_changes_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/control_stat_totals.py b/openshock/rest/models/control_stat_totals.py new file mode 100644 index 0000000..0439ec9 --- /dev/null +++ b/openshock/rest/models/control_stat_totals.py @@ -0,0 +1,105 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.control_type import ControlType + +T = TypeVar("T", bound="ControlStatTotals") + + +@_attrs_define +class ControlStatTotals: + """Aggregated activity of one control type, split by whether it was live control. + + Attributes: + type_ (ControlType): + live (bool): + count (int): Number of controls, for live control the number of continuous bursts. + duration_ms (int): + average_intensity (float): Average intensity weighted by duration. + max_intensity (int): + """ + + type_: ControlType + live: bool + count: int + duration_ms: int + average_intensity: float + max_intensity: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + type_ = self.type_.value + + live = self.live + + count = self.count + + duration_ms = self.duration_ms + + average_intensity = self.average_intensity + + max_intensity = self.max_intensity + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "type": type_, + "live": live, + "count": count, + "durationMs": duration_ms, + "averageIntensity": average_intensity, + "maxIntensity": max_intensity, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + type_ = ControlType(d.pop("type")) + + live = d.pop("live") + + count = d.pop("count") + + duration_ms = d.pop("durationMs") + + average_intensity = d.pop("averageIntensity") + + max_intensity = d.pop("maxIntensity") + + control_stat_totals = cls( + type_=type_, + live=live, + count=count, + duration_ms=duration_ms, + average_intensity=average_intensity, + max_intensity=max_intensity, + ) + + control_stat_totals.additional_properties = d + return control_stat_totals + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/control_stats_response.py b/openshock/rest/models/control_stats_response.py new file mode 100644 index 0000000..5571466 --- /dev/null +++ b/openshock/rest/models/control_stats_response.py @@ -0,0 +1,78 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.given_control_stats import GivenControlStats + from ..models.received_control_stats import ReceivedControlStats + + +T = TypeVar("T", bound="ControlStatsResponse") + + +@_attrs_define +class ControlStatsResponse: + """ + Attributes: + received (ReceivedControlStats): + given (GivenControlStats): + """ + + received: ReceivedControlStats + given: GivenControlStats + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + received = self.received.to_dict() + + given = self.given.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "received": received, + "given": given, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.given_control_stats import GivenControlStats # noqa: PLC0415 + from ..models.received_control_stats import ReceivedControlStats # noqa: PLC0415 + + d = dict(src_dict) + received = ReceivedControlStats.from_dict(d.pop("received")) + + given = GivenControlStats.from_dict(d.pop("given")) + + control_stats_response = cls( + received=received, + given=given, + ) + + control_stats_response.additional_properties = d + return control_stats_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/control_type.py b/openshock/rest/models/control_type.py new file mode 100644 index 0000000..c764409 --- /dev/null +++ b/openshock/rest/models/control_type.py @@ -0,0 +1,12 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class ControlType(StrEnum): + SHOCK = "Shock" + SOUND = "Sound" + STOP = "Stop" + VIBRATE = "Vibrate" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/create_automation_token_dto.py b/openshock/rest/models/create_automation_token_dto.py new file mode 100644 index 0000000..00e0bf8 --- /dev/null +++ b/openshock/rest/models/create_automation_token_dto.py @@ -0,0 +1,112 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="CreateAutomationTokenDto") + + +@_attrs_define +class CreateAutomationTokenDto: + """ + Attributes: + name (str): + types (list[AutomationTokenType]): + auto_cleanup_users (bool | Unset): Whether the automated accounts this token creates are deleted once TimeSpan? + CreateAutomationTokenDto.AutoCleanupAfter has + passed since they were created. Off by default; accounts the token didn't create are never deleted. + auto_cleanup_after (None | str | Unset): + """ + + name: str + types: list[AutomationTokenType] + auto_cleanup_users: bool | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + types = [] + for types_item_data in self.types: + types_item = types_item_data.value + types.append(types_item) + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "types": types, + } + ) + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + types = [] + _types = d.pop("types") + for types_item_data in _types: + types_item = AutomationTokenType(types_item_data) + + types.append(types_item) + + auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + create_automation_token_dto = cls( + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + create_automation_token_dto.additional_properties = d + return create_automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/create_share_request.py b/openshock/rest/models/create_share_request.py new file mode 100644 index 0000000..28a1dd0 --- /dev/null +++ b/openshock/rest/models/create_share_request.py @@ -0,0 +1,109 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.shocker_perm_limit_pair_with_id import ShockerPermLimitPairWithId + + +T = TypeVar("T", bound="CreateShareRequest") + + +@_attrs_define +class CreateShareRequest: + """ + Attributes: + shockers (list[ShockerPermLimitPairWithId]): + user (None | Unset | UUID): + """ + + shockers: list[ShockerPermLimitPairWithId] + user: None | Unset | UUID = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + user: None | str | Unset + if isinstance(self.user, Unset): + user = UNSET + elif isinstance(self.user, UUID): + user = str(self.user) + else: + user = self.user + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "shockers": shockers, + } + ) + if user is not UNSET: + field_dict["user"] = user + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_perm_limit_pair_with_id import ShockerPermLimitPairWithId # noqa: PLC0415 + + d = dict(src_dict) + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = ShockerPermLimitPairWithId.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + def _parse_user(data: object) -> None | Unset | UUID: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + user_type_1 = UUID(data) + + return user_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | Unset | UUID, data) + + user = _parse_user(d.pop("user", UNSET)) + + create_share_request = cls( + shockers=shockers, + user=user, + ) + + create_share_request.additional_properties = d + return create_share_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/create_token_request_v2.py b/openshock/rest/models/create_token_request_v2.py new file mode 100644 index 0000000..7dfea1a --- /dev/null +++ b/openshock/rest/models/create_token_request_v2.py @@ -0,0 +1,127 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.shocker_control_settings import ShockerControlSettings + + +T = TypeVar("T", bound="CreateTokenRequestV2") + + +@_attrs_define +class CreateTokenRequestV2: + """ + Attributes: + name (str): + permissions (list[PermissionType]): + shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits + for intensity and duration. + valid_until (datetime.datetime | None | Unset): + """ + + name: str + permissions: list[PermissionType] + shocker_control: ShockerControlSettings + valid_until: datetime.datetime | None | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + shocker_control = self.shocker_control.to_dict() + + valid_until: None | str | Unset + if isinstance(self.valid_until, Unset): + valid_until = UNSET + elif isinstance(self.valid_until, datetime.datetime): + valid_until = self.valid_until.isoformat() + else: + valid_until = self.valid_until + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "permissions": permissions, + "shockerControl": shocker_control, + } + ) + if valid_until is not UNSET: + field_dict["validUntil"] = valid_until + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 + + d = dict(src_dict) + name = d.pop("name") + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) + + def _parse_valid_until(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + valid_until_type_1 = datetime.datetime.fromisoformat(data) + + return valid_until_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + valid_until = _parse_valid_until(d.pop("validUntil", UNSET)) + + create_token_request_v2 = cls( + name=name, + permissions=permissions, + shocker_control=shocker_control, + valid_until=valid_until, + ) + + create_token_request_v2.additional_properties = d + return create_token_request_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/created_automation_token_dto.py b/openshock/rest/models/created_automation_token_dto.py new file mode 100644 index 0000000..882a7e2 --- /dev/null +++ b/openshock/rest/models/created_automation_token_dto.py @@ -0,0 +1,166 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="CreatedAutomationTokenDto") + + +@_attrs_define +class CreatedAutomationTokenDto: + """ + Attributes: + id (UUID): + name (str): + secret (str): + types (list[AutomationTokenType]): + created_at (datetime.datetime): + last_rotated_at (datetime.datetime | None | Unset): + auto_cleanup_users (bool | Unset): + auto_cleanup_after (None | str | Unset): + """ + + id: UUID + name: str + secret: str + types: list[AutomationTokenType] + created_at: datetime.datetime + last_rotated_at: datetime.datetime | None | Unset = UNSET + auto_cleanup_users: bool | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + secret = self.secret + + types = [] + for types_item_data in self.types: + types_item = types_item_data.value + types.append(types_item) + + created_at = self.created_at.isoformat() + + last_rotated_at: None | str | Unset + if isinstance(self.last_rotated_at, Unset): + last_rotated_at = UNSET + elif isinstance(self.last_rotated_at, datetime.datetime): + last_rotated_at = self.last_rotated_at.isoformat() + else: + last_rotated_at = self.last_rotated_at + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "secret": secret, + "types": types, + "createdAt": created_at, + } + ) + if last_rotated_at is not UNSET: + field_dict["lastRotatedAt"] = last_rotated_at + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + secret = d.pop("secret") + + types = [] + _types = d.pop("types") + for types_item_data in _types: + types_item = AutomationTokenType(types_item_data) + + types.append(types_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) + + return last_rotated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) + + auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + created_automation_token_dto = cls( + id=id, + name=name, + secret=secret, + types=types, + created_at=created_at, + last_rotated_at=last_rotated_at, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + created_automation_token_dto.additional_properties = d + return created_automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/daily_control_stats.py b/openshock/rest/models/daily_control_stats.py new file mode 100644 index 0000000..46709d7 --- /dev/null +++ b/openshock/rest/models/daily_control_stats.py @@ -0,0 +1,85 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.control_stat_totals import ControlStatTotals + + +T = TypeVar("T", bound="DailyControlStats") + + +@_attrs_define +class DailyControlStats: + """ + Attributes: + date (datetime.date): Day in the requested time zone. + stats (list[ControlStatTotals]): + """ + + date: datetime.date + stats: list[ControlStatTotals] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + date = self.date.isoformat() + + stats = [] + for stats_item_data in self.stats: + stats_item = stats_item_data.to_dict() + stats.append(stats_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "date": date, + "stats": stats, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control_stat_totals import ControlStatTotals # noqa: PLC0415 + + d = dict(src_dict) + date = datetime.date.fromisoformat(d.pop("date")) + + stats = [] + _stats = d.pop("stats") + for stats_item_data in _stats: + stats_item = ControlStatTotals.from_dict(stats_item_data) + + stats.append(stats_item) + + daily_control_stats = cls( + date=date, + stats=stats, + ) + + daily_control_stats.additional_properties = d + return daily_control_stats + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/device_response.py b/openshock/rest/models/device_response.py new file mode 100644 index 0000000..b7e1864 --- /dev/null +++ b/openshock/rest/models/device_response.py @@ -0,0 +1,80 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="DeviceResponse") + + +@_attrs_define +class DeviceResponse: + """ + Attributes: + id (UUID): + name (str): + created_on (datetime.datetime): + """ + + id: UUID + name: str + created_on: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_on = self.created_on.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdOn": created_on, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + device_response = cls( + id=id, + name=name, + created_on=created_on, + ) + + device_response.additional_properties = d + return device_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/device_self_response.py b/openshock/rest/models/device_self_response.py new file mode 100644 index 0000000..4917858 --- /dev/null +++ b/openshock/rest/models/device_self_response.py @@ -0,0 +1,93 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.minimal_shocker import MinimalShocker + + +T = TypeVar("T", bound="DeviceSelfResponse") + + +@_attrs_define +class DeviceSelfResponse: + """ + Attributes: + id (UUID): + name (str): + shockers (list[MinimalShocker]): + """ + + id: UUID + name: str + shockers: list[MinimalShocker] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "shockers": shockers, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.minimal_shocker import MinimalShocker # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = MinimalShocker.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + device_self_response = cls( + id=id, + name=name, + shockers=shockers, + ) + + device_self_response.additional_properties = d + return device_self_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/device_with_shockers_response.py b/openshock/rest/models/device_with_shockers_response.py new file mode 100644 index 0000000..dc8c698 --- /dev/null +++ b/openshock/rest/models/device_with_shockers_response.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_response import ShockerResponse + + +T = TypeVar("T", bound="DeviceWithShockersResponse") + + +@_attrs_define +class DeviceWithShockersResponse: + """ + Attributes: + shockers (list[ShockerResponse]): + id (UUID): + name (str): + created_on (datetime.datetime): + """ + + shockers: list[ShockerResponse] + id: UUID + name: str + created_on: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + id = str(self.id) + + name = self.name + + created_on = self.created_on.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "shockers": shockers, + "id": id, + "name": name, + "createdOn": created_on, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_response import ShockerResponse # noqa: PLC0415 + + d = dict(src_dict) + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = ShockerResponse.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + device_with_shockers_response = cls( + shockers=shockers, + id=id, + name=name, + created_on=created_on, + ) + + device_with_shockers_response.additional_properties = d + return device_with_shockers_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/device_with_token_response.py b/openshock/rest/models/device_with_token_response.py new file mode 100644 index 0000000..3e085c2 --- /dev/null +++ b/openshock/rest/models/device_with_token_response.py @@ -0,0 +1,95 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="DeviceWithTokenResponse") + + +@_attrs_define +class DeviceWithTokenResponse: + """ + Attributes: + token (None | str): + id (UUID): + name (str): + created_on (datetime.datetime): + """ + + token: None | str + id: UUID + name: str + created_on: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token: None | str + token = self.token + + id = str(self.id) + + name = self.name + + created_on = self.created_on.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "token": token, + "id": id, + "name": name, + "createdOn": created_on, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_token(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + token = _parse_token(d.pop("token")) + + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + device_with_token_response = cls( + token=token, + id=id, + name=name, + created_on=created_on, + ) + + device_with_token_response.additional_properties = d + return device_with_token_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/duration_limit_settings.py b/openshock/rest/models/duration_limit_settings.py new file mode 100644 index 0000000..a24b40d --- /dev/null +++ b/openshock/rest/models/duration_limit_settings.py @@ -0,0 +1,90 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.control_limit_mode import ControlLimitMode +from ..types import UNSET, Unset + +T = TypeVar("T", bound="DurationLimitSettings") + + +@_attrs_define +class DurationLimitSettings: + """ + Attributes: + min_ (int): + max_ (int): + mode (ControlLimitMode | Unset): Determines how a per-token min/max limit is applied to an incoming control + value. + """ + + min_: int + max_: int + mode: ControlLimitMode | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + min_ = self.min_ + + max_ = self.max_ + + mode: str | Unset = UNSET + if not isinstance(self.mode, Unset): + mode = self.mode.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "min": min_, + "max": max_, + } + ) + if mode is not UNSET: + field_dict["mode"] = mode + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + min_ = d.pop("min") + + max_ = d.pop("max") + + _mode = d.pop("mode", UNSET) + mode: ControlLimitMode | Unset + if isinstance(_mode, Unset): + mode = UNSET + else: + mode = ControlLimitMode(_mode) + + duration_limit_settings = cls( + min_=min_, + max_=max_, + mode=mode, + ) + + duration_limit_settings.additional_properties = d + return duration_limit_settings + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/edit_token_request_v2.py b/openshock/rest/models/edit_token_request_v2.py new file mode 100644 index 0000000..3cd7cfa --- /dev/null +++ b/openshock/rest/models/edit_token_request_v2.py @@ -0,0 +1,95 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType + +if TYPE_CHECKING: + from ..models.shocker_control_settings import ShockerControlSettings + + +T = TypeVar("T", bound="EditTokenRequestV2") + + +@_attrs_define +class EditTokenRequestV2: + """ + Attributes: + name (str): + permissions (list[PermissionType]): + shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits + for intensity and duration. + """ + + name: str + permissions: list[PermissionType] + shocker_control: ShockerControlSettings + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + shocker_control = self.shocker_control.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "permissions": permissions, + "shockerControl": shocker_control, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 + + d = dict(src_dict) + name = d.pop("name") + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) + + edit_token_request_v2 = cls( + name=name, + permissions=permissions, + shocker_control=shocker_control, + ) + + edit_token_request_v2.additional_properties = d + return edit_token_request_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_request.py b/openshock/rest/models/email_outbox_bulk_request.py new file mode 100644 index 0000000..fcf889f --- /dev/null +++ b/openshock/rest/models/email_outbox_bulk_request.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxBulkRequest") + + +@_attrs_define +class EmailOutboxBulkRequest: + """A set of email outbox message ids to apply a bulk requeue/cancel/delete to. + + Attributes: + ids (list[UUID]): + """ + + ids: list[UUID] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + ids = [] + for ids_item_data in self.ids: + ids_item = str(ids_item_data) + ids.append(ids_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "ids": ids, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + ids = [] + _ids = d.pop("ids") + for ids_item_data in _ids: + ids_item = UUID(ids_item_data) + + ids.append(ids_item) + + email_outbox_bulk_request = cls( + ids=ids, + ) + + email_outbox_bulk_request.additional_properties = d + return email_outbox_bulk_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_result_dto.py b/openshock/rest/models/email_outbox_bulk_result_dto.py new file mode 100644 index 0000000..2d7ad4f --- /dev/null +++ b/openshock/rest/models/email_outbox_bulk_result_dto.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxBulkResultDto") + + +@_attrs_define +class EmailOutboxBulkResultDto: + """Outcome of a bulk email outbox operation: how many ids were requested and how many rows were + actually affected (rows that were missing or in an ineligible state are silently not counted). + + Attributes: + requested (int): + affected (int): + """ + + requested: int + affected: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + requested = self.requested + + affected = self.affected + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "requested": requested, + "affected": affected, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + requested = d.pop("requested") + + affected = d.pop("affected") + + email_outbox_bulk_result_dto = cls( + requested=requested, + affected=affected, + ) + + email_outbox_bulk_result_dto.additional_properties = d + return email_outbox_bulk_result_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto.py b/openshock/rest/models/email_outbox_message_dto.py new file mode 100644 index 0000000..80d3e7c --- /dev/null +++ b/openshock/rest/models/email_outbox_message_dto.py @@ -0,0 +1,226 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.email_status import EmailStatus +from ..models.email_type import EmailType + +if TYPE_CHECKING: + from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload + + +T = TypeVar("T", bound="EmailOutboxMessageDto") + + +@_attrs_define +class EmailOutboxMessageDto: + """An EmailOutboxMessage as exposed to admins on the mail-queue page. Mirrors the row + verbatim - the outbox stores no rendered body and no usable secret, so every field is safe to show. + + Attributes: + id (UUID): + type_ (EmailType): The kind of email an outbox message represents. The outbox stores + only the intent to send one of these, never a rendered body or a usable secret, the + consumer maps the type to the matching template and (for token-bearing types) mints a fresh + secret at send time. + recipient (str): + recipient_name (None | str): + payload (EmailOutboxMessageDtoPayload): + coalesce_key (None | str): + status (EmailStatus): Delivery state of an email outbox message. + attempt_count (int): + next_attempt_at (datetime.datetime): + last_error (None | str): + created_at (datetime.datetime): + sent_at (datetime.datetime | None): + failed_at (datetime.datetime | None): + """ + + id: UUID + type_: EmailType + recipient: str + recipient_name: None | str + payload: EmailOutboxMessageDtoPayload + coalesce_key: None | str + status: EmailStatus + attempt_count: int + next_attempt_at: datetime.datetime + last_error: None | str + created_at: datetime.datetime + sent_at: datetime.datetime | None + failed_at: datetime.datetime | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + type_ = self.type_.value + + recipient = self.recipient + + recipient_name: None | str + recipient_name = self.recipient_name + + payload = self.payload.to_dict() + + coalesce_key: None | str + coalesce_key = self.coalesce_key + + status = self.status.value + + attempt_count = self.attempt_count + + next_attempt_at = self.next_attempt_at.isoformat() + + last_error: None | str + last_error = self.last_error + + created_at = self.created_at.isoformat() + + sent_at: None | str + if isinstance(self.sent_at, datetime.datetime): + sent_at = self.sent_at.isoformat() + else: + sent_at = self.sent_at + + failed_at: None | str + if isinstance(self.failed_at, datetime.datetime): + failed_at = self.failed_at.isoformat() + else: + failed_at = self.failed_at + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "type": type_, + "recipient": recipient, + "recipientName": recipient_name, + "payload": payload, + "coalesceKey": coalesce_key, + "status": status, + "attemptCount": attempt_count, + "nextAttemptAt": next_attempt_at, + "lastError": last_error, + "createdAt": created_at, + "sentAt": sent_at, + "failedAt": failed_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + type_ = EmailType(d.pop("type")) + + recipient = d.pop("recipient") + + def _parse_recipient_name(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + recipient_name = _parse_recipient_name(d.pop("recipientName")) + + payload = EmailOutboxMessageDtoPayload.from_dict(d.pop("payload")) + + def _parse_coalesce_key(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + coalesce_key = _parse_coalesce_key(d.pop("coalesceKey")) + + status = EmailStatus(d.pop("status")) + + attempt_count = d.pop("attemptCount") + + next_attempt_at = datetime.datetime.fromisoformat(d.pop("nextAttemptAt")) + + def _parse_last_error(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + last_error = _parse_last_error(d.pop("lastError")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_sent_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + sent_at_type_1 = datetime.datetime.fromisoformat(data) + + return sent_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + sent_at = _parse_sent_at(d.pop("sentAt")) + + def _parse_failed_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + failed_at_type_1 = datetime.datetime.fromisoformat(data) + + return failed_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + failed_at = _parse_failed_at(d.pop("failedAt")) + + email_outbox_message_dto = cls( + id=id, + type_=type_, + recipient=recipient, + recipient_name=recipient_name, + payload=payload, + coalesce_key=coalesce_key, + status=status, + attempt_count=attempt_count, + next_attempt_at=next_attempt_at, + last_error=last_error, + created_at=created_at, + sent_at=sent_at, + failed_at=failed_at, + ) + + email_outbox_message_dto.additional_properties = d + return email_outbox_message_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto_payload.py b/openshock/rest/models/email_outbox_message_dto_payload.py new file mode 100644 index 0000000..2db2ad1 --- /dev/null +++ b/openshock/rest/models/email_outbox_message_dto_payload.py @@ -0,0 +1,46 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxMessageDtoPayload") + + +@_attrs_define +class EmailOutboxMessageDtoPayload: + additional_properties: dict[str, str] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + email_outbox_message_dto_payload = cls() + + email_outbox_message_dto_payload.additional_properties = d + return email_outbox_message_dto_payload + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> str: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: str) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_stats_dto.py b/openshock/rest/models/email_outbox_stats_dto.py new file mode 100644 index 0000000..1cd818c --- /dev/null +++ b/openshock/rest/models/email_outbox_stats_dto.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxStatsDto") + + +@_attrs_define +class EmailOutboxStatsDto: + """Count of email outbox rows in each delivery state, for the admin mail-queue overview tiles. + + Attributes: + pending (int): + sending (int): + sent (int): + failed (int): + skipped (int): + total (int): + """ + + pending: int + sending: int + sent: int + failed: int + skipped: int + total: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + pending = self.pending + + sending = self.sending + + sent = self.sent + + failed = self.failed + + skipped = self.skipped + + total = self.total + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "pending": pending, + "sending": sending, + "sent": sent, + "failed": failed, + "skipped": skipped, + "total": total, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + pending = d.pop("pending") + + sending = d.pop("sending") + + sent = d.pop("sent") + + failed = d.pop("failed") + + skipped = d.pop("skipped") + + total = d.pop("total") + + email_outbox_stats_dto = cls( + pending=pending, + sending=sending, + sent=sent, + failed=failed, + skipped=skipped, + total=total, + ) + + email_outbox_stats_dto.additional_properties = d + return email_outbox_stats_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_provider_blacklist_dto.py b/openshock/rest/models/email_provider_blacklist_dto.py new file mode 100644 index 0000000..53a85f4 --- /dev/null +++ b/openshock/rest/models/email_provider_blacklist_dto.py @@ -0,0 +1,80 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailProviderBlacklistDto") + + +@_attrs_define +class EmailProviderBlacklistDto: + """ + Attributes: + id (UUID): + domain (str): + created_at (datetime.datetime): + """ + + id: UUID + domain: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + domain = self.domain + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "domain": domain, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + domain = d.pop("domain") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + email_provider_blacklist_dto = cls( + id=id, + domain=domain, + created_at=created_at, + ) + + email_provider_blacklist_dto.additional_properties = d + return email_provider_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_status.py b/openshock/rest/models/email_status.py new file mode 100644 index 0000000..12e74f7 --- /dev/null +++ b/openshock/rest/models/email_status.py @@ -0,0 +1,13 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class EmailStatus(StrEnum): + FAILED = "Failed" + PENDING = "Pending" + SENDING = "Sending" + SENT = "Sent" + SKIPPED = "Skipped" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/email_type.py b/openshock/rest/models/email_type.py new file mode 100644 index 0000000..a778271 --- /dev/null +++ b/openshock/rest/models/email_type.py @@ -0,0 +1,12 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class EmailType(StrEnum): + ACCOUNTACTIVATION = "AccountActivation" + EMAILCHANGENOTICE = "EmailChangeNotice" + EMAILVERIFICATION = "EmailVerification" + PASSWORDRESET = "PasswordReset" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/given_control_stats.py b/openshock/rest/models/given_control_stats.py new file mode 100644 index 0000000..c01396d --- /dev/null +++ b/openshock/rest/models/given_control_stats.py @@ -0,0 +1,94 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.control_stat_totals import ControlStatTotals + from ..models.user_control_stats import UserControlStats + + +T = TypeVar("T", bound="GivenControlStats") + + +@_attrs_define +class GivenControlStats: + """ + Attributes: + totals (list[ControlStatTotals]): + owners (list[UserControlStats]): + """ + + totals: list[ControlStatTotals] + owners: list[UserControlStats] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + totals = [] + for totals_item_data in self.totals: + totals_item = totals_item_data.to_dict() + totals.append(totals_item) + + owners = [] + for owners_item_data in self.owners: + owners_item = owners_item_data.to_dict() + owners.append(owners_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "totals": totals, + "owners": owners, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control_stat_totals import ControlStatTotals # noqa: PLC0415 + from ..models.user_control_stats import UserControlStats # noqa: PLC0415 + + d = dict(src_dict) + totals = [] + _totals = d.pop("totals") + for totals_item_data in _totals: + totals_item = ControlStatTotals.from_dict(totals_item_data) + + totals.append(totals_item) + + owners = [] + _owners = d.pop("owners") + for owners_item_data in _owners: + owners_item = UserControlStats.from_dict(owners_item_data) + + owners.append(owners_item) + + given_control_stats = cls( + totals=totals, + owners=owners, + ) + + given_control_stats.additional_properties = d + return given_control_stats + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/hub_create_request.py b/openshock/rest/models/hub_create_request.py new file mode 100644 index 0000000..cda3276 --- /dev/null +++ b/openshock/rest/models/hub_create_request.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="HubCreateRequest") + + +@_attrs_define +class HubCreateRequest: + """ + Attributes: + name (str): + """ + + name: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + hub_create_request = cls( + name=name, + ) + + hub_create_request.additional_properties = d + return hub_create_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/hub_edit_request.py b/openshock/rest/models/hub_edit_request.py new file mode 100644 index 0000000..9d284a7 --- /dev/null +++ b/openshock/rest/models/hub_edit_request.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="HubEditRequest") + + +@_attrs_define +class HubEditRequest: + """ + Attributes: + name (str): + """ + + name: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + hub_edit_request = cls( + name=name, + ) + + hub_edit_request.additional_properties = d + return hub_edit_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/intensity_limit_settings.py b/openshock/rest/models/intensity_limit_settings.py new file mode 100644 index 0000000..46d07cf --- /dev/null +++ b/openshock/rest/models/intensity_limit_settings.py @@ -0,0 +1,80 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.control_limit_mode import ControlLimitMode + +T = TypeVar("T", bound="IntensityLimitSettings") + + +@_attrs_define +class IntensityLimitSettings: + """ + Attributes: + min_ (int): + max_ (int): + mode (ControlLimitMode): Determines how a per-token min/max limit is applied to an incoming control value. + """ + + min_: int + max_: int + mode: ControlLimitMode + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + min_ = self.min_ + + max_ = self.max_ + + mode = self.mode.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "min": min_, + "max": max_, + "mode": mode, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + min_ = d.pop("min") + + max_ = d.pop("max") + + mode = ControlLimitMode(d.pop("mode")) + + intensity_limit_settings = cls( + min_=min_, + max_=max_, + mode=mode, + ) + + intensity_limit_settings.additional_properties = d + return intensity_limit_settings + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/lcg_node_response_v2.py b/openshock/rest/models/lcg_node_response_v2.py new file mode 100644 index 0000000..efdd977 --- /dev/null +++ b/openshock/rest/models/lcg_node_response_v2.py @@ -0,0 +1,86 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="LcgNodeResponseV2") + + +@_attrs_define +class LcgNodeResponseV2: + """ + Attributes: + host (str): + port (int): + path (str): + country (str): + """ + + host: str + port: int + path: str + country: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + host = self.host + + port = self.port + + path = self.path + + country = self.country + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "host": host, + "port": port, + "path": path, + "country": country, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + host = d.pop("host") + + port = d.pop("port") + + path = d.pop("path") + + country = d.pop("country") + + lcg_node_response_v2 = cls( + host=host, + port=port, + path=path, + country=country, + ) + + lcg_node_response_v2.additional_properties = d + return lcg_node_response_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/lcg_response_v2.py b/openshock/rest/models/lcg_response_v2.py new file mode 100644 index 0000000..370925c --- /dev/null +++ b/openshock/rest/models/lcg_response_v2.py @@ -0,0 +1,87 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="LcgResponseV2") + + +@_attrs_define +class LcgResponseV2: + """ + Attributes: + host (str): Public host of the gateway the hub is connected to. + port (int): Public port to connect to (default 443). + path_prefix (str): Base path prefix the gateway is served under, e.g. "/gateway" (empty for root). The client + builds the full URL and appends the live-control route (`/1/ws/live/{hubId}`) itself. + country (str): + """ + + host: str + port: int + path_prefix: str + country: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + host = self.host + + port = self.port + + path_prefix = self.path_prefix + + country = self.country + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "host": host, + "port": port, + "pathPrefix": path_prefix, + "country": country, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + host = d.pop("host") + + port = d.pop("port") + + path_prefix = d.pop("pathPrefix") + + country = d.pop("country") + + lcg_response_v2 = cls( + host=host, + port=port, + path_prefix=path_prefix, + country=country, + ) + + lcg_response_v2.additional_properties = d + return lcg_response_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py b/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py new file mode 100644 index 0000000..8aa0cb9 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_online_device_response import AdminOnlineDeviceResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse") + + +@_attrs_define +class LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse: + """ + Attributes: + message (str): Default: ''. + data (list[AdminOnlineDeviceResponse]): + """ + + data: list[AdminOnlineDeviceResponse] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_online_device_response import AdminOnlineDeviceResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = AdminOnlineDeviceResponse.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_admin_online_device_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_admin_online_device_response.additional_properties = d + return legacy_data_response_of_array_of_admin_online_device_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_device_response.py b/openshock/rest/models/legacy_data_response_of_array_of_device_response.py new file mode 100644 index 0000000..5f44a78 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_device_response.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.device_response import DeviceResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfDeviceResponse") + + +@_attrs_define +class LegacyDataResponseOfArrayOfDeviceResponse: + """ + Attributes: + message (str): Default: ''. + data (list[DeviceResponse]): + """ + + data: list[DeviceResponse] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.device_response import DeviceResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = DeviceResponse.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_device_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_device_response.additional_properties = d + return legacy_data_response_of_array_of_device_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_device_with_shockers_response.py b/openshock/rest/models/legacy_data_response_of_array_of_device_with_shockers_response.py new file mode 100644 index 0000000..92a5258 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_device_with_shockers_response.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.device_with_shockers_response import DeviceWithShockersResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfDeviceWithShockersResponse") + + +@_attrs_define +class LegacyDataResponseOfArrayOfDeviceWithShockersResponse: + """ + Attributes: + message (str): Default: ''. + data (list[DeviceWithShockersResponse]): + """ + + data: list[DeviceWithShockersResponse] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.device_with_shockers_response import DeviceWithShockersResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = DeviceWithShockersResponse.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_device_with_shockers_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_device_with_shockers_response.additional_properties = d + return legacy_data_response_of_array_of_device_with_shockers_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_log_entry.py b/openshock/rest/models/legacy_data_response_of_array_of_log_entry.py new file mode 100644 index 0000000..d9d48c3 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_log_entry.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.log_entry import LogEntry + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfLogEntry") + + +@_attrs_define +class LegacyDataResponseOfArrayOfLogEntry: + """ + Attributes: + message (str): Default: ''. + data (list[LogEntry]): + """ + + data: list[LogEntry] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.log_entry import LogEntry # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = LogEntry.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_log_entry = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_log_entry.additional_properties = d + return legacy_data_response_of_array_of_log_entry + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_own_public_share_response.py b/openshock/rest/models/legacy_data_response_of_array_of_own_public_share_response.py new file mode 100644 index 0000000..57ae041 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_own_public_share_response.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.own_public_share_response import OwnPublicShareResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfOwnPublicShareResponse") + + +@_attrs_define +class LegacyDataResponseOfArrayOfOwnPublicShareResponse: + """ + Attributes: + message (str): Default: ''. + data (list[OwnPublicShareResponse]): + """ + + data: list[OwnPublicShareResponse] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.own_public_share_response import OwnPublicShareResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = OwnPublicShareResponse.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_own_public_share_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_own_public_share_response.additional_properties = d + return legacy_data_response_of_array_of_own_public_share_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_owner_shocker_response.py b/openshock/rest/models/legacy_data_response_of_array_of_owner_shocker_response.py new file mode 100644 index 0000000..c292b45 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_owner_shocker_response.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.owner_shocker_response import OwnerShockerResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfOwnerShockerResponse") + + +@_attrs_define +class LegacyDataResponseOfArrayOfOwnerShockerResponse: + """ + Attributes: + message (str): Default: ''. + data (list[OwnerShockerResponse]): + """ + + data: list[OwnerShockerResponse] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.owner_shocker_response import OwnerShockerResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = OwnerShockerResponse.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_owner_shocker_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_owner_shocker_response.additional_properties = d + return legacy_data_response_of_array_of_owner_shocker_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_share_code_info.py b/openshock/rest/models/legacy_data_response_of_array_of_share_code_info.py new file mode 100644 index 0000000..dc232b2 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_share_code_info.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.share_code_info import ShareCodeInfo + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfShareCodeInfo") + + +@_attrs_define +class LegacyDataResponseOfArrayOfShareCodeInfo: + """ + Attributes: + message (str): Default: ''. + data (list[ShareCodeInfo]): + """ + + data: list[ShareCodeInfo] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.share_code_info import ShareCodeInfo # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = ShareCodeInfo.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_share_code_info = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_share_code_info.additional_properties = d + return legacy_data_response_of_array_of_share_code_info + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_share_info.py b/openshock/rest/models/legacy_data_response_of_array_of_share_info.py new file mode 100644 index 0000000..cc21677 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_share_info.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.share_info import ShareInfo + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfShareInfo") + + +@_attrs_define +class LegacyDataResponseOfArrayOfShareInfo: + """ + Attributes: + message (str): Default: ''. + data (list[ShareInfo]): + """ + + data: list[ShareInfo] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.share_info import ShareInfo # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = ShareInfo.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_share_info = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_share_info.additional_properties = d + return legacy_data_response_of_array_of_share_info + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_array_of_shocker_response.py b/openshock/rest/models/legacy_data_response_of_array_of_shocker_response.py new file mode 100644 index 0000000..3bec25d --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_shocker_response.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_response import ShockerResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfShockerResponse") + + +@_attrs_define +class LegacyDataResponseOfArrayOfShockerResponse: + """ + Attributes: + message (str): Default: ''. + data (list[ShockerResponse]): + """ + + data: list[ShockerResponse] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_response import ShockerResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = ShockerResponse.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_shocker_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_shocker_response.additional_properties = d + return legacy_data_response_of_array_of_shocker_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_backend_info_response.py b/openshock/rest/models/legacy_data_response_of_backend_info_response.py new file mode 100644 index 0000000..9a17332 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_backend_info_response.py @@ -0,0 +1,76 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.backend_info_response import BackendInfoResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfBackendInfoResponse") + + +@_attrs_define +class LegacyDataResponseOfBackendInfoResponse: + """ + Attributes: + message (str): Default: ''. + data (BackendInfoResponse): + """ + + data: BackendInfoResponse + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.backend_info_response import BackendInfoResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = BackendInfoResponse.from_dict(d.pop("data")) + + legacy_data_response_of_backend_info_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_backend_info_response.additional_properties = d + return legacy_data_response_of_backend_info_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_device_self_response.py b/openshock/rest/models/legacy_data_response_of_device_self_response.py new file mode 100644 index 0000000..b1c9aab --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_device_self_response.py @@ -0,0 +1,76 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.device_self_response import DeviceSelfResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfDeviceSelfResponse") + + +@_attrs_define +class LegacyDataResponseOfDeviceSelfResponse: + """ + Attributes: + message (str): Default: ''. + data (DeviceSelfResponse): + """ + + data: DeviceSelfResponse + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.device_self_response import DeviceSelfResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = DeviceSelfResponse.from_dict(d.pop("data")) + + legacy_data_response_of_device_self_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_device_self_response.additional_properties = d + return legacy_data_response_of_device_self_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_device_with_token_response.py b/openshock/rest/models/legacy_data_response_of_device_with_token_response.py new file mode 100644 index 0000000..b632b66 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_device_with_token_response.py @@ -0,0 +1,76 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.device_with_token_response import DeviceWithTokenResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfDeviceWithTokenResponse") + + +@_attrs_define +class LegacyDataResponseOfDeviceWithTokenResponse: + """ + Attributes: + message (str): Default: ''. + data (DeviceWithTokenResponse): + """ + + data: DeviceWithTokenResponse + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.device_with_token_response import DeviceWithTokenResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = DeviceWithTokenResponse.from_dict(d.pop("data")) + + legacy_data_response_of_device_with_token_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_device_with_token_response.additional_properties = d + return legacy_data_response_of_device_with_token_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_guid.py b/openshock/rest/models/legacy_data_response_of_guid.py new file mode 100644 index 0000000..bc4f2a5 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_guid.py @@ -0,0 +1,71 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="LegacyDataResponseOfGuid") + + +@_attrs_define +class LegacyDataResponseOfGuid: + """ + Attributes: + message (str): Default: ''. + data (UUID): + """ + + data: UUID + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = str(self.data) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + message = d.pop("message") + + data = UUID(d.pop("data")) + + legacy_data_response_of_guid = cls( + message=message, + data=data, + ) + + legacy_data_response_of_guid.additional_properties = d + return legacy_data_response_of_guid + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py b/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py new file mode 100644 index 0000000..757a667 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.ota_item import OtaItem + + +T = TypeVar("T", bound="LegacyDataResponseOfIReadOnlyCollectionOfOtaItem") + + +@_attrs_define +class LegacyDataResponseOfIReadOnlyCollectionOfOtaItem: + """ + Attributes: + message (str): Default: ''. + data (list[OtaItem]): + """ + + data: list[OtaItem] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.ota_item import OtaItem # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = OtaItem.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_i_read_only_collection_of_ota_item = cls( + message=message, + data=data, + ) + + legacy_data_response_of_i_read_only_collection_of_ota_item.additional_properties = d + return legacy_data_response_of_i_read_only_collection_of_ota_item + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_legacy_user_self_response.py b/openshock/rest/models/legacy_data_response_of_legacy_user_self_response.py new file mode 100644 index 0000000..aa5b909 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_legacy_user_self_response.py @@ -0,0 +1,77 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.legacy_user_self_response import LegacyUserSelfResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfLegacyUserSelfResponse") + + +@_attrs_define +class LegacyDataResponseOfLegacyUserSelfResponse: + """ + Attributes: + message (str): Default: ''. + data (LegacyUserSelfResponse): Response shape of the deprecated GET /1/users/self, kept for API token clients + that still read `rank`. + """ + + data: LegacyUserSelfResponse + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.legacy_user_self_response import LegacyUserSelfResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = LegacyUserSelfResponse.from_dict(d.pop("data")) + + legacy_data_response_of_legacy_user_self_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_legacy_user_self_response.additional_properties = d + return legacy_data_response_of_legacy_user_self_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_pause_reason.py b/openshock/rest/models/legacy_data_response_of_pause_reason.py new file mode 100644 index 0000000..525c6d4 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_pause_reason.py @@ -0,0 +1,78 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="LegacyDataResponseOfPauseReason") + + +@_attrs_define +class LegacyDataResponseOfPauseReason: + """ + Attributes: + message (str): Default: ''. + data (int): An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where + reasons are OR'd together. + + Each bit corresponds to: + - 1: Shocker + - 2: UserShare + - 4: PublicShare + + For example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons. + """ + + data: int + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + message = d.pop("message") + + data = d.pop("data") + + legacy_data_response_of_pause_reason = cls( + message=message, + data=data, + ) + + legacy_data_response_of_pause_reason.additional_properties = d + return legacy_data_response_of_pause_reason + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_public_share_response.py b/openshock/rest/models/legacy_data_response_of_public_share_response.py new file mode 100644 index 0000000..15389c7 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_public_share_response.py @@ -0,0 +1,76 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.public_share_response import PublicShareResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfPublicShareResponse") + + +@_attrs_define +class LegacyDataResponseOfPublicShareResponse: + """ + Attributes: + message (str): Default: ''. + data (PublicShareResponse): + """ + + data: PublicShareResponse + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.public_share_response import PublicShareResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = PublicShareResponse.from_dict(d.pop("data")) + + legacy_data_response_of_public_share_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_public_share_response.additional_properties = d + return legacy_data_response_of_public_share_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_shocker_with_device.py b/openshock/rest/models/legacy_data_response_of_shocker_with_device.py new file mode 100644 index 0000000..eedd1eb --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_shocker_with_device.py @@ -0,0 +1,76 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_with_device import ShockerWithDevice + + +T = TypeVar("T", bound="LegacyDataResponseOfShockerWithDevice") + + +@_attrs_define +class LegacyDataResponseOfShockerWithDevice: + """ + Attributes: + message (str): Default: ''. + data (ShockerWithDevice): + """ + + data: ShockerWithDevice + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_with_device import ShockerWithDevice # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = ShockerWithDevice.from_dict(d.pop("data")) + + legacy_data_response_of_shocker_with_device = cls( + message=message, + data=data, + ) + + legacy_data_response_of_shocker_with_device.additional_properties = d + return legacy_data_response_of_shocker_with_device + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_stats_response.py b/openshock/rest/models/legacy_data_response_of_stats_response.py new file mode 100644 index 0000000..ad3f22f --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_stats_response.py @@ -0,0 +1,76 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.stats_response import StatsResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfStatsResponse") + + +@_attrs_define +class LegacyDataResponseOfStatsResponse: + """ + Attributes: + message (str): Default: ''. + data (StatsResponse): + """ + + data: StatsResponse + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.stats_response import StatsResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = StatsResponse.from_dict(d.pop("data")) + + legacy_data_response_of_stats_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_stats_response.additional_properties = d + return legacy_data_response_of_stats_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_ofboolean.py b/openshock/rest/models/legacy_data_response_ofboolean.py new file mode 100644 index 0000000..6568102 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_ofboolean.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="LegacyDataResponseOfboolean") + + +@_attrs_define +class LegacyDataResponseOfboolean: + """ + Attributes: + message (str): Default: ''. + data (bool): + """ + + data: bool + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + message = d.pop("message") + + data = d.pop("data") + + legacy_data_response_ofboolean = cls( + message=message, + data=data, + ) + + legacy_data_response_ofboolean.additional_properties = d + return legacy_data_response_ofboolean + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_ofstring.py b/openshock/rest/models/legacy_data_response_ofstring.py new file mode 100644 index 0000000..6405577 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_ofstring.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="LegacyDataResponseOfstring") + + +@_attrs_define +class LegacyDataResponseOfstring: + """ + Attributes: + message (str): Default: ''. + data (str): + """ + + data: str + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + message = d.pop("message") + + data = d.pop("data") + + legacy_data_response_ofstring = cls( + message=message, + data=data, + ) + + legacy_data_response_ofstring.additional_properties = d + return legacy_data_response_ofstring + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_empty_response.py b/openshock/rest/models/legacy_empty_response.py new file mode 100644 index 0000000..2b74029 --- /dev/null +++ b/openshock/rest/models/legacy_empty_response.py @@ -0,0 +1,73 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="LegacyEmptyResponse") + + +@_attrs_define +class LegacyEmptyResponse: + """ + Attributes: + message (str): + data (Any | Unset): + """ + + message: str + data: Any | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = self.data + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + } + ) + if data is not UNSET: + field_dict["data"] = data + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + message = d.pop("message") + + data = d.pop("data", UNSET) + + legacy_empty_response = cls( + message=message, + data=data, + ) + + legacy_empty_response.additional_properties = d + return legacy_empty_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_user_self_response.py b/openshock/rest/models/legacy_user_self_response.py new file mode 100644 index 0000000..2b6f3b1 --- /dev/null +++ b/openshock/rest/models/legacy_user_self_response.py @@ -0,0 +1,122 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.role_type import RoleType + +T = TypeVar("T", bound="LegacyUserSelfResponse") + + +@_attrs_define +class LegacyUserSelfResponse: + """Response shape of the deprecated GET /1/users/self, kept for API token clients that still read `rank`. + + Attributes: + id (UUID): + name (str): + email (str): + image (str): + roles (list[RoleType]): + rank (str): + has_password (bool): + """ + + id: UUID + name: str + email: str + image: str + roles: list[RoleType] + rank: str + has_password: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + email = self.email + + image = self.image + + roles = [] + for roles_item_data in self.roles: + roles_item = roles_item_data.value + roles.append(roles_item) + + rank = self.rank + + has_password = self.has_password + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "email": email, + "image": image, + "roles": roles, + "rank": rank, + "hasPassword": has_password, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + email = d.pop("email") + + image = d.pop("image") + + roles = [] + _roles = d.pop("roles") + for roles_item_data in _roles: + roles_item = RoleType(roles_item_data) + + roles.append(roles_item) + + rank = d.pop("rank") + + has_password = d.pop("hasPassword") + + legacy_user_self_response = cls( + id=id, + name=name, + email=email, + image=image, + roles=roles, + rank=rank, + has_password=has_password, + ) + + legacy_user_self_response.additional_properties = d + return legacy_user_self_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/log_entry.py b/openshock/rest/models/log_entry.py new file mode 100644 index 0000000..f4adb0f --- /dev/null +++ b/openshock/rest/models/log_entry.py @@ -0,0 +1,120 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.control_type import ControlType + +if TYPE_CHECKING: + from ..models.control_log_sender_light import ControlLogSenderLight + + +T = TypeVar("T", bound="LogEntry") + + +@_attrs_define +class LogEntry: + """ + Attributes: + id (UUID): + created_on (datetime.datetime): + type_ (ControlType): + controlled_by (ControlLogSenderLight): + intensity (int): + duration (int): + live_control (bool): + """ + + id: UUID + created_on: datetime.datetime + type_: ControlType + controlled_by: ControlLogSenderLight + intensity: int + duration: int + live_control: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + created_on = self.created_on.isoformat() + + type_ = self.type_.value + + controlled_by = self.controlled_by.to_dict() + + intensity = self.intensity + + duration = self.duration + + live_control = self.live_control + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "createdOn": created_on, + "type": type_, + "controlledBy": controlled_by, + "intensity": intensity, + "duration": duration, + "liveControl": live_control, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control_log_sender_light import ControlLogSenderLight # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + type_ = ControlType(d.pop("type")) + + controlled_by = ControlLogSenderLight.from_dict(d.pop("controlledBy")) + + intensity = d.pop("intensity") + + duration = d.pop("duration") + + live_control = d.pop("liveControl") + + log_entry = cls( + id=id, + created_on=created_on, + type_=type_, + controlled_by=controlled_by, + intensity=intensity, + duration=duration, + live_control=live_control, + ) + + log_entry.additional_properties = d + return log_entry + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/log_entry_with_hub.py b/openshock/rest/models/log_entry_with_hub.py new file mode 100644 index 0000000..9b85577 --- /dev/null +++ b/openshock/rest/models/log_entry_with_hub.py @@ -0,0 +1,152 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.control_type import ControlType + +if TYPE_CHECKING: + from ..models.control_log_sender_light import ControlLogSenderLight + + +T = TypeVar("T", bound="LogEntryWithHub") + + +@_attrs_define +class LogEntryWithHub: + """ + Attributes: + id (UUID): + hub_id (UUID): + hub_name (str): + shocker_id (UUID): + shocker_name (str): + created_on (datetime.datetime): + type_ (ControlType): + controlled_by (ControlLogSenderLight): + intensity (int): + duration (int): + live_control (bool): + """ + + id: UUID + hub_id: UUID + hub_name: str + shocker_id: UUID + shocker_name: str + created_on: datetime.datetime + type_: ControlType + controlled_by: ControlLogSenderLight + intensity: int + duration: int + live_control: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + hub_id = str(self.hub_id) + + hub_name = self.hub_name + + shocker_id = str(self.shocker_id) + + shocker_name = self.shocker_name + + created_on = self.created_on.isoformat() + + type_ = self.type_.value + + controlled_by = self.controlled_by.to_dict() + + intensity = self.intensity + + duration = self.duration + + live_control = self.live_control + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "hubId": hub_id, + "hubName": hub_name, + "shockerId": shocker_id, + "shockerName": shocker_name, + "createdOn": created_on, + "type": type_, + "controlledBy": controlled_by, + "intensity": intensity, + "duration": duration, + "liveControl": live_control, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control_log_sender_light import ControlLogSenderLight # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + hub_id = UUID(d.pop("hubId")) + + hub_name = d.pop("hubName") + + shocker_id = UUID(d.pop("shockerId")) + + shocker_name = d.pop("shockerName") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + type_ = ControlType(d.pop("type")) + + controlled_by = ControlLogSenderLight.from_dict(d.pop("controlledBy")) + + intensity = d.pop("intensity") + + duration = d.pop("duration") + + live_control = d.pop("liveControl") + + log_entry_with_hub = cls( + id=id, + hub_id=hub_id, + hub_name=hub_name, + shocker_id=shocker_id, + shocker_name=shocker_name, + created_on=created_on, + type_=type_, + controlled_by=controlled_by, + intensity=intensity, + duration=duration, + live_control=live_control, + ) + + log_entry_with_hub.additional_properties = d + return log_entry_with_hub + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/login_session_response.py b/openshock/rest/models/login_session_response.py new file mode 100644 index 0000000..47328f3 --- /dev/null +++ b/openshock/rest/models/login_session_response.py @@ -0,0 +1,203 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="LoginSessionResponse") + + +@_attrs_define +class LoginSessionResponse: + """ + Attributes: + id (UUID): + ip (str): An IPv4 or IPv6 address in its textual form. + user_agent (str): + created (datetime.datetime): + expires (datetime.datetime): + last_used (datetime.datetime | None): + asn_org (None | str | Unset): + is_vpn (bool | None | Unset): + country_code (None | str | Unset): + city (None | str | Unset): + """ + + id: UUID + ip: str + user_agent: str + created: datetime.datetime + expires: datetime.datetime + last_used: datetime.datetime | None + asn_org: None | str | Unset = UNSET + is_vpn: bool | None | Unset = UNSET + country_code: None | str | Unset = UNSET + city: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + ip = self.ip + + user_agent = self.user_agent + + created = self.created.isoformat() + + expires = self.expires.isoformat() + + last_used: None | str + if isinstance(self.last_used, datetime.datetime): + last_used = self.last_used.isoformat() + else: + last_used = self.last_used + + asn_org: None | str | Unset + if isinstance(self.asn_org, Unset): + asn_org = UNSET + else: + asn_org = self.asn_org + + is_vpn: bool | None | Unset + if isinstance(self.is_vpn, Unset): + is_vpn = UNSET + else: + is_vpn = self.is_vpn + + country_code: None | str | Unset + if isinstance(self.country_code, Unset): + country_code = UNSET + else: + country_code = self.country_code + + city: None | str | Unset + if isinstance(self.city, Unset): + city = UNSET + else: + city = self.city + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "ip": ip, + "userAgent": user_agent, + "created": created, + "expires": expires, + "lastUsed": last_used, + } + ) + if asn_org is not UNSET: + field_dict["asnOrg"] = asn_org + if is_vpn is not UNSET: + field_dict["isVpn"] = is_vpn + if country_code is not UNSET: + field_dict["countryCode"] = country_code + if city is not UNSET: + field_dict["city"] = city + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + ip = d.pop("ip") + + user_agent = d.pop("userAgent") + + created = datetime.datetime.fromisoformat(d.pop("created")) + + expires = datetime.datetime.fromisoformat(d.pop("expires")) + + def _parse_last_used(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + last_used = _parse_last_used(d.pop("lastUsed")) + + def _parse_asn_org(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + asn_org = _parse_asn_org(d.pop("asnOrg", UNSET)) + + def _parse_is_vpn(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + is_vpn = _parse_is_vpn(d.pop("isVpn", UNSET)) + + def _parse_country_code(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + country_code = _parse_country_code(d.pop("countryCode", UNSET)) + + def _parse_city(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + city = _parse_city(d.pop("city", UNSET)) + + login_session_response = cls( + id=id, + ip=ip, + user_agent=user_agent, + created=created, + expires=expires, + last_used=last_used, + asn_org=asn_org, + is_vpn=is_vpn, + country_code=country_code, + city=city, + ) + + login_session_response.additional_properties = d + return login_session_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/login_v2.py b/openshock/rest/models/login_v2.py new file mode 100644 index 0000000..2111d42 --- /dev/null +++ b/openshock/rest/models/login_v2.py @@ -0,0 +1,78 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="LoginV2") + + +@_attrs_define +class LoginV2: + """ + Attributes: + password (str): + username_or_email (str): + turnstile_response (str): + """ + + password: str + username_or_email: str + turnstile_response: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + password = self.password + + username_or_email = self.username_or_email + + turnstile_response = self.turnstile_response + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "password": password, + "usernameOrEmail": username_or_email, + "turnstileResponse": turnstile_response, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + password = d.pop("password") + + username_or_email = d.pop("usernameOrEmail") + + turnstile_response = d.pop("turnstileResponse") + + login_v2 = cls( + password=password, + username_or_email=username_or_email, + turnstile_response=turnstile_response, + ) + + login_v2.additional_properties = d + return login_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/login_v2_ok_response.py b/openshock/rest/models/login_v2_ok_response.py new file mode 100644 index 0000000..27df451 --- /dev/null +++ b/openshock/rest/models/login_v2_ok_response.py @@ -0,0 +1,113 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.role_type import RoleType + +T = TypeVar("T", bound="LoginV2OkResponse") + + +@_attrs_define +class LoginV2OkResponse: + """ + Attributes: + account_id (UUID): + account_name (str): + account_email (str): + is_verified (bool): + profile_image (str): + account_roles (list[RoleType]): + """ + + account_id: UUID + account_name: str + account_email: str + is_verified: bool + profile_image: str + account_roles: list[RoleType] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + account_id = str(self.account_id) + + account_name = self.account_name + + account_email = self.account_email + + is_verified = self.is_verified + + profile_image = self.profile_image + + account_roles = [] + for account_roles_item_data in self.account_roles: + account_roles_item = account_roles_item_data.value + account_roles.append(account_roles_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "accountId": account_id, + "accountName": account_name, + "accountEmail": account_email, + "isVerified": is_verified, + "profileImage": profile_image, + "accountRoles": account_roles, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + account_id = UUID(d.pop("accountId")) + + account_name = d.pop("accountName") + + account_email = d.pop("accountEmail") + + is_verified = d.pop("isVerified") + + profile_image = d.pop("profileImage") + + account_roles = [] + _account_roles = d.pop("accountRoles") + for account_roles_item_data in _account_roles: + account_roles_item = RoleType(account_roles_item_data) + + account_roles.append(account_roles_item) + + login_v2_ok_response = cls( + account_id=account_id, + account_name=account_name, + account_email=account_email, + is_verified=is_verified, + profile_image=profile_image, + account_roles=account_roles, + ) + + login_v2_ok_response.additional_properties = d + return login_v2_ok_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/match_type_enum.py b/openshock/rest/models/match_type_enum.py new file mode 100644 index 0000000..f734f77 --- /dev/null +++ b/openshock/rest/models/match_type_enum.py @@ -0,0 +1,10 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class MatchTypeEnum(StrEnum): + CONTAINS = "Contains" + EXACT = "Exact" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/minimal_shocker.py b/openshock/rest/models/minimal_shocker.py new file mode 100644 index 0000000..21606b1 --- /dev/null +++ b/openshock/rest/models/minimal_shocker.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.shocker_model_type import ShockerModelType + +T = TypeVar("T", bound="MinimalShocker") + + +@_attrs_define +class MinimalShocker: + """ + Attributes: + id (UUID): + rf_id (int): + model (ShockerModelType): + """ + + id: UUID + rf_id: int + model: ShockerModelType + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + rf_id = self.rf_id + + model = self.model.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "rfId": rf_id, + "model": model, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + rf_id = d.pop("rfId") + + model = ShockerModelType(d.pop("model")) + + minimal_shocker = cls( + id=id, + rf_id=rf_id, + model=model, + ) + + minimal_shocker.additional_properties = d + return minimal_shocker + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/new_shocker.py b/openshock/rest/models/new_shocker.py new file mode 100644 index 0000000..0644ced --- /dev/null +++ b/openshock/rest/models/new_shocker.py @@ -0,0 +1,89 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.shocker_model_type import ShockerModelType + +T = TypeVar("T", bound="NewShocker") + + +@_attrs_define +class NewShocker: + """ + Attributes: + name (str): + rf_id (int): + device (UUID): + model (ShockerModelType): + """ + + name: str + rf_id: int + device: UUID + model: ShockerModelType + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + rf_id = self.rf_id + + device = str(self.device) + + model = self.model.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "rfId": rf_id, + "device": device, + "model": model, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + rf_id = d.pop("rfId") + + device = UUID(d.pop("device")) + + model = ShockerModelType(d.pop("model")) + + new_shocker = cls( + name=name, + rf_id=rf_id, + device=device, + model=model, + ) + + new_shocker.additional_properties = d + return new_shocker + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/o_auth_connection_response.py b/openshock/rest/models/o_auth_connection_response.py new file mode 100644 index 0000000..ce6a08a --- /dev/null +++ b/openshock/rest/models/o_auth_connection_response.py @@ -0,0 +1,93 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="OAuthConnectionResponse") + + +@_attrs_define +class OAuthConnectionResponse: + """ + Attributes: + provider_key (str): + external_id (str): + display_name (None | str): + linked_at (datetime.datetime): + """ + + provider_key: str + external_id: str + display_name: None | str + linked_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + provider_key = self.provider_key + + external_id = self.external_id + + display_name: None | str + display_name = self.display_name + + linked_at = self.linked_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "providerKey": provider_key, + "externalId": external_id, + "displayName": display_name, + "linkedAt": linked_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + provider_key = d.pop("providerKey") + + external_id = d.pop("externalId") + + def _parse_display_name(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + display_name = _parse_display_name(d.pop("displayName")) + + linked_at = datetime.datetime.fromisoformat(d.pop("linkedAt")) + + o_auth_connection_response = cls( + provider_key=provider_key, + external_id=external_id, + display_name=display_name, + linked_at=linked_at, + ) + + o_auth_connection_response.additional_properties = d + return o_auth_connection_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/open_shock_problem.py b/openshock/rest/models/open_shock_problem.py new file mode 100644 index 0000000..48329c6 --- /dev/null +++ b/openshock/rest/models/open_shock_problem.py @@ -0,0 +1,194 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="OpenShockProblem") + + +@_attrs_define +class OpenShockProblem: + """ + Attributes: + type_ (None | str): + title (None | str): + status (int | None | Unset): + detail (None | str | Unset): + instance (None | str | Unset): + message (str | Unset): + trace_id (None | str | Unset): + request_id (None | str | Unset): + """ + + type_: None | str + title: None | str + status: int | None | Unset = UNSET + detail: None | str | Unset = UNSET + instance: None | str | Unset = UNSET + message: str | Unset = UNSET + trace_id: None | str | Unset = UNSET + request_id: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + type_: None | str + type_ = self.type_ + + title: None | str + title = self.title + + status: int | None | Unset + if isinstance(self.status, Unset): + status = UNSET + else: + status = self.status + + detail: None | str | Unset + if isinstance(self.detail, Unset): + detail = UNSET + else: + detail = self.detail + + instance: None | str | Unset + if isinstance(self.instance, Unset): + instance = UNSET + else: + instance = self.instance + + message = self.message + + trace_id: None | str | Unset + if isinstance(self.trace_id, Unset): + trace_id = UNSET + else: + trace_id = self.trace_id + + request_id: None | str | Unset + if isinstance(self.request_id, Unset): + request_id = UNSET + else: + request_id = self.request_id + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "type": type_, + "title": title, + } + ) + if status is not UNSET: + field_dict["status"] = status + if detail is not UNSET: + field_dict["detail"] = detail + if instance is not UNSET: + field_dict["instance"] = instance + if message is not UNSET: + field_dict["message"] = message + if trace_id is not UNSET: + field_dict["traceId"] = trace_id + if request_id is not UNSET: + field_dict["requestId"] = request_id + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_type_(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + type_ = _parse_type_(d.pop("type")) + + def _parse_title(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + title = _parse_title(d.pop("title")) + + def _parse_status(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + status = _parse_status(d.pop("status", UNSET)) + + def _parse_detail(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + detail = _parse_detail(d.pop("detail", UNSET)) + + def _parse_instance(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + instance = _parse_instance(d.pop("instance", UNSET)) + + message = d.pop("message", UNSET) + + def _parse_trace_id(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + trace_id = _parse_trace_id(d.pop("traceId", UNSET)) + + def _parse_request_id(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + request_id = _parse_request_id(d.pop("requestId", UNSET)) + + open_shock_problem = cls( + type_=type_, + title=title, + status=status, + detail=detail, + instance=instance, + message=message, + trace_id=trace_id, + request_id=request_id, + ) + + open_shock_problem.additional_properties = d + return open_shock_problem + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/ota_item.py b/openshock/rest/models/ota_item.py new file mode 100644 index 0000000..7c9e8fd --- /dev/null +++ b/openshock/rest/models/ota_item.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.ota_update_status import OtaUpdateStatus + +T = TypeVar("T", bound="OtaItem") + + +@_attrs_define +class OtaItem: + """ + Attributes: + id (int): + started_at (datetime.datetime): + status (OtaUpdateStatus): + version (str): + message (None | str): + """ + + id: int + started_at: datetime.datetime + status: OtaUpdateStatus + version: str + message: None | str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = self.id + + started_at = self.started_at.isoformat() + + status = self.status.value + + version = self.version + + message: None | str + message = self.message + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "startedAt": started_at, + "status": status, + "version": version, + "message": message, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = d.pop("id") + + started_at = datetime.datetime.fromisoformat(d.pop("startedAt")) + + status = OtaUpdateStatus(d.pop("status")) + + version = d.pop("version") + + def _parse_message(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + message = _parse_message(d.pop("message")) + + ota_item = cls( + id=id, + started_at=started_at, + status=status, + version=version, + message=message, + ) + + ota_item.additional_properties = d + return ota_item + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/ota_update_status.py b/openshock/rest/models/ota_update_status.py new file mode 100644 index 0000000..6f8243f --- /dev/null +++ b/openshock/rest/models/ota_update_status.py @@ -0,0 +1,13 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class OtaUpdateStatus(StrEnum): + ERROR = "Error" + FINISHED = "Finished" + RUNNING = "Running" + STARTED = "Started" + TIMEOUT = "Timeout" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/own_public_share_response.py b/openshock/rest/models/own_public_share_response.py new file mode 100644 index 0000000..204e679 --- /dev/null +++ b/openshock/rest/models/own_public_share_response.py @@ -0,0 +1,112 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="OwnPublicShareResponse") + + +@_attrs_define +class OwnPublicShareResponse: + """ + Attributes: + id (UUID): + name (str): + created_on (datetime.datetime): + expires_on (datetime.datetime | None | Unset): + """ + + id: UUID + name: str + created_on: datetime.datetime + expires_on: datetime.datetime | None | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_on = self.created_on.isoformat() + + expires_on: None | str | Unset + if isinstance(self.expires_on, Unset): + expires_on = UNSET + elif isinstance(self.expires_on, datetime.datetime): + expires_on = self.expires_on.isoformat() + else: + expires_on = self.expires_on + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdOn": created_on, + } + ) + if expires_on is not UNSET: + field_dict["expiresOn"] = expires_on + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + expires_on_type_1 = datetime.datetime.fromisoformat(data) + + return expires_on_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + expires_on = _parse_expires_on(d.pop("expiresOn", UNSET)) + + own_public_share_response = cls( + id=id, + name=name, + created_on=created_on, + expires_on=expires_on, + ) + + own_public_share_response.additional_properties = d + return own_public_share_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/owner_shocker_response.py b/openshock/rest/models/owner_shocker_response.py new file mode 100644 index 0000000..3432c69 --- /dev/null +++ b/openshock/rest/models/owner_shocker_response.py @@ -0,0 +1,101 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shared_device import SharedDevice + + +T = TypeVar("T", bound="OwnerShockerResponse") + + +@_attrs_define +class OwnerShockerResponse: + """ + Attributes: + id (UUID): + name (str): + image (str): + devices (list[SharedDevice]): + """ + + id: UUID + name: str + image: str + devices: list[SharedDevice] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + image = self.image + + devices = [] + for devices_item_data in self.devices: + devices_item = devices_item_data.to_dict() + devices.append(devices_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "image": image, + "devices": devices, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shared_device import SharedDevice # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + image = d.pop("image") + + devices = [] + _devices = d.pop("devices") + for devices_item_data in _devices: + devices_item = SharedDevice.from_dict(devices_item_data) + + devices.append(devices_item) + + owner_shocker_response = cls( + id=id, + name=name, + image=image, + devices=devices, + ) + + owner_shocker_response.additional_properties = d + return owner_shocker_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/paged_result_of_audit_log_entry_response.py b/openshock/rest/models/paged_result_of_audit_log_entry_response.py new file mode 100644 index 0000000..afb380c --- /dev/null +++ b/openshock/rest/models/paged_result_of_audit_log_entry_response.py @@ -0,0 +1,112 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.audit_log_entry_response import AuditLogEntryResponse + + +T = TypeVar("T", bound="PagedResultOfAuditLogEntryResponse") + + +@_attrs_define +class PagedResultOfAuditLogEntryResponse: + """Page of results for a paginated list endpoint. + + Attributes: + items (list[AuditLogEntryResponse]): Items on the current page. + page (int): 1-based current page index. + page_size (int): Page size used to produce this result. + total_count (int): Total number of items across all pages matching the query. + total_pages (int | Unset): Total number of pages. Always at least 1, even when `TotalCount` is zero. + """ + + items: list[AuditLogEntryResponse] + page: int + page_size: int + total_count: int + total_pages: int | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + items = [] + for items_item_data in self.items: + items_item = items_item_data.to_dict() + items.append(items_item) + + page = self.page + + page_size = self.page_size + + total_count = self.total_count + + total_pages = self.total_pages + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "items": items, + "page": page, + "pageSize": page_size, + "totalCount": total_count, + } + ) + if total_pages is not UNSET: + field_dict["totalPages"] = total_pages + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.audit_log_entry_response import AuditLogEntryResponse # noqa: PLC0415 + + d = dict(src_dict) + items = [] + _items = d.pop("items") + for items_item_data in _items: + items_item = AuditLogEntryResponse.from_dict(items_item_data) + + items.append(items_item) + + page = d.pop("page") + + page_size = d.pop("pageSize") + + total_count = d.pop("totalCount") + + total_pages = d.pop("totalPages", UNSET) + + paged_result_of_audit_log_entry_response = cls( + items=items, + page=page, + page_size=page_size, + total_count=total_count, + total_pages=total_pages, + ) + + paged_result_of_audit_log_entry_response.additional_properties = d + return paged_result_of_audit_log_entry_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/paged_result_of_log_entry_with_hub.py b/openshock/rest/models/paged_result_of_log_entry_with_hub.py new file mode 100644 index 0000000..acd22b9 --- /dev/null +++ b/openshock/rest/models/paged_result_of_log_entry_with_hub.py @@ -0,0 +1,112 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.log_entry_with_hub import LogEntryWithHub + + +T = TypeVar("T", bound="PagedResultOfLogEntryWithHub") + + +@_attrs_define +class PagedResultOfLogEntryWithHub: + """Page of results for a paginated list endpoint. + + Attributes: + items (list[LogEntryWithHub]): Items on the current page. + page (int): 1-based current page index. + page_size (int): Page size used to produce this result. + total_count (int): Total number of items across all pages matching the query. + total_pages (int | Unset): Total number of pages. Always at least 1, even when `TotalCount` is zero. + """ + + items: list[LogEntryWithHub] + page: int + page_size: int + total_count: int + total_pages: int | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + items = [] + for items_item_data in self.items: + items_item = items_item_data.to_dict() + items.append(items_item) + + page = self.page + + page_size = self.page_size + + total_count = self.total_count + + total_pages = self.total_pages + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "items": items, + "page": page, + "pageSize": page_size, + "totalCount": total_count, + } + ) + if total_pages is not UNSET: + field_dict["totalPages"] = total_pages + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.log_entry_with_hub import LogEntryWithHub # noqa: PLC0415 + + d = dict(src_dict) + items = [] + _items = d.pop("items") + for items_item_data in _items: + items_item = LogEntryWithHub.from_dict(items_item_data) + + items.append(items_item) + + page = d.pop("page") + + page_size = d.pop("pageSize") + + total_count = d.pop("totalCount") + + total_pages = d.pop("totalPages", UNSET) + + paged_result_of_log_entry_with_hub = cls( + items=items, + page=page, + page_size=page_size, + total_count=total_count, + total_pages=total_pages, + ) + + paged_result_of_log_entry_with_hub.additional_properties = d + return paged_result_of_log_entry_with_hub + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_admin_users_view.py b/openshock/rest/models/paginated_of_admin_users_view.py new file mode 100644 index 0000000..fa4499d --- /dev/null +++ b/openshock/rest/models/paginated_of_admin_users_view.py @@ -0,0 +1,100 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_users_view import AdminUsersView + + +T = TypeVar("T", bound="PaginatedOfAdminUsersView") + + +@_attrs_define +class PaginatedOfAdminUsersView: + """ + Attributes: + offset (int): + limit (int): + total (int): + data (list[AdminUsersView]): + """ + + offset: int + limit: int + total: int + data: list[AdminUsersView] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + offset = self.offset + + limit = self.limit + + total = self.total + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "offset": offset, + "limit": limit, + "total": total, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_users_view import AdminUsersView # noqa: PLC0415 + + d = dict(src_dict) + offset = d.pop("offset") + + limit = d.pop("limit") + + total = d.pop("total") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = AdminUsersView.from_dict(data_item_data) + + data.append(data_item) + + paginated_of_admin_users_view = cls( + offset=offset, + limit=limit, + total=total, + data=data, + ) + + paginated_of_admin_users_view.additional_properties = d + return paginated_of_admin_users_view + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_email_outbox_message_dto.py b/openshock/rest/models/paginated_of_email_outbox_message_dto.py new file mode 100644 index 0000000..dffe554 --- /dev/null +++ b/openshock/rest/models/paginated_of_email_outbox_message_dto.py @@ -0,0 +1,100 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.email_outbox_message_dto import EmailOutboxMessageDto + + +T = TypeVar("T", bound="PaginatedOfEmailOutboxMessageDto") + + +@_attrs_define +class PaginatedOfEmailOutboxMessageDto: + """ + Attributes: + offset (int): + limit (int): + total (int): + data (list[EmailOutboxMessageDto]): + """ + + offset: int + limit: int + total: int + data: list[EmailOutboxMessageDto] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + offset = self.offset + + limit = self.limit + + total = self.total + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "offset": offset, + "limit": limit, + "total": total, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.email_outbox_message_dto import EmailOutboxMessageDto # noqa: PLC0415 + + d = dict(src_dict) + offset = d.pop("offset") + + limit = d.pop("limit") + + total = d.pop("total") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = EmailOutboxMessageDto.from_dict(data_item_data) + + data.append(data_item) + + paginated_of_email_outbox_message_dto = cls( + offset=offset, + limit=limit, + total=total, + data=data, + ) + + paginated_of_email_outbox_message_dto.additional_properties = d + return paginated_of_email_outbox_message_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/password_hashing_algorithm.py b/openshock/rest/models/password_hashing_algorithm.py new file mode 100644 index 0000000..13a3409 --- /dev/null +++ b/openshock/rest/models/password_hashing_algorithm.py @@ -0,0 +1,11 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class PasswordHashingAlgorithm(StrEnum): + BCRYPT = "BCrypt" + PBKDF2 = "PBKDF2" + UNKNOWN = "Unknown" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/password_reset_process_data.py b/openshock/rest/models/password_reset_process_data.py new file mode 100644 index 0000000..4595ac2 --- /dev/null +++ b/openshock/rest/models/password_reset_process_data.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="PasswordResetProcessData") + + +@_attrs_define +class PasswordResetProcessData: + """ + Attributes: + password (str): + """ + + password: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + password = self.password + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "password": password, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + password = d.pop("password") + + password_reset_process_data = cls( + password=password, + ) + + password_reset_process_data.additional_properties = d + return password_reset_process_data + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/password_reset_request_v2.py b/openshock/rest/models/password_reset_request_v2.py new file mode 100644 index 0000000..b108dbe --- /dev/null +++ b/openshock/rest/models/password_reset_request_v2.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="PasswordResetRequestV2") + + +@_attrs_define +class PasswordResetRequestV2: + """ + Attributes: + email (str): + turnstile_response (str): + """ + + email: str + turnstile_response: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + email = self.email + + turnstile_response = self.turnstile_response + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "email": email, + "turnstileResponse": turnstile_response, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + email = d.pop("email") + + turnstile_response = d.pop("turnstileResponse") + + password_reset_request_v2 = cls( + email=email, + turnstile_response=turnstile_response, + ) + + password_reset_request_v2.additional_properties = d + return password_reset_request_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/patch_automation_token_dto.py b/openshock/rest/models/patch_automation_token_dto.py new file mode 100644 index 0000000..ac287bc --- /dev/null +++ b/openshock/rest/models/patch_automation_token_dto.py @@ -0,0 +1,154 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="PatchAutomationTokenDto") + + +@_attrs_define +class PatchAutomationTokenDto: + """ + Attributes: + name (None | str | Unset): + types (list[AutomationTokenType] | None | Unset): + auto_cleanup_users (bool | None | Unset): + auto_cleanup_after (None | str | Unset): + """ + + name: None | str | Unset = UNSET + types: list[AutomationTokenType] | None | Unset = UNSET + auto_cleanup_users: bool | None | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name: None | str | Unset + if isinstance(self.name, Unset): + name = UNSET + else: + name = self.name + + types: list[str] | None | Unset + if isinstance(self.types, Unset): + types = UNSET + elif isinstance(self.types, list): + types = [] + for types_type_1_item_data in self.types: + types_type_1_item = types_type_1_item_data.value + types.append(types_type_1_item) + + else: + types = self.types + + auto_cleanup_users: bool | None | Unset + if isinstance(self.auto_cleanup_users, Unset): + auto_cleanup_users = UNSET + else: + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if name is not UNSET: + field_dict["name"] = name + if types is not UNSET: + field_dict["types"] = types + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_name(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + name = _parse_name(d.pop("name", UNSET)) + + def _parse_types(data: object) -> list[AutomationTokenType] | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, list): + raise TypeError() + types_type_1 = [] + _types_type_1 = data + for types_type_1_item_data in _types_type_1: + types_type_1_item = AutomationTokenType(types_type_1_item_data) + + types_type_1.append(types_type_1_item) + + return types_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(list[AutomationTokenType] | None | Unset, data) + + types = _parse_types(d.pop("types", UNSET)) + + def _parse_auto_cleanup_users(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + auto_cleanup_users = _parse_auto_cleanup_users(d.pop("autoCleanupUsers", UNSET)) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + patch_automation_token_dto = cls( + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + patch_automation_token_dto.additional_properties = d + return patch_automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/pause_request.py b/openshock/rest/models/pause_request.py new file mode 100644 index 0000000..37d3847 --- /dev/null +++ b/openshock/rest/models/pause_request.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="PauseRequest") + + +@_attrs_define +class PauseRequest: + """ + Attributes: + pause (bool): + """ + + pause: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + pause = self.pause + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "pause": pause, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + pause = d.pop("pause") + + pause_request = cls( + pause=pause, + ) + + pause_request.additional_properties = d + return pause_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/pause_user_share_shockers_request.py b/openshock/rest/models/pause_user_share_shockers_request.py new file mode 100644 index 0000000..f0f08dd --- /dev/null +++ b/openshock/rest/models/pause_user_share_shockers_request.py @@ -0,0 +1,79 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="PauseUserShareShockersRequest") + + +@_attrs_define +class PauseUserShareShockersRequest: + """ + Attributes: + shockers (list[UUID]): + pause (bool): + """ + + shockers: list[UUID] + pause: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = str(shockers_item_data) + shockers.append(shockers_item) + + pause = self.pause + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "shockers": shockers, + "pause": pause, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = UUID(shockers_item_data) + + shockers.append(shockers_item) + + pause = d.pop("pause") + + pause_user_share_shockers_request = cls( + shockers=shockers, + pause=pause, + ) + + pause_user_share_shockers_request.additional_properties = d + return pause_user_share_shockers_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/pause_user_share_shockers_response.py b/openshock/rest/models/pause_user_share_shockers_response.py new file mode 100644 index 0000000..51ea06c --- /dev/null +++ b/openshock/rest/models/pause_user_share_shockers_response.py @@ -0,0 +1,76 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.pause_user_share_shockers_response_pause_states import PauseUserShareShockersResponsePauseStates + + +T = TypeVar("T", bound="PauseUserShareShockersResponse") + + +@_attrs_define +class PauseUserShareShockersResponse: + """ + Attributes: + affected_records (int): + pause_states (PauseUserShareShockersResponsePauseStates): + """ + + affected_records: int + pause_states: PauseUserShareShockersResponsePauseStates + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + affected_records = self.affected_records + + pause_states = self.pause_states.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "affectedRecords": affected_records, + "pauseStates": pause_states, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.pause_user_share_shockers_response_pause_states import PauseUserShareShockersResponsePauseStates # noqa: PLC0415 + + d = dict(src_dict) + affected_records = d.pop("affectedRecords") + + pause_states = PauseUserShareShockersResponsePauseStates.from_dict(d.pop("pauseStates")) + + pause_user_share_shockers_response = cls( + affected_records=affected_records, + pause_states=pause_states, + ) + + pause_user_share_shockers_response.additional_properties = d + return pause_user_share_shockers_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/pause_user_share_shockers_response_pause_states.py b/openshock/rest/models/pause_user_share_shockers_response_pause_states.py new file mode 100644 index 0000000..f99f360 --- /dev/null +++ b/openshock/rest/models/pause_user_share_shockers_response_pause_states.py @@ -0,0 +1,46 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="PauseUserShareShockersResponsePauseStates") + + +@_attrs_define +class PauseUserShareShockersResponsePauseStates: + additional_properties: dict[str, int] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + pause_user_share_shockers_response_pause_states = cls() + + pause_user_share_shockers_response_pause_states.additional_properties = d + return pause_user_share_shockers_response_pause_states + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> int: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: int) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/permission_type.py b/openshock/rest/models/permission_type.py new file mode 100644 index 0000000..fe652be --- /dev/null +++ b/openshock/rest/models/permission_type.py @@ -0,0 +1,17 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class PermissionType(StrEnum): + DEVICES_AUTH = "devices.auth" + DEVICES_EDIT = "devices.edit" + PUBLICSHARES_EDIT = "publicshares.edit" + PUBLICSHARES_PAUSE = "publicshares.pause" + SHOCKERS_EDIT = "shockers.edit" + SHOCKERS_PAUSE = "shockers.pause" + SHOCKERS_USE = "shockers.use" + USERSHARES_EDIT = "usershares.edit" + USERSHARES_PAUSE = "usershares.pause" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/problem_details.py b/openshock/rest/models/problem_details.py new file mode 100644 index 0000000..2a84689 --- /dev/null +++ b/openshock/rest/models/problem_details.py @@ -0,0 +1,154 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="ProblemDetails") + + +@_attrs_define +class ProblemDetails: + """ + Attributes: + type_ (None | str | Unset): + title (None | str | Unset): + status (int | None | Unset): + detail (None | str | Unset): + instance (None | str | Unset): + """ + + type_: None | str | Unset = UNSET + title: None | str | Unset = UNSET + status: int | None | Unset = UNSET + detail: None | str | Unset = UNSET + instance: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + type_: None | str | Unset + if isinstance(self.type_, Unset): + type_ = UNSET + else: + type_ = self.type_ + + title: None | str | Unset + if isinstance(self.title, Unset): + title = UNSET + else: + title = self.title + + status: int | None | Unset + if isinstance(self.status, Unset): + status = UNSET + else: + status = self.status + + detail: None | str | Unset + if isinstance(self.detail, Unset): + detail = UNSET + else: + detail = self.detail + + instance: None | str | Unset + if isinstance(self.instance, Unset): + instance = UNSET + else: + instance = self.instance + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if type_ is not UNSET: + field_dict["type"] = type_ + if title is not UNSET: + field_dict["title"] = title + if status is not UNSET: + field_dict["status"] = status + if detail is not UNSET: + field_dict["detail"] = detail + if instance is not UNSET: + field_dict["instance"] = instance + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_type_(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + type_ = _parse_type_(d.pop("type", UNSET)) + + def _parse_title(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + title = _parse_title(d.pop("title", UNSET)) + + def _parse_status(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + status = _parse_status(d.pop("status", UNSET)) + + def _parse_detail(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + detail = _parse_detail(d.pop("detail", UNSET)) + + def _parse_instance(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + instance = _parse_instance(d.pop("instance", UNSET)) + + problem_details = cls( + type_=type_, + title=title, + status=status, + detail=detail, + instance=instance, + ) + + problem_details.additional_properties = d + return problem_details + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/public_share_create.py b/openshock/rest/models/public_share_create.py new file mode 100644 index 0000000..f8de2a1 --- /dev/null +++ b/openshock/rest/models/public_share_create.py @@ -0,0 +1,95 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="PublicShareCreate") + + +@_attrs_define +class PublicShareCreate: + """ + Attributes: + name (str): + expires_on (datetime.datetime | None | Unset): + """ + + name: str + expires_on: datetime.datetime | None | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + expires_on: None | str | Unset + if isinstance(self.expires_on, Unset): + expires_on = UNSET + elif isinstance(self.expires_on, datetime.datetime): + expires_on = self.expires_on.isoformat() + else: + expires_on = self.expires_on + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + } + ) + if expires_on is not UNSET: + field_dict["expiresOn"] = expires_on + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + expires_on_type_1 = datetime.datetime.fromisoformat(data) + + return expires_on_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + expires_on = _parse_expires_on(d.pop("expiresOn", UNSET)) + + public_share_create = cls( + name=name, + expires_on=expires_on, + ) + + public_share_create.additional_properties = d + return public_share_create + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/public_share_device.py b/openshock/rest/models/public_share_device.py new file mode 100644 index 0000000..0b5625d --- /dev/null +++ b/openshock/rest/models/public_share_device.py @@ -0,0 +1,93 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.public_share_shocker import PublicShareShocker + + +T = TypeVar("T", bound="PublicShareDevice") + + +@_attrs_define +class PublicShareDevice: + """ + Attributes: + id (UUID): + name (str): + shockers (list[PublicShareShocker]): + """ + + id: UUID + name: str + shockers: list[PublicShareShocker] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "shockers": shockers, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.public_share_shocker import PublicShareShocker # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = PublicShareShocker.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + public_share_device = cls( + id=id, + name=name, + shockers=shockers, + ) + + public_share_device.additional_properties = d + return public_share_device + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/public_share_edit_shocker.py b/openshock/rest/models/public_share_edit_shocker.py new file mode 100644 index 0000000..0f80556 --- /dev/null +++ b/openshock/rest/models/public_share_edit_shocker.py @@ -0,0 +1,100 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="PublicShareEditShocker") + + +@_attrs_define +class PublicShareEditShocker: + """ + Attributes: + permissions (ShockerPermissions): + limits (ShockerLimits): + cooldown (int | None | Unset): + """ + + permissions: ShockerPermissions + limits: ShockerLimits + cooldown: int | None | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + cooldown: int | None | Unset + if isinstance(self.cooldown, Unset): + cooldown = UNSET + else: + cooldown = self.cooldown + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "permissions": permissions, + "limits": limits, + } + ) + if cooldown is not UNSET: + field_dict["cooldown"] = cooldown + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + def _parse_cooldown(data: object) -> int | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(int | None | Unset, data) + + cooldown = _parse_cooldown(d.pop("cooldown", UNSET)) + + public_share_edit_shocker = cls( + permissions=permissions, + limits=limits, + cooldown=cooldown, + ) + + public_share_edit_shocker.additional_properties = d + return public_share_edit_shocker + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/public_share_response.py b/openshock/rest/models/public_share_response.py new file mode 100644 index 0000000..5b121db --- /dev/null +++ b/openshock/rest/models/public_share_response.py @@ -0,0 +1,149 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.basic_user_info import BasicUserInfo + from ..models.public_share_device import PublicShareDevice + + +T = TypeVar("T", bound="PublicShareResponse") + + +@_attrs_define +class PublicShareResponse: + """ + Attributes: + id (UUID): + name (str): + created_on (datetime.datetime): + author (BasicUserInfo): + expires_on (datetime.datetime | None | Unset): + devices (list[PublicShareDevice] | Unset): + """ + + id: UUID + name: str + created_on: datetime.datetime + author: BasicUserInfo + expires_on: datetime.datetime | None | Unset = UNSET + devices: list[PublicShareDevice] | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_on = self.created_on.isoformat() + + author = self.author.to_dict() + + expires_on: None | str | Unset + if isinstance(self.expires_on, Unset): + expires_on = UNSET + elif isinstance(self.expires_on, datetime.datetime): + expires_on = self.expires_on.isoformat() + else: + expires_on = self.expires_on + + devices: list[dict[str, Any]] | Unset = UNSET + if not isinstance(self.devices, Unset): + devices = [] + for devices_item_data in self.devices: + devices_item = devices_item_data.to_dict() + devices.append(devices_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdOn": created_on, + "author": author, + } + ) + if expires_on is not UNSET: + field_dict["expiresOn"] = expires_on + if devices is not UNSET: + field_dict["devices"] = devices + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + from ..models.public_share_device import PublicShareDevice # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + author = BasicUserInfo.from_dict(d.pop("author")) + + def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + expires_on_type_1 = datetime.datetime.fromisoformat(data) + + return expires_on_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + expires_on = _parse_expires_on(d.pop("expiresOn", UNSET)) + + _devices = d.pop("devices", UNSET) + devices: list[PublicShareDevice] | Unset = UNSET + if _devices is not UNSET: + devices = [] + for devices_item_data in _devices: + devices_item = PublicShareDevice.from_dict(devices_item_data) + + devices.append(devices_item) + + public_share_response = cls( + id=id, + name=name, + created_on=created_on, + author=author, + expires_on=expires_on, + devices=devices, + ) + + public_share_response.additional_properties = d + return public_share_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/public_share_shocker.py b/openshock/rest/models/public_share_shocker.py new file mode 100644 index 0000000..a0dd402 --- /dev/null +++ b/openshock/rest/models/public_share_shocker.py @@ -0,0 +1,111 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="PublicShareShocker") + + +@_attrs_define +class PublicShareShocker: + """ + Attributes: + id (UUID): + name (str): + permissions (ShockerPermissions): + limits (ShockerLimits): + paused (int): An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where + reasons are OR'd together. + + Each bit corresponds to: + - 1: Shocker + - 2: UserShare + - 4: PublicShare + + For example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons. + """ + + id: UUID + name: str + permissions: ShockerPermissions + limits: ShockerLimits + paused: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + paused = self.paused + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "permissions": permissions, + "limits": limits, + "paused": paused, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + paused = d.pop("paused") + + public_share_shocker = cls( + id=id, + name=name, + permissions=permissions, + limits=limits, + paused=paused, + ) + + public_share_shocker.additional_properties = d + return public_share_shocker + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/received_control_stats.py b/openshock/rest/models/received_control_stats.py new file mode 100644 index 0000000..8f6ceb1 --- /dev/null +++ b/openshock/rest/models/received_control_stats.py @@ -0,0 +1,130 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.control_stat_totals import ControlStatTotals + from ..models.daily_control_stats import DailyControlStats + from ..models.shocker_control_stats import ShockerControlStats + from ..models.user_control_stats import UserControlStats + + +T = TypeVar("T", bound="ReceivedControlStats") + + +@_attrs_define +class ReceivedControlStats: + """ + Attributes: + totals (list[ControlStatTotals]): + shockers (list[ShockerControlStats]): + controllers (list[UserControlStats]): + days (list[DailyControlStats]): + """ + + totals: list[ControlStatTotals] + shockers: list[ShockerControlStats] + controllers: list[UserControlStats] + days: list[DailyControlStats] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + totals = [] + for totals_item_data in self.totals: + totals_item = totals_item_data.to_dict() + totals.append(totals_item) + + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + controllers = [] + for controllers_item_data in self.controllers: + controllers_item = controllers_item_data.to_dict() + controllers.append(controllers_item) + + days = [] + for days_item_data in self.days: + days_item = days_item_data.to_dict() + days.append(days_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "totals": totals, + "shockers": shockers, + "controllers": controllers, + "days": days, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control_stat_totals import ControlStatTotals # noqa: PLC0415 + from ..models.daily_control_stats import DailyControlStats # noqa: PLC0415 + from ..models.shocker_control_stats import ShockerControlStats # noqa: PLC0415 + from ..models.user_control_stats import UserControlStats # noqa: PLC0415 + + d = dict(src_dict) + totals = [] + _totals = d.pop("totals") + for totals_item_data in _totals: + totals_item = ControlStatTotals.from_dict(totals_item_data) + + totals.append(totals_item) + + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = ShockerControlStats.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + controllers = [] + _controllers = d.pop("controllers") + for controllers_item_data in _controllers: + controllers_item = UserControlStats.from_dict(controllers_item_data) + + controllers.append(controllers_item) + + days = [] + _days = d.pop("days") + for days_item_data in _days: + days_item = DailyControlStats.from_dict(days_item_data) + + days.append(days_item) + + received_control_stats = cls( + totals=totals, + shockers=shockers, + controllers=controllers, + days=days, + ) + + received_control_stats.additional_properties = d + return received_control_stats + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/remove_user_shares_response.py b/openshock/rest/models/remove_user_shares_response.py new file mode 100644 index 0000000..c36e607 --- /dev/null +++ b/openshock/rest/models/remove_user_shares_response.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="RemoveUserSharesResponse") + + +@_attrs_define +class RemoveUserSharesResponse: + """ + Attributes: + affected_records (int): + """ + + affected_records: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + affected_records = self.affected_records + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "affectedRecords": affected_records, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + affected_records = d.pop("affectedRecords") + + remove_user_shares_response = cls( + affected_records=affected_records, + ) + + remove_user_shares_response.additional_properties = d + return remove_user_shares_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/report_tokens_request.py b/openshock/rest/models/report_tokens_request.py new file mode 100644 index 0000000..8c6cafb --- /dev/null +++ b/openshock/rest/models/report_tokens_request.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ReportTokensRequest") + + +@_attrs_define +class ReportTokensRequest: + """ + Attributes: + turnstile_response (str): + secrets (list[str]): + """ + + turnstile_response: str + secrets: list[str] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + turnstile_response = self.turnstile_response + + secrets = self.secrets + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "turnstileResponse": turnstile_response, + "secrets": secrets, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + turnstile_response = d.pop("turnstileResponse") + + secrets = cast(list[str], d.pop("secrets")) + + report_tokens_request = cls( + turnstile_response=turnstile_response, + secrets=secrets, + ) + + report_tokens_request.additional_properties = d + return report_tokens_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/role_type.py b/openshock/rest/models/role_type.py new file mode 100644 index 0000000..b84fed3 --- /dev/null +++ b/openshock/rest/models/role_type.py @@ -0,0 +1,12 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class RoleType(StrEnum): + ADMIN = "Admin" + STAFF = "Staff" + SUPPORT = "Support" + SYSTEM = "System" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/send_test_email_dto.py b/openshock/rest/models/send_test_email_dto.py new file mode 100644 index 0000000..e3fd2d6 --- /dev/null +++ b/openshock/rest/models/send_test_email_dto.py @@ -0,0 +1,98 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.email_type import EmailType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="SendTestEmailDto") + + +@_attrs_define +class SendTestEmailDto: + """Request to enqueue a preview/test email of a chosen type to a chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no request row). + + Attributes: + type_ (EmailType): The kind of email an outbox message represents. The outbox stores + only the intent to send one of these, never a rendered body or a usable secret, the + consumer maps the type to the matching template and (for token-bearing types) mints a fresh + secret at send time. + recipient (str): Destination address for the test email. + recipient_name (None | str | Unset): Optional display name for the recipient. + """ + + type_: EmailType + recipient: str + recipient_name: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + type_ = self.type_.value + + recipient = self.recipient + + recipient_name: None | str | Unset + if isinstance(self.recipient_name, Unset): + recipient_name = UNSET + else: + recipient_name = self.recipient_name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "type": type_, + "recipient": recipient, + } + ) + if recipient_name is not UNSET: + field_dict["recipientName"] = recipient_name + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + type_ = EmailType(d.pop("type")) + + recipient = d.pop("recipient") + + def _parse_recipient_name(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + recipient_name = _parse_recipient_name(d.pop("recipientName", UNSET)) + + send_test_email_dto = cls( + type_=type_, + recipient=recipient, + recipient_name=recipient_name, + ) + + send_test_email_dto.additional_properties = d + return send_test_email_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_token_paused_request.py b/openshock/rest/models/set_token_paused_request.py new file mode 100644 index 0000000..4a6507c --- /dev/null +++ b/openshock/rest/models/set_token_paused_request.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetTokenPausedRequest") + + +@_attrs_define +class SetTokenPausedRequest: + """ + Attributes: + paused (bool): When true, the token is paused and may not send shocker control messages. + """ + + paused: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + paused = self.paused + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "paused": paused, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + paused = d.pop("paused") + + set_token_paused_request = cls( + paused=paused, + ) + + set_token_paused_request.additional_properties = d + return set_token_paused_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_user_email_request_body.py b/openshock/rest/models/set_user_email_request_body.py new file mode 100644 index 0000000..6d555e5 --- /dev/null +++ b/openshock/rest/models/set_user_email_request_body.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetUserEmailRequestBody") + + +@_attrs_define +class SetUserEmailRequestBody: + """ + Attributes: + email (str): + """ + + email: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + email = self.email + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "email": email, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + email = d.pop("email") + + set_user_email_request_body = cls( + email=email, + ) + + set_user_email_request_body.additional_properties = d + return set_user_email_request_body + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_user_name_request_body.py b/openshock/rest/models/set_user_name_request_body.py new file mode 100644 index 0000000..178e806 --- /dev/null +++ b/openshock/rest/models/set_user_name_request_body.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetUserNameRequestBody") + + +@_attrs_define +class SetUserNameRequestBody: + """ + Attributes: + name (str): + """ + + name: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + set_user_name_request_body = cls( + name=name, + ) + + set_user_name_request_body.additional_properties = d + return set_user_name_request_body + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_user_password_request_body.py b/openshock/rest/models/set_user_password_request_body.py new file mode 100644 index 0000000..2eba296 --- /dev/null +++ b/openshock/rest/models/set_user_password_request_body.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetUserPasswordRequestBody") + + +@_attrs_define +class SetUserPasswordRequestBody: + """ + Attributes: + password (str): + """ + + password: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + password = self.password + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "password": password, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + password = d.pop("password") + + set_user_password_request_body = cls( + password=password, + ) + + set_user_password_request_body.additional_properties = d + return set_user_password_request_body + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/share_code_info.py b/openshock/rest/models/share_code_info.py new file mode 100644 index 0000000..387ba77 --- /dev/null +++ b/openshock/rest/models/share_code_info.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ShareCodeInfo") + + +@_attrs_define +class ShareCodeInfo: + """ + Attributes: + id (UUID): + created_on (datetime.datetime): + """ + + id: UUID + created_on: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + created_on = self.created_on.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "createdOn": created_on, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + share_code_info = cls( + id=id, + created_on=created_on, + ) + + share_code_info.additional_properties = d + return share_code_info + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/share_info.py b/openshock/rest/models/share_info.py new file mode 100644 index 0000000..1bc4943 --- /dev/null +++ b/openshock/rest/models/share_info.py @@ -0,0 +1,105 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.basic_user_info import BasicUserInfo + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="ShareInfo") + + +@_attrs_define +class ShareInfo: + """ + Attributes: + shared_with (BasicUserInfo): + created_on (datetime.datetime): + permissions (ShockerPermissions): + limits (ShockerLimits): + paused (bool): + """ + + shared_with: BasicUserInfo + created_on: datetime.datetime + permissions: ShockerPermissions + limits: ShockerLimits + paused: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + shared_with = self.shared_with.to_dict() + + created_on = self.created_on.isoformat() + + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + paused = self.paused + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "sharedWith": shared_with, + "createdOn": created_on, + "permissions": permissions, + "limits": limits, + "paused": paused, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + shared_with = BasicUserInfo.from_dict(d.pop("sharedWith")) + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + paused = d.pop("paused") + + share_info = cls( + shared_with=shared_with, + created_on=created_on, + permissions=permissions, + limits=limits, + paused=paused, + ) + + share_info.additional_properties = d + return share_info + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/share_invite_base_details.py b/openshock/rest/models/share_invite_base_details.py new file mode 100644 index 0000000..602d7bd --- /dev/null +++ b/openshock/rest/models/share_invite_base_details.py @@ -0,0 +1,131 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.basic_user_info import BasicUserInfo + from ..models.shocker_perm_limit_pair_with_id_and_name import ShockerPermLimitPairWithIdAndName + + +T = TypeVar("T", bound="ShareInviteBaseDetails") + + +@_attrs_define +class ShareInviteBaseDetails: + """ + Attributes: + shockers (list[ShockerPermLimitPairWithIdAndName]): + id (UUID): + created_at (datetime.datetime): + owner (BasicUserInfo): + shared_with (BasicUserInfo | None): + """ + + shockers: list[ShockerPermLimitPairWithIdAndName] + id: UUID + created_at: datetime.datetime + owner: BasicUserInfo + shared_with: BasicUserInfo | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + id = str(self.id) + + created_at = self.created_at.isoformat() + + owner = self.owner.to_dict() + + shared_with: dict[str, Any] | None + if isinstance(self.shared_with, BasicUserInfo): + shared_with = self.shared_with.to_dict() + else: + shared_with = self.shared_with + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "shockers": shockers, + "id": id, + "createdAt": created_at, + "owner": owner, + "sharedWith": shared_with, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + from ..models.shocker_perm_limit_pair_with_id_and_name import ShockerPermLimitPairWithIdAndName # noqa: PLC0415 + + d = dict(src_dict) + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = ShockerPermLimitPairWithIdAndName.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + id = UUID(d.pop("id")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + owner = BasicUserInfo.from_dict(d.pop("owner")) + + def _parse_shared_with(data: object) -> BasicUserInfo | None: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + shared_with_type_1 = BasicUserInfo.from_dict(data) + + return shared_with_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(BasicUserInfo | None, data) + + shared_with = _parse_shared_with(d.pop("sharedWith")) + + share_invite_base_details = cls( + shockers=shockers, + id=id, + created_at=created_at, + owner=owner, + shared_with=shared_with, + ) + + share_invite_base_details.additional_properties = d + return share_invite_base_details + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shared_device.py b/openshock/rest/models/shared_device.py new file mode 100644 index 0000000..909ed8d --- /dev/null +++ b/openshock/rest/models/shared_device.py @@ -0,0 +1,93 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shared_shocker import SharedShocker + + +T = TypeVar("T", bound="SharedDevice") + + +@_attrs_define +class SharedDevice: + """ + Attributes: + id (UUID): + name (str): + shockers (list[SharedShocker]): + """ + + id: UUID + name: str + shockers: list[SharedShocker] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "shockers": shockers, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shared_shocker import SharedShocker # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = SharedShocker.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + shared_device = cls( + id=id, + name=name, + shockers=shockers, + ) + + shared_device.additional_properties = d + return shared_device + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shared_shocker.py b/openshock/rest/models/shared_shocker.py new file mode 100644 index 0000000..5cb6ba4 --- /dev/null +++ b/openshock/rest/models/shared_shocker.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="SharedShocker") + + +@_attrs_define +class SharedShocker: + """ + Attributes: + id (UUID): + name (str): + is_paused (bool): + permissions (ShockerPermissions): + limits (ShockerLimits): + """ + + id: UUID + name: str + is_paused: bool + permissions: ShockerPermissions + limits: ShockerLimits + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + is_paused = self.is_paused + + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "isPaused": is_paused, + "permissions": permissions, + "limits": limits, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + is_paused = d.pop("isPaused") + + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + shared_shocker = cls( + id=id, + name=name, + is_paused=is_paused, + permissions=permissions, + limits=limits, + ) + + shared_shocker.additional_properties = d + return shared_shocker + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_control_settings.py b/openshock/rest/models/shocker_control_settings.py new file mode 100644 index 0000000..56f40d1 --- /dev/null +++ b/openshock/rest/models/shocker_control_settings.py @@ -0,0 +1,87 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.duration_limit_settings import DurationLimitSettings + from ..models.intensity_limit_settings import IntensityLimitSettings + + +T = TypeVar("T", bound="ShockerControlSettings") + + +@_attrs_define +class ShockerControlSettings: + """Per-token shocker control configuration: a toggle plus min/max limits for intensity and duration. + + Attributes: + paused (bool): When true, this token is paused and may not send shocker control messages. + intensity (IntensityLimitSettings): + duration (DurationLimitSettings): + """ + + paused: bool + intensity: IntensityLimitSettings + duration: DurationLimitSettings + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + paused = self.paused + + intensity = self.intensity.to_dict() + + duration = self.duration.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "paused": paused, + "intensity": intensity, + "duration": duration, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.duration_limit_settings import DurationLimitSettings # noqa: PLC0415 + from ..models.intensity_limit_settings import IntensityLimitSettings # noqa: PLC0415 + + d = dict(src_dict) + paused = d.pop("paused") + + intensity = IntensityLimitSettings.from_dict(d.pop("intensity")) + + duration = DurationLimitSettings.from_dict(d.pop("duration")) + + shocker_control_settings = cls( + paused=paused, + intensity=intensity, + duration=duration, + ) + + shocker_control_settings.additional_properties = d + return shocker_control_settings + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_control_stats.py b/openshock/rest/models/shocker_control_stats.py new file mode 100644 index 0000000..f42169e --- /dev/null +++ b/openshock/rest/models/shocker_control_stats.py @@ -0,0 +1,117 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.control_stat_totals import ControlStatTotals + + +T = TypeVar("T", bound="ShockerControlStats") + + +@_attrs_define +class ShockerControlStats: + """ + Attributes: + shocker_id (None | UUID): Null for shockers that have since been deleted, these are combined into one entry. + shocker_name (None | str): + stats (list[ControlStatTotals]): + """ + + shocker_id: None | UUID + shocker_name: None | str + stats: list[ControlStatTotals] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + shocker_id: None | str + if isinstance(self.shocker_id, UUID): + shocker_id = str(self.shocker_id) + else: + shocker_id = self.shocker_id + + shocker_name: None | str + shocker_name = self.shocker_name + + stats = [] + for stats_item_data in self.stats: + stats_item = stats_item_data.to_dict() + stats.append(stats_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "shockerId": shocker_id, + "shockerName": shocker_name, + "stats": stats, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control_stat_totals import ControlStatTotals # noqa: PLC0415 + + d = dict(src_dict) + + def _parse_shocker_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + shocker_id_type_1 = UUID(data) + + return shocker_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + shocker_id = _parse_shocker_id(d.pop("shockerId")) + + def _parse_shocker_name(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + shocker_name = _parse_shocker_name(d.pop("shockerName")) + + stats = [] + _stats = d.pop("stats") + for stats_item_data in _stats: + stats_item = ControlStatTotals.from_dict(stats_item_data) + + stats.append(stats_item) + + shocker_control_stats = cls( + shocker_id=shocker_id, + shocker_name=shocker_name, + stats=stats, + ) + + shocker_control_stats.additional_properties = d + return shocker_control_stats + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_limits.py b/openshock/rest/models/shocker_limits.py new file mode 100644 index 0000000..0429085 --- /dev/null +++ b/openshock/rest/models/shocker_limits.py @@ -0,0 +1,83 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ShockerLimits") + + +@_attrs_define +class ShockerLimits: + """ + Attributes: + intensity (int | None): + duration (int | None): + """ + + intensity: int | None + duration: int | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + intensity: int | None + intensity = self.intensity + + duration: int | None + duration = self.duration + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "intensity": intensity, + "duration": duration, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_intensity(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + intensity = _parse_intensity(d.pop("intensity")) + + def _parse_duration(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + duration = _parse_duration(d.pop("duration")) + + shocker_limits = cls( + intensity=intensity, + duration=duration, + ) + + shocker_limits.additional_properties = d + return shocker_limits + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_model_type.py b/openshock/rest/models/shocker_model_type.py new file mode 100644 index 0000000..cceb428 --- /dev/null +++ b/openshock/rest/models/shocker_model_type.py @@ -0,0 +1,12 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class ShockerModelType(StrEnum): + CAIXIANLIN = "CaiXianlin" + PETRAINER998DR = "Petrainer998DR" + PETTRAINER = "PetTrainer" + WELLTURNT330 = "WellturnT330" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/shocker_perm_limit_pair.py b/openshock/rest/models/shocker_perm_limit_pair.py new file mode 100644 index 0000000..7043703 --- /dev/null +++ b/openshock/rest/models/shocker_perm_limit_pair.py @@ -0,0 +1,78 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="ShockerPermLimitPair") + + +@_attrs_define +class ShockerPermLimitPair: + """ + Attributes: + permissions (ShockerPermissions): + limits (ShockerLimits): + """ + + permissions: ShockerPermissions + limits: ShockerLimits + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "permissions": permissions, + "limits": limits, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + shocker_perm_limit_pair = cls( + permissions=permissions, + limits=limits, + ) + + shocker_perm_limit_pair.additional_properties = d + return shocker_perm_limit_pair + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_perm_limit_pair_with_id.py b/openshock/rest/models/shocker_perm_limit_pair_with_id.py new file mode 100644 index 0000000..b0ed6f0 --- /dev/null +++ b/openshock/rest/models/shocker_perm_limit_pair_with_id.py @@ -0,0 +1,97 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="ShockerPermLimitPairWithId") + + +@_attrs_define +class ShockerPermLimitPairWithId: + """ + Attributes: + permissions (ShockerPermissions): + limits (ShockerLimits): + id (UUID | Unset): + """ + + permissions: ShockerPermissions + limits: ShockerLimits + id: UUID | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + id: str | Unset = UNSET + if not isinstance(self.id, Unset): + id = str(self.id) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "permissions": permissions, + "limits": limits, + } + ) + if id is not UNSET: + field_dict["id"] = id + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + _id = d.pop("id", UNSET) + id: UUID | Unset + if isinstance(_id, Unset): + id = UNSET + else: + id = UUID(_id) + + shocker_perm_limit_pair_with_id = cls( + permissions=permissions, + limits=limits, + id=id, + ) + + shocker_perm_limit_pair_with_id.additional_properties = d + return shocker_perm_limit_pair_with_id + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_perm_limit_pair_with_id_and_name.py b/openshock/rest/models/shocker_perm_limit_pair_with_id_and_name.py new file mode 100644 index 0000000..bafeff6 --- /dev/null +++ b/openshock/rest/models/shocker_perm_limit_pair_with_id_and_name.py @@ -0,0 +1,105 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="ShockerPermLimitPairWithIdAndName") + + +@_attrs_define +class ShockerPermLimitPairWithIdAndName: + """ + Attributes: + name (str): + permissions (ShockerPermissions): + limits (ShockerLimits): + id (UUID | Unset): + """ + + name: str + permissions: ShockerPermissions + limits: ShockerLimits + id: UUID | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + id: str | Unset = UNSET + if not isinstance(self.id, Unset): + id = str(self.id) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "permissions": permissions, + "limits": limits, + } + ) + if id is not UNSET: + field_dict["id"] = id + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + name = d.pop("name") + + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + _id = d.pop("id", UNSET) + id: UUID | Unset + if isinstance(_id, Unset): + id = UNSET + else: + id = UUID(_id) + + shocker_perm_limit_pair_with_id_and_name = cls( + name=name, + permissions=permissions, + limits=limits, + id=id, + ) + + shocker_perm_limit_pair_with_id_and_name.additional_properties = d + return shocker_perm_limit_pair_with_id_and_name + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_permissions.py b/openshock/rest/models/shocker_permissions.py new file mode 100644 index 0000000..eab7bd2 --- /dev/null +++ b/openshock/rest/models/shocker_permissions.py @@ -0,0 +1,89 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="ShockerPermissions") + + +@_attrs_define +class ShockerPermissions: + """ + Attributes: + vibrate (bool): + sound (bool): + shock (bool): + live (bool | Unset): + """ + + vibrate: bool + sound: bool + shock: bool + live: bool | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + vibrate = self.vibrate + + sound = self.sound + + shock = self.shock + + live = self.live + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "vibrate": vibrate, + "sound": sound, + "shock": shock, + } + ) + if live is not UNSET: + field_dict["live"] = live + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + vibrate = d.pop("vibrate") + + sound = d.pop("sound") + + shock = d.pop("shock") + + live = d.pop("live", UNSET) + + shocker_permissions = cls( + vibrate=vibrate, + sound=sound, + shock=shock, + live=live, + ) + + shocker_permissions.additional_properties = d + return shocker_permissions + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_response.py b/openshock/rest/models/shocker_response.py new file mode 100644 index 0000000..67b4bc9 --- /dev/null +++ b/openshock/rest/models/shocker_response.py @@ -0,0 +1,106 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.shocker_model_type import ShockerModelType + +T = TypeVar("T", bound="ShockerResponse") + + +@_attrs_define +class ShockerResponse: + """ + Attributes: + name (str): + is_paused (bool): + created_on (datetime.datetime): + id (UUID): + rf_id (int): + model (ShockerModelType): + """ + + name: str + is_paused: bool + created_on: datetime.datetime + id: UUID + rf_id: int + model: ShockerModelType + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + is_paused = self.is_paused + + created_on = self.created_on.isoformat() + + id = str(self.id) + + rf_id = self.rf_id + + model = self.model.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "isPaused": is_paused, + "createdOn": created_on, + "id": id, + "rfId": rf_id, + "model": model, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + is_paused = d.pop("isPaused") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + id = UUID(d.pop("id")) + + rf_id = d.pop("rfId") + + model = ShockerModelType(d.pop("model")) + + shocker_response = cls( + name=name, + is_paused=is_paused, + created_on=created_on, + id=id, + rf_id=rf_id, + model=model, + ) + + shocker_response.additional_properties = d + return shocker_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/shocker_with_device.py b/openshock/rest/models/shocker_with_device.py new file mode 100644 index 0000000..27b6f85 --- /dev/null +++ b/openshock/rest/models/shocker_with_device.py @@ -0,0 +1,114 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.shocker_model_type import ShockerModelType + +T = TypeVar("T", bound="ShockerWithDevice") + + +@_attrs_define +class ShockerWithDevice: + """ + Attributes: + device (UUID): + name (str): + is_paused (bool): + created_on (datetime.datetime): + id (UUID): + rf_id (int): + model (ShockerModelType): + """ + + device: UUID + name: str + is_paused: bool + created_on: datetime.datetime + id: UUID + rf_id: int + model: ShockerModelType + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + device = str(self.device) + + name = self.name + + is_paused = self.is_paused + + created_on = self.created_on.isoformat() + + id = str(self.id) + + rf_id = self.rf_id + + model = self.model.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "device": device, + "name": name, + "isPaused": is_paused, + "createdOn": created_on, + "id": id, + "rfId": rf_id, + "model": model, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + device = UUID(d.pop("device")) + + name = d.pop("name") + + is_paused = d.pop("isPaused") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + id = UUID(d.pop("id")) + + rf_id = d.pop("rfId") + + model = ShockerModelType(d.pop("model")) + + shocker_with_device = cls( + device=device, + name=name, + is_paused=is_paused, + created_on=created_on, + id=id, + rf_id=rf_id, + model=model, + ) + + shocker_with_device.additional_properties = d + return shocker_with_device + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/sign_up_v2.py b/openshock/rest/models/sign_up_v2.py new file mode 100644 index 0000000..07329a8 --- /dev/null +++ b/openshock/rest/models/sign_up_v2.py @@ -0,0 +1,86 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SignUpV2") + + +@_attrs_define +class SignUpV2: + """ + Attributes: + username (str): + password (str): + email (str): + turnstile_response (str): + """ + + username: str + password: str + email: str + turnstile_response: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + username = self.username + + password = self.password + + email = self.email + + turnstile_response = self.turnstile_response + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "username": username, + "password": password, + "email": email, + "turnstileResponse": turnstile_response, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + username = d.pop("username") + + password = d.pop("password") + + email = d.pop("email") + + turnstile_response = d.pop("turnstileResponse") + + sign_up_v2 = cls( + username=username, + password=password, + email=email, + turnstile_response=turnstile_response, + ) + + sign_up_v2.additional_properties = d + return sign_up_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/sort_direction.py b/openshock/rest/models/sort_direction.py new file mode 100644 index 0000000..41805af --- /dev/null +++ b/openshock/rest/models/sort_direction.py @@ -0,0 +1,10 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class SortDirection(StrEnum): + ASC = "Asc" + DESC = "Desc" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/stats_response.py b/openshock/rest/models/stats_response.py new file mode 100644 index 0000000..e8576f4 --- /dev/null +++ b/openshock/rest/models/stats_response.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="StatsResponse") + + +@_attrs_define +class StatsResponse: + """ + Attributes: + devices_online (int): + """ + + devices_online: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + devices_online = self.devices_online + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "devicesOnline": devices_online, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + devices_online = d.pop("devicesOnline") + + stats_response = cls( + devices_online=devices_online, + ) + + stats_response.additional_properties = d + return stats_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/token_created_response_v2.py b/openshock/rest/models/token_created_response_v2.py new file mode 100644 index 0000000..0ff2f4b --- /dev/null +++ b/openshock/rest/models/token_created_response_v2.py @@ -0,0 +1,171 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType + +if TYPE_CHECKING: + from ..models.shocker_control_settings import ShockerControlSettings + + +T = TypeVar("T", bound="TokenCreatedResponseV2") + + +@_attrs_define +class TokenCreatedResponseV2: + """ + Attributes: + id (UUID): + name (str): + token (str): + created_at (datetime.datetime): + valid_until (datetime.datetime | None): + last_used (datetime.datetime | None): + permissions (list[PermissionType]): + shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits + for intensity and duration. + """ + + id: UUID + name: str + token: str + created_at: datetime.datetime + valid_until: datetime.datetime | None + last_used: datetime.datetime | None + permissions: list[PermissionType] + shocker_control: ShockerControlSettings + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + token = self.token + + created_at = self.created_at.isoformat() + + valid_until: None | str + if isinstance(self.valid_until, datetime.datetime): + valid_until = self.valid_until.isoformat() + else: + valid_until = self.valid_until + + last_used: None | str + if isinstance(self.last_used, datetime.datetime): + last_used = self.last_used.isoformat() + else: + last_used = self.last_used + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + shocker_control = self.shocker_control.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "token": token, + "createdAt": created_at, + "validUntil": valid_until, + "lastUsed": last_used, + "permissions": permissions, + "shockerControl": shocker_control, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + token = d.pop("token") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_valid_until(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + valid_until_type_1 = datetime.datetime.fromisoformat(data) + + return valid_until_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + valid_until = _parse_valid_until(d.pop("validUntil")) + + def _parse_last_used(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + last_used = _parse_last_used(d.pop("lastUsed")) + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) + + token_created_response_v2 = cls( + id=id, + name=name, + token=token, + created_at=created_at, + valid_until=valid_until, + last_used=last_used, + permissions=permissions, + shocker_control=shocker_control, + ) + + token_created_response_v2.additional_properties = d + return token_created_response_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/token_paused_response.py b/openshock/rest/models/token_paused_response.py new file mode 100644 index 0000000..dbce49a --- /dev/null +++ b/openshock/rest/models/token_paused_response.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="TokenPausedResponse") + + +@_attrs_define +class TokenPausedResponse: + """ + Attributes: + paused (bool): The now-set paused state of the token. + """ + + paused: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + paused = self.paused + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "paused": paused, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + paused = d.pop("paused") + + token_paused_response = cls( + paused=paused, + ) + + token_paused_response.additional_properties = d + return token_paused_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/token_response_v2.py b/openshock/rest/models/token_response_v2.py new file mode 100644 index 0000000..0873041 --- /dev/null +++ b/openshock/rest/models/token_response_v2.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType + +if TYPE_CHECKING: + from ..models.shocker_control_settings import ShockerControlSettings + + +T = TypeVar("T", bound="TokenResponseV2") + + +@_attrs_define +class TokenResponseV2: + """ + Attributes: + id (UUID): + name (str): + created_on (datetime.datetime): + valid_until (datetime.datetime | None): + last_used (datetime.datetime | None): + permissions (list[PermissionType]): + shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits + for intensity and duration. + """ + + id: UUID + name: str + created_on: datetime.datetime + valid_until: datetime.datetime | None + last_used: datetime.datetime | None + permissions: list[PermissionType] + shocker_control: ShockerControlSettings + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_on = self.created_on.isoformat() + + valid_until: None | str + if isinstance(self.valid_until, datetime.datetime): + valid_until = self.valid_until.isoformat() + else: + valid_until = self.valid_until + + last_used: None | str + if isinstance(self.last_used, datetime.datetime): + last_used = self.last_used.isoformat() + else: + last_used = self.last_used + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + shocker_control = self.shocker_control.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdOn": created_on, + "validUntil": valid_until, + "lastUsed": last_used, + "permissions": permissions, + "shockerControl": shocker_control, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + def _parse_valid_until(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + valid_until_type_1 = datetime.datetime.fromisoformat(data) + + return valid_until_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + valid_until = _parse_valid_until(d.pop("validUntil")) + + def _parse_last_used(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + last_used = _parse_last_used(d.pop("lastUsed")) + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) + + token_response_v2 = cls( + id=id, + name=name, + created_on=created_on, + valid_until=valid_until, + last_used=last_used, + permissions=permissions, + shocker_control=shocker_control, + ) + + token_response_v2.additional_properties = d + return token_response_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_control_stat_totals.py b/openshock/rest/models/user_control_stat_totals.py new file mode 100644 index 0000000..bfc345c --- /dev/null +++ b/openshock/rest/models/user_control_stat_totals.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.control_stat_totals import ControlStatTotals + + +T = TypeVar("T", bound="UserControlStatTotals") + + +@_attrs_define +class UserControlStatTotals: + """Lifetime totals of one user, the same views as ControlStatsResponse without breakdowns. + + Attributes: + user_id (UUID): + received (list[ControlStatTotals]): Activity on shockers the user owns. + given (list[ControlStatTotals]): Activity the user sent to shockers, their own included. + """ + + user_id: UUID + received: list[ControlStatTotals] + given: list[ControlStatTotals] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + user_id = str(self.user_id) + + received = [] + for received_item_data in self.received: + received_item = received_item_data.to_dict() + received.append(received_item) + + given = [] + for given_item_data in self.given: + given_item = given_item_data.to_dict() + given.append(given_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "userId": user_id, + "received": received, + "given": given, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.control_stat_totals import ControlStatTotals # noqa: PLC0415 + + d = dict(src_dict) + user_id = UUID(d.pop("userId")) + + received = [] + _received = d.pop("received") + for received_item_data in _received: + received_item = ControlStatTotals.from_dict(received_item_data) + + received.append(received_item) + + given = [] + _given = d.pop("given") + for given_item_data in _given: + given_item = ControlStatTotals.from_dict(given_item_data) + + given.append(given_item) + + user_control_stat_totals = cls( + user_id=user_id, + received=received, + given=given, + ) + + user_control_stat_totals.additional_properties = d + return user_control_stat_totals + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_control_stats.py b/openshock/rest/models/user_control_stats.py new file mode 100644 index 0000000..2bfe84b --- /dev/null +++ b/openshock/rest/models/user_control_stats.py @@ -0,0 +1,132 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.basic_user_info import BasicUserInfo + from ..models.control_stat_totals import ControlStatTotals + + +T = TypeVar("T", bound="UserControlStats") + + +@_attrs_define +class UserControlStats: + """ + Attributes: + user_id (None | UUID): Null for guests (public shares). + user (BasicUserInfo | None): + stats (list[ControlStatTotals]): + """ + + user_id: None | UUID + user: BasicUserInfo | None + stats: list[ControlStatTotals] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + + user_id: None | str + if isinstance(self.user_id, UUID): + user_id = str(self.user_id) + else: + user_id = self.user_id + + user: dict[str, Any] | None + if isinstance(self.user, BasicUserInfo): + user = self.user.to_dict() + else: + user = self.user + + stats = [] + for stats_item_data in self.stats: + stats_item = stats_item_data.to_dict() + stats.append(stats_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "userId": user_id, + "user": user, + "stats": stats, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + from ..models.control_stat_totals import ControlStatTotals # noqa: PLC0415 + + d = dict(src_dict) + + def _parse_user_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + user_id_type_1 = UUID(data) + + return user_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + user_id = _parse_user_id(d.pop("userId")) + + def _parse_user(data: object) -> BasicUserInfo | None: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + user_type_1 = BasicUserInfo.from_dict(data) + + return user_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(BasicUserInfo | None, data) + + user = _parse_user(d.pop("user")) + + stats = [] + _stats = d.pop("stats") + for stats_item_data in _stats: + stats_item = ControlStatTotals.from_dict(stats_item_data) + + stats.append(stats_item) + + user_control_stats = cls( + user_id=user_id, + user=user, + stats=stats, + ) + + user_control_stats.additional_properties = d + return user_control_stats + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_name_blacklist_dto.py b/openshock/rest/models/user_name_blacklist_dto.py new file mode 100644 index 0000000..3f1a8e9 --- /dev/null +++ b/openshock/rest/models/user_name_blacklist_dto.py @@ -0,0 +1,90 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.match_type_enum import MatchTypeEnum + +T = TypeVar("T", bound="UserNameBlacklistDto") + + +@_attrs_define +class UserNameBlacklistDto: + """ + Attributes: + id (UUID): + value (str): + match_type (MatchTypeEnum): + created_at (datetime.datetime): + """ + + id: UUID + value: str + match_type: MatchTypeEnum + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + value = self.value + + match_type = self.match_type.value + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "value": value, + "matchType": match_type, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + value = d.pop("value") + + match_type = MatchTypeEnum(d.pop("matchType")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + user_name_blacklist_dto = cls( + id=id, + value=value, + match_type=match_type, + created_at=created_at, + ) + + user_name_blacklist_dto.additional_properties = d + return user_name_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_patch_dto.py b/openshock/rest/models/user_patch_dto.py new file mode 100644 index 0000000..b4432b7 --- /dev/null +++ b/openshock/rest/models/user_patch_dto.py @@ -0,0 +1,94 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="UserPatchDto") + + +@_attrs_define +class UserPatchDto: + """ + Attributes: + name (None | str | Unset): + email (None | str | Unset): + """ + + name: None | str | Unset = UNSET + email: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name: None | str | Unset + if isinstance(self.name, Unset): + name = UNSET + else: + name = self.name + + email: None | str | Unset + if isinstance(self.email, Unset): + email = UNSET + else: + email = self.email + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if name is not UNSET: + field_dict["name"] = name + if email is not UNSET: + field_dict["email"] = email + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_name(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + name = _parse_name(d.pop("name", UNSET)) + + def _parse_email(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + email = _parse_email(d.pop("email", UNSET)) + + user_patch_dto = cls( + name=name, + email=email, + ) + + user_patch_dto.additional_properties = d + return user_patch_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_self_response.py b/openshock/rest/models/user_self_response.py new file mode 100644 index 0000000..62bef64 --- /dev/null +++ b/openshock/rest/models/user_self_response.py @@ -0,0 +1,113 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.role_type import RoleType + +T = TypeVar("T", bound="UserSelfResponse") + + +@_attrs_define +class UserSelfResponse: + """ + Attributes: + id (UUID): + name (str): + email (str): + image (str): + roles (list[RoleType]): + has_password (bool): + """ + + id: UUID + name: str + email: str + image: str + roles: list[RoleType] + has_password: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + email = self.email + + image = self.image + + roles = [] + for roles_item_data in self.roles: + roles_item = roles_item_data.value + roles.append(roles_item) + + has_password = self.has_password + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "email": email, + "image": image, + "roles": roles, + "hasPassword": has_password, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + email = d.pop("email") + + image = d.pop("image") + + roles = [] + _roles = d.pop("roles") + for roles_item_data in _roles: + roles_item = RoleType(roles_item_data) + + roles.append(roles_item) + + has_password = d.pop("hasPassword") + + user_self_response = cls( + id=id, + name=name, + email=email, + image=image, + roles=roles, + has_password=has_password, + ) + + user_self_response.additional_properties = d + return user_self_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_share_info.py b/openshock/rest/models/user_share_info.py new file mode 100644 index 0000000..555c039 --- /dev/null +++ b/openshock/rest/models/user_share_info.py @@ -0,0 +1,120 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + +T = TypeVar("T", bound="UserShareInfo") + + +@_attrs_define +class UserShareInfo: + """ + Attributes: + id (UUID): + name (str): + created_on (datetime.datetime): + permissions (ShockerPermissions): + limits (ShockerLimits): + paused (int): An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where + reasons are OR'd together. + + Each bit corresponds to: + - 1: Shocker + - 2: UserShare + - 4: PublicShare + + For example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons. + """ + + id: UUID + name: str + created_on: datetime.datetime + permissions: ShockerPermissions + limits: ShockerLimits + paused: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_on = self.created_on.isoformat() + + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + + paused = self.paused + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdOn": created_on, + "permissions": permissions, + "limits": limits, + "paused": paused, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + + paused = d.pop("paused") + + user_share_info = cls( + id=id, + name=name, + created_on=created_on, + permissions=permissions, + limits=limits, + paused=paused, + ) + + user_share_info.additional_properties = d + return user_share_info + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/username_availability.py b/openshock/rest/models/username_availability.py new file mode 100644 index 0000000..844c793 --- /dev/null +++ b/openshock/rest/models/username_availability.py @@ -0,0 +1,11 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class UsernameAvailability(StrEnum): + AVAILABLE = "Available" + INVALID = "Invalid" + TAKEN = "Taken" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/username_check_response.py b/openshock/rest/models/username_check_response.py new file mode 100644 index 0000000..6152a2a --- /dev/null +++ b/openshock/rest/models/username_check_response.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.username_availability import UsernameAvailability +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.username_error import UsernameError + + +T = TypeVar("T", bound="UsernameCheckResponse") + + +@_attrs_define +class UsernameCheckResponse: + """ + Attributes: + availability (UsernameAvailability): + error (None | Unset | UsernameError): + """ + + availability: UsernameAvailability + error: None | Unset | UsernameError = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.username_error import UsernameError # noqa: PLC0415 + + availability = self.availability.value + + error: dict[str, Any] | None | Unset + if isinstance(self.error, Unset): + error = UNSET + elif isinstance(self.error, UsernameError): + error = self.error.to_dict() + else: + error = self.error + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "availability": availability, + } + ) + if error is not UNSET: + field_dict["error"] = error + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.username_error import UsernameError # noqa: PLC0415 + + d = dict(src_dict) + availability = UsernameAvailability(d.pop("availability")) + + def _parse_error(data: object) -> None | Unset | UsernameError: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, dict): + raise TypeError() + error_type_1 = UsernameError.from_dict(data) + + return error_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | Unset | UsernameError, data) + + error = _parse_error(d.pop("error", UNSET)) + + username_check_response = cls( + availability=availability, + error=error, + ) + + username_check_response.additional_properties = d + return username_check_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/username_error.py b/openshock/rest/models/username_error.py new file mode 100644 index 0000000..8917868 --- /dev/null +++ b/openshock/rest/models/username_error.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.username_error_type import UsernameErrorType + +T = TypeVar("T", bound="UsernameError") + + +@_attrs_define +class UsernameError: + """ + Attributes: + message (str): + type_ (UsernameErrorType): + """ + + message: str + type_: UsernameErrorType + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + type_ = self.type_.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "type": type_, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + message = d.pop("message") + + type_ = UsernameErrorType(d.pop("type")) + + username_error = cls( + message=message, + type_=type_, + ) + + username_error.additional_properties = d + return username_error + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/username_error_type.py b/openshock/rest/models/username_error_type.py new file mode 100644 index 0000000..360998a --- /dev/null +++ b/openshock/rest/models/username_error_type.py @@ -0,0 +1,14 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class UsernameErrorType(StrEnum): + BLACKLISTED = "Blacklisted" + OBNOXIOUSCHARACTERS = "ObnoxiousCharacters" + RESEMBLEEMAIL = "ResembleEmail" + STARTORENDWITHWHITESPACE = "StartOrEndWithWhitespace" + TOOLONG = "TooLong" + TOOSHORT = "TooShort" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/v2_user_shares.py b/openshock/rest/models/v2_user_shares.py new file mode 100644 index 0000000..286e44c --- /dev/null +++ b/openshock/rest/models/v2_user_shares.py @@ -0,0 +1,92 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.v2_user_shares_list_item import V2UserSharesListItem + + +T = TypeVar("T", bound="V2UserShares") + + +@_attrs_define +class V2UserShares: + """ + Attributes: + outgoing (list[V2UserSharesListItem]): + incoming (list[V2UserSharesListItem]): + """ + + outgoing: list[V2UserSharesListItem] + incoming: list[V2UserSharesListItem] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + outgoing = [] + for outgoing_item_data in self.outgoing: + outgoing_item = outgoing_item_data.to_dict() + outgoing.append(outgoing_item) + + incoming = [] + for incoming_item_data in self.incoming: + incoming_item = incoming_item_data.to_dict() + incoming.append(incoming_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "outgoing": outgoing, + "incoming": incoming, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.v2_user_shares_list_item import V2UserSharesListItem # noqa: PLC0415 + + d = dict(src_dict) + outgoing = [] + _outgoing = d.pop("outgoing") + for outgoing_item_data in _outgoing: + outgoing_item = V2UserSharesListItem.from_dict(outgoing_item_data) + + outgoing.append(outgoing_item) + + incoming = [] + _incoming = d.pop("incoming") + for incoming_item_data in _incoming: + incoming_item = V2UserSharesListItem.from_dict(incoming_item_data) + + incoming.append(incoming_item) + + v2_user_shares = cls( + outgoing=outgoing, + incoming=incoming, + ) + + v2_user_shares.additional_properties = d + return v2_user_shares + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/v2_user_shares_list_item.py b/openshock/rest/models/v2_user_shares_list_item.py new file mode 100644 index 0000000..70ca4d0 --- /dev/null +++ b/openshock/rest/models/v2_user_shares_list_item.py @@ -0,0 +1,101 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.user_share_info import UserShareInfo + + +T = TypeVar("T", bound="V2UserSharesListItem") + + +@_attrs_define +class V2UserSharesListItem: + """ + Attributes: + id (UUID): + name (str): + image (str): + shares (list[UserShareInfo]): + """ + + id: UUID + name: str + image: str + shares: list[UserShareInfo] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + image = self.image + + shares = [] + for shares_item_data in self.shares: + shares_item = shares_item_data.to_dict() + shares.append(shares_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "image": image, + "shares": shares, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.user_share_info import UserShareInfo # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + image = d.pop("image") + + shares = [] + _shares = d.pop("shares") + for shares_item_data in _shares: + shares_item = UserShareInfo.from_dict(shares_item_data) + + shares.append(shares_item) + + v2_user_shares_list_item = cls( + id=id, + name=name, + image=image, + shares=shares, + ) + + v2_user_shares_list_item.additional_properties = d + return v2_user_shares_list_item + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/webhook_dto.py b/openshock/rest/models/webhook_dto.py new file mode 100644 index 0000000..ba0eb10 --- /dev/null +++ b/openshock/rest/models/webhook_dto.py @@ -0,0 +1,88 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="WebhookDto") + + +@_attrs_define +class WebhookDto: + """ + Attributes: + id (UUID): + name (str): + url (str): + created_at (datetime.datetime): + """ + + id: UUID + name: str + url: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + url = self.url + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "url": url, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + url = d.pop("url") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + webhook_dto = cls( + id=id, + name=name, + url=url, + created_at=created_at, + ) + + webhook_dto.additional_properties = d + return webhook_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/types.py b/openshock/rest/types.py new file mode 100644 index 0000000..63f524a --- /dev/null +++ b/openshock/rest/types.py @@ -0,0 +1,55 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains some shared types for properties""" + +from collections.abc import Mapping, MutableMapping +from http import HTTPStatus +from typing import IO, BinaryIO, Generic, Literal, TypeVar + +from attrs import define + + +class Unset: + def __bool__(self) -> Literal[False]: + return False + + +UNSET: Unset = Unset() + +# The types that `httpx2.Client(files=)` can accept, copied from that library. +FileContent = IO[bytes] | bytes | str +FileTypes = ( + # (filename, file (or bytes), content_type) + tuple[str | None, FileContent, str | None] + # (filename, file (or bytes), content_type, headers) + | tuple[str | None, FileContent, str | None, Mapping[str, str]] +) +RequestFiles = list[tuple[str, FileTypes]] + + +@define +class File: + """Contains information for file uploads""" + + payload: BinaryIO + file_name: str | None = None + mime_type: str | None = None + + def to_tuple(self) -> FileTypes: + """Return a tuple representation that httpx2 will accept for multipart/form-data""" + return self.file_name, self.payload, self.mime_type + + +T = TypeVar("T") + + +@define +class Response(Generic[T]): + """A response from an endpoint""" + + status_code: HTTPStatus + content: bytes + headers: MutableMapping[str, str] + parsed: T | None + + +__all__ = ["UNSET", "File", "FileTypes", "RequestFiles", "Response", "Unset"] diff --git a/pyproject.toml b/pyproject.toml index 0fedc9e..df79edd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,22 +7,23 @@ name = "openshock" version = "0.2.0b1" description = "The official OpenShock Python SDK to integrate with an OpenShock backend easily" readme = "README.md" -requires-python = ">=3.10" +requires-python = ">=3.11" license = { text = "MIT" } authors = [ { name = "OpenShock", email = "contact@openshock.app" }, ] dependencies = [ - "httpx>=0.28.1", + "httpx2>=2.13.1,<3", + "attrs>=23.1", ] keywords = ["openshock", "api", "iot", "signalr", "asyncio"] classifiers = [ "Development Status :: 3 - Alpha", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "Framework :: AsyncIO", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", @@ -40,22 +41,27 @@ Issues = "https://github.com/OpenShock/SDK.Python/issues" realtime = [ "websockets>=13.0", ] +# Pinned toolchain for scripts/generate.py. The versions decide the generated output, so +# bump them deliberately and regenerate in the same change. +codegen = [ + "openapi-python-client==0.30.0", + "ruff==0.17.6", +] dev = [ - "openshock[realtime]", + "openshock[realtime,codegen]", "pytest>=8.0", "pytest-asyncio>=0.24", "pytest-cov", "pytest-timeout", "mypy>=1.10", - "ruff>=0.8", ] # --- ruff (linter + formatter) --- [tool.ruff] -target-version = "py310" +target-version = "py311" line-length = 120 -# Generated from openshock/_async by scripts/unasync.py; formatting it would make it drift. -extend-exclude = ["openshock/_sync"] +# Generated by scripts/generate.py, which formats it itself. +extend-exclude = ["openshock/rest"] [tool.ruff.lint] select = ["E", "F", "W", "I", "UP", "B", "SIM"] @@ -65,7 +71,7 @@ known-first-party = ["openshock"] # --- mypy --- [tool.mypy] -python_version = "3.10" +python_version = "3.11" strict = true warn_return_any = true warn_unused_configs = true @@ -81,3 +87,7 @@ testpaths = ["tests"] asyncio_mode = "auto" timeout = 30 asyncio_default_fixture_loop_scope = "function" + +[tool.coverage.run] +# Generated code; tests/test_generated.py checks it against the spec instead. +omit = ["openshock/rest/*"] diff --git a/scripts/generate.py b/scripts/generate.py new file mode 100644 index 0000000..87820ff --- /dev/null +++ b/scripts/generate.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +""" +Generate the REST client (openshock/rest) from the backend's OpenAPI document. + +Everything under openshock/rest is generated. Never edit it by hand: change the backend, +refresh the spec snapshot and regenerate. + + python scripts/generate.py # regenerate openshock/rest from openapi/openapi.json + python scripts/generate.py --update # download the latest spec first, then regenerate + python scripts/generate.py --check # exit 1 if openshock/rest is out of date (used in CI) + +Requires the pinned generator toolchain: pip install -e ".[codegen]" +""" + +from __future__ import annotations + +import argparse +import filecmp +import json +import os +import shutil +import subprocess +import sys +import tempfile +import urllib.request +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parent.parent +SPEC = ROOT / "openapi" / "openapi.json" +CONFIG = ROOT / "openapi" / "generator-config.yaml" +TARGET = ROOT / "openshock" / "rest" +DEFAULT_SPEC_URL = "https://api.openshock.app/openapi.json" + +JSON = "application/json" +HEADER = "# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand.\n" + + +def prepare(spec: dict[str, Any]) -> dict[str, Any]: + """Adjust the document where the generator cannot take it as published.""" + # The backend declares OpenAPI 3.2.0, the generator accepts 3.1 only. The document uses + # nothing that is specific to 3.2, so relabelling is enough. + if str(spec.get("openapi", "")).startswith("3.2"): + spec["openapi"] = "3.1.0" + + # ASP.NET lists every JSON flavour it accepts (application/json, text/json, + # application/*+json). The generator would emit one branch per flavour and send the + # last one as Content-Type, so keep plain JSON wherever it is offered. + for path_item in spec.get("paths", {}).values(): + for operation in path_item.values(): + if not isinstance(operation, dict): + continue + bodies = [operation.get("requestBody"), *(operation.get("responses") or {}).values()] + for body in bodies: + content = (body or {}).get("content") + if content and JSON in content: + body["content"] = {JSON: content[JSON]} + return spec + + +def generate(output: Path) -> None: + with tempfile.TemporaryDirectory() as tmp: + prepared = Path(tmp) / "openapi.json" + prepared.write_text(json.dumps(prepare(json.loads(SPEC.read_text(encoding="utf-8")))), encoding="utf-8") + result = subprocess.run( + [ + sys.executable, "-m", "openapi_python_client", "generate", + "--path", str(prepared), + "--config", str(CONFIG), + "--meta", "none", + "--output-path", str(output), + "--overwrite", + ], + capture_output=True, + text=True, + # The post hooks call ruff by name; make sure the one next to this interpreter is found. + env={**os.environ, "PATH": f"{Path(sys.executable).parent}{os.pathsep}{os.environ.get('PATH', '')}"}, + ) # fmt: skip + report = (result.stdout + result.stderr).strip() + if result.returncode != 0 or "WARNING" in report or "Error" in report: + # Warnings mean an operation or model was skipped. Treat that as a failure rather + # than silently shipping an incomplete client. + print(report) + raise SystemExit("Generation failed or was incomplete.") + for path in output.rglob("*.py"): + text = path.read_text(encoding="utf-8") + if text.strip(): + path.write_text(HEADER + text, encoding="utf-8") + + +def differences(left: Path, right: Path) -> list[str]: + """Relative paths of Python files that differ between two trees.""" + + def files(root: Path) -> set[str]: + return {str(p.relative_to(root)) for p in root.rglob("*.py")} if root.exists() else set() + + a, b = files(left), files(right) + changed = sorted(a ^ b) + changed += sorted(name for name in a & b if not filecmp.cmp(left / name, right / name, shallow=False)) + return changed + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--update", action="store_true", help="download the latest spec before generating") + parser.add_argument("--url", default=DEFAULT_SPEC_URL, help="where --update downloads the spec from") + parser.add_argument("--check", action="store_true", help="verify openshock/rest is up to date, change nothing") + args = parser.parse_args() + + if args.update: + with urllib.request.urlopen(args.url, timeout=30) as response: + document = json.load(response) + SPEC.write_text(json.dumps(document, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"Updated {SPEC.relative_to(ROOT)} from {args.url}") + + with tempfile.TemporaryDirectory() as tmp: + fresh = Path(tmp) / "rest" + generate(fresh) + changed = differences(fresh, TARGET) + if args.check: + if changed: + print("openshock/rest is out of date. Run `python scripts/generate.py`. Differing files:") + for name in changed[:50]: + print(f" {name}") + return 1 + print("openshock/rest is up to date") + return 0 + if TARGET.exists(): + shutil.rmtree(TARGET) + shutil.copytree(fresh, TARGET) + print(f"Generated {sum(1 for _ in TARGET.rglob('*.py'))} files into openshock/rest ({len(changed)} changed)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/unasync.py b/scripts/unasync.py deleted file mode 100644 index fce11e0..0000000 --- a/scripts/unasync.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python3 -""" -Generate the synchronous client (openshock/_sync) from the async one (openshock/_async). - -The async code is the single source of truth. Run this after editing anything under -openshock/_async: - - python scripts/unasync.py # rewrite openshock/_sync - python scripts/unasync.py --check # exit 1 if openshock/_sync is out of date (used in CI) -""" - -from __future__ import annotations - -import re -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -SRC = ROOT / "openshock" / "_async" -DST = ROOT / "openshock" / "_sync" - -HEADER = "# This file is generated from openshock/_async by scripts/unasync.py. Do not edit it by hand.\n" - -# Applied in order, on whole words. -REPLACEMENTS: list[tuple[str, str]] = [ - (r"\basync def\b", "def"), - (r"\basync with\b", "with"), - (r"\basync for\b", "for"), - (r"\bawait ", ""), - (r"\bAsyncOpenShock(\w*)Client\b", r"OpenShock\1Client"), - (r"\b_AsyncBaseClient\b", "_BaseClient"), - (r"\bAsync(\w+)Resource\b", r"\1Resource"), - (r"\bhttpx\.AsyncClient\b", "httpx.Client"), - (r"\bhttpx\.AsyncBaseTransport\b", "httpx.BaseTransport"), - (r"\b__aenter__\b", "__enter__"), - (r"\b__aexit__\b", "__exit__"), - (r"\baclose\b", "close"), -] - - -def convert(source: str) -> str: - for pattern, repl in REPLACEMENTS: - source = re.sub(pattern, repl, source) - return HEADER + source if source.strip() else source - - -def main() -> int: - check = "--check" in sys.argv[1:] - stale: list[Path] = [] - expected: set[Path] = set() - - for src in sorted(SRC.rglob("*.py")): - dst = DST / src.relative_to(SRC) - expected.add(dst) - new = convert(src.read_text(encoding="utf-8")) - old = dst.read_text(encoding="utf-8") if dst.exists() else None - if new == old: - continue - stale.append(dst) - if not check: - dst.parent.mkdir(parents=True, exist_ok=True) - dst.write_text(new, encoding="utf-8") - - for dst in sorted(DST.rglob("*.py")) if DST.exists() else []: - if dst not in expected: - stale.append(dst) - if not check: - dst.unlink() - - if check and stale: - print("openshock/_sync is out of date. Run `python scripts/unasync.py`. Stale files:") - for path in stale: - print(f" {path.relative_to(ROOT)}") - return 1 - if not check: - print(f"unasync: {len(stale)} file(s) updated") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tests/test_client.py b/tests/test_client.py index b2f92a8..cd15387 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,71 +1,241 @@ -"""Tests for client construction and error handling.""" +"""The preconfigured clients driving generated operations: headers, sync/async, error mapping.""" -import pytest - -from openshock import OpenShockClient, OpenShockHubClient -from openshock.exceptions import OpenShockApiError, OpenShockAuthError, OpenShockError, OpenShockNotFound - - -class TestClientConstruction: - def test_api_token(self): - client = OpenShockClient(api_token="test-token") - assert client._auth is not None - client.close() - - def test_hub_token(self): - client = OpenShockHubClient(hub_token="test-token") - assert client._auth is not None - client.close() - - def test_no_auth_raises(self): - with pytest.raises(ValueError, match="must provide"): - OpenShockClient() - - def test_both_auth_raises(self): - from openshock.auth import ApiTokenAuth - - with pytest.raises(ValueError, match="not both"): - OpenShockClient(auth=ApiTokenAuth("x"), api_token="y") +import json +from uuid import UUID - def test_context_manager(self): - with OpenShockClient(api_token="test") as client: - assert hasattr(client, "meta") - assert hasattr(client, "account") - assert hasattr(client, "devices") - assert hasattr(client, "shockers") - assert hasattr(client, "shares") - assert hasattr(client, "sessions") - assert hasattr(client, "user_shares") +import httpx2 +import pytest - def test_hub_context_manager(self): - with OpenShockHubClient(hub_token="test") as client: - assert hasattr(client, "hub") - assert hasattr(client, "meta") +from openshock import ( + HubOffline, + OpenShockApiError, + OpenShockAuthError, + OpenShockClient, + OpenShockHubClient, + OpenShockNotFound, + OpenShockRateLimited, + ShockerNoPermission, + ShockerNotFoundOrNoAccess, + ShockerPaused, + TokenPermissionMissing, + unwrap, +) +from openshock.rest.api.hub_endpoints import device_get_self +from openshock.rest.api.hub_management import devices_get_live_control_gateway_info_v2, devices_list_devices +from openshock.rest.api.shockers import shocker_list_shockers, shocker_send_control +from openshock.rest.client import AuthenticatedClient +from openshock.rest.models import Control, ControlRequest, ControlType, OpenShockProblem, ShockerModelType + +HUB = "11111111-1111-1111-1111-111111111111" +SHOCKER = "22222222-2222-2222-2222-222222222222" + +OWN_SHOCKERS = { + "message": "", + "data": [ + { + "id": HUB, + "name": "My Hub", + "createdOn": "2024-06-01T12:00:00.1234567Z", + "shockers": [ + { + "id": SHOCKER, + "rfId": 1234, + "model": "CaiXianlin", + "name": "Leg", + "isPaused": False, + "createdOn": "2024-06-01T12:00:00Z", + "somethingNewer": {"than": "the spec"}, + } + ], + } + ], +} +CONTROL = ControlRequest( + shocks=[Control(id=UUID(SHOCKER), type_=ControlType.VIBRATE, intensity=25, duration=1000)], + custom_name="Bot", +) + + +def problem(type_: str, status: int, **extra) -> httpx2.Response: + body = {"type": type_, "title": "Nope", "status": status, "requestId": "req-1", **extra} + return httpx2.Response(status, json=body, headers={"Content-Type": "application/problem+json"}) + + +def client_for(response: httpx2.Response, cls=OpenShockClient, **kwargs): + seen: list[httpx2.Request] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + seen.append(request) + return response + + return cls("tok", httpx_args={"transport": httpx2.MockTransport(handler)}, **kwargs), seen + + +class TestPresets: + def test_api_token_header_and_user_agent(self): + client, seen = client_for(httpx2.Response(200, json=OWN_SHOCKERS), app_name="MyApp", app_version="1.2.3") + with client: + shocker_list_shockers.sync(client=client) + assert seen[0].headers["OpenShockToken"] == "tok" + assert "Authorization" not in seen[0].headers + ua = seen[0].headers["User-Agent"] + assert ua.startswith("OpenShock.SDK.Python/") and "MyApp 1.2.3" in ua and "httpx2" in ua + assert seen[0].url == "https://api.openshock.app/1/shockers/own" + + def test_hub_client_uses_device_token(self): + body = { + "message": "", + "data": {"id": HUB, "name": "d", "shockers": [{"id": SHOCKER, "rfId": 1, "model": "CaiXianlin"}]}, + } + client, seen = client_for(httpx2.Response(200, json=body), cls=OpenShockHubClient) + with client: + me = unwrap(device_get_self.sync(client=client)) + assert seen[0].headers["DeviceToken"] == "tok" + assert me.data.shockers[0].id == UUID(SHOCKER) def test_custom_base_url(self): - client = OpenShockClient(api_token="test", base_url="https://custom.api.example.com") - assert "custom.api.example.com" in str(client._client.base_url) - client.close() - - -class TestExceptionHierarchy: - def test_auth_error_is_openshock_error(self): - assert issubclass(OpenShockAuthError, OpenShockError) - - def test_not_found_is_openshock_error(self): - assert issubclass(OpenShockNotFound, OpenShockError) - - def test_api_error_is_openshock_error(self): - assert issubclass(OpenShockApiError, OpenShockError) - - def test_status_errors_are_api_errors(self): + client, seen = client_for(httpx2.Response(200, json=OWN_SHOCKERS), base_url="https://api.example.org/") + with client: + shocker_list_shockers.sync(client=client) + assert seen[0].url == "https://api.example.org/1/shockers/own" + assert client.base_url == "https://api.example.org" + + def test_token_is_required(self): + with pytest.raises(ValueError): + OpenShockClient() + with pytest.raises(ValueError): + OpenShockHubClient("") + + def test_generated_with_helpers_keep_the_preset(self): + client = OpenShockClient("tok", app_name="MyApp", app_version="1.0") + derived = client.with_headers({"X-Extra": "1"}) + assert isinstance(derived, OpenShockClient) + assert derived.auth_headers == {"OpenShockToken": "tok"} + http = derived.get_httpx_client() + assert http.headers["X-Extra"] == "1" and "MyApp 1.0" in http.headers["User-Agent"] + assert http.headers["OpenShockToken"] == "tok" + http.close() + + def test_is_a_generated_client(self): + assert isinstance(OpenShockClient("tok"), AuthenticatedClient) + + +class TestCalls: + def test_sync_call_parses_models(self): + client, _ = client_for(httpx2.Response(200, json=OWN_SHOCKERS)) + with client: + hubs = unwrap(shocker_list_shockers.sync(client=client)).data + shocker = hubs[0].shockers[0] + assert hubs[0].id == UUID(HUB) + assert hubs[0].created_on.microsecond == 123456 + assert shocker.model is ShockerModelType.CAIXIANLIN + assert shocker.rf_id == 1234 and not shocker.is_paused + # Fields the backend added after this client was generated are kept, not dropped. + assert shocker["somethingNewer"] == {"than": "the spec"} + + async def test_async_call_parses_models(self): + client, seen = client_for(httpx2.Response(200, json=OWN_SHOCKERS)) + async with client: + hubs = unwrap(await shocker_list_shockers.asyncio(client=client)).data + assert hubs[0].shockers[0].name == "Leg" + assert seen[0].headers["OpenShockToken"] == "tok" + + def test_request_body(self): + client, seen = client_for(httpx2.Response(200, json={"message": "ok"})) + with client: + shocker_send_control.sync(client=client, body=CONTROL) + assert seen[0].method == "POST" and seen[0].url.path == "/2/shockers/control" + assert seen[0].headers["Content-Type"] == "application/json" + assert json.loads(seen[0].content) == { + "shocks": [{"id": SHOCKER, "type": "Vibrate", "intensity": 25, "duration": 1000}], + "customName": "Bot", + } + + def test_detailed_variant_and_unwrap(self): + gateway = {"host": "gw.example", "port": 443, "pathPrefix": "", "country": "DE"} + client, _ = client_for(httpx2.Response(200, json=gateway)) + with client: + response = devices_get_live_control_gateway_info_v2.sync_detailed(UUID(HUB), client=client) + assert response.status_code == 200 + assert unwrap(response).host == "gw.example" + + +class TestErrors: + @pytest.mark.parametrize( + ("type_", "status", "expected"), + [ + ("Shocker.Control.NotFound", 404, ShockerNotFoundOrNoAccess), + ("Shocker.Control.Paused", 412, ShockerPaused), + ("Shocker.Control.NoPermission", 403, ShockerNoPermission), + ], + ) + def test_control_problems_raise(self, type_, status, expected): + client, _ = client_for(problem(type_, status, shockerId=SHOCKER)) + with client, pytest.raises(expected) as info: + shocker_send_control.sync(client=client, body=CONTROL) + err = info.value + assert err.shocker_id == UUID(SHOCKER) + assert err.status_code == status and err.problem_type == type_ + assert err.problem is not None and err.problem.request_id == "req-1" + assert "POST https://api.openshock.app/2/shockers/control" in str(err) + + async def test_async_errors_raise_too(self): + client, _ = client_for(problem("Shocker.Control.Paused", 412, shockerId=SHOCKER)) + async with client: + with pytest.raises(ShockerPaused): + await shocker_send_control.asyncio(client=client, body=CONTROL) + with pytest.raises(ShockerPaused): + await shocker_send_control.asyncio_detailed(client=client, body=CONTROL) + + def test_hub_offline(self): + client, _ = client_for(problem("Device.NotOnline", 404)) + with client, pytest.raises(HubOffline): + devices_get_live_control_gateway_info_v2.sync(UUID(HUB), client=client) + + def test_token_permission_missing(self): + response = problem( + "Authorization.Token.PermissionMissing", + 403, + requiredPermission="devices.edit", + grantedPermissions=["shockers.use"], + ) + client, _ = client_for(response) + with client, pytest.raises(TokenPermissionMissing) as info: + devices_list_devices.sync(client=client) + assert info.value.required_permission == "devices.edit" + assert info.value.granted_permissions == ["shockers.use"] + + @pytest.mark.parametrize( + ("response", "expected"), + [ + (httpx2.Response(401, text=""), OpenShockAuthError), + (httpx2.Response(404, text="gone"), OpenShockNotFound), + (httpx2.Response(429, text="slow down", headers={"Retry-After": "7"}), OpenShockRateLimited), + (httpx2.Response(500, text="boom"), OpenShockApiError), + ], + ) + def test_undocumented_statuses_raise_by_status(self, response, expected): + client, _ = client_for(response) + with client, pytest.raises(expected) as info: + shocker_list_shockers.sync(client=client) + assert info.value.status_code == response.status_code + if expected is OpenShockRateLimited: + assert info.value.retry_after == 7 + + def test_specific_errors_keep_their_generic_base(self): + assert issubclass(ShockerNotFoundOrNoAccess, OpenShockNotFound) + assert issubclass(ShockerNoPermission, OpenShockAuthError) + assert issubclass(HubOffline, OpenShockNotFound) assert issubclass(OpenShockAuthError, OpenShockApiError) - assert issubclass(OpenShockNotFound, OpenShockApiError) - - -def test_resource_classes_are_importable(): - from openshock.resources import AsyncShockersResource, ShockersResource - with OpenShockClient(api_token="test") as client: - assert isinstance(client.shockers, ShockersResource) - assert not isinstance(client.shockers, AsyncShockersResource) + def test_raise_on_error_can_be_turned_off(self): + client, _ = client_for(problem("Shocker.Control.Paused", 412, shockerId=SHOCKER), raise_on_error=False) + with client: + result = shocker_send_control.sync(client=client, body=CONTROL) + assert isinstance(result, OpenShockProblem) and result.type_ == "Shocker.Control.Paused" + # unwrap turns a returned problem into the same typed error. + with pytest.raises(ShockerPaused) as info: + unwrap(result) + assert info.value.shocker_id == UUID(SHOCKER) + with pytest.raises(ShockerPaused): + unwrap(shocker_send_control.sync_detailed(client=client, body=CONTROL)) diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py deleted file mode 100644 index d1c1e9b..0000000 --- a/tests/test_endpoints.py +++ /dev/null @@ -1,228 +0,0 @@ -"""Every REST method, sync and async: hits the right route and parses a realistic response.""" - -from __future__ import annotations - -import inspect -import json -from typing import Any -from uuid import UUID - -import httpx -import pytest - -from openshock import ( - AsyncOpenShockClient, - AsyncOpenShockHubClient, - OpenShockClient, - OpenShockHubClient, - OtaUpdateStatus, - PauseReason, - ShareInviteShocker, - ShockerLimits, - ShockerPermissions, -) - -A = "11111111-1111-1111-1111-111111111111" -B = "22222222-2222-2222-2222-222222222222" -NOW = "2024-06-01T12:00:00Z" -PERMS = {"vibrate": True, "sound": True, "shock": True, "live": False} -LIMITS = {"intensity": 50, "duration": 3000} -USER = {"id": A, "name": "user", "image": "https://img"} -SHOCKER = {"id": B, "rfId": 1, "model": "CaiXianlin", "name": "s", "isPaused": False, "createdOn": NOW} -TOKEN = {"id": A, "name": "t", "createdOn": NOW, "validUntil": None, "lastUsed": NOW, "permissions": ["shockers.use"]} -SESSION = {"id": A, "ip": "::1", "userAgent": "ua", "created": NOW, "expires": NOW, "lastUsed": None} -LOG = { - "id": A, - "createdOn": NOW, - "type": "Shock", - "controlledBy": {**USER, "customName": None}, - "intensity": 1, - "duration": 300, - "liveControl": False, -} -SHARE_ITEM = {"id": B, "name": "s", "createdOn": NOW, "permissions": PERMS, "limits": LIMITS, "paused": 0} -USER_SHARE = {**USER, "shares": [SHARE_ITEM]} -INVITE = { - "id": A, - "createdAt": NOW, - "owner": USER, - "sharedWith": USER, - "shockers": [{"id": B, "name": "s", "permissions": PERMS, "limits": LIMITS}], -} -PUBLIC_SHARE = { - "id": A, - "name": "p", - "createdOn": NOW, - "expiresOn": None, - "author": USER, - "devices": [{"id": A, "name": "d", "shockers": [{"id": B, "name": "s", "permissions": PERMS, "limits": LIMITS}]}], -} -P = ShockerPermissions(vibrate=True, sound=True, shock=False) -L = ShockerLimits(intensity=10, duration=1000) - - -def data(value: Any) -> dict[str, Any]: - return {"message": "", "data": value} - - -# (resource.method, args, kwargs, HTTP method, path, response body, check(result)) -USER_CASES: list[tuple[str, tuple, dict, str, str, Any, Any]] = [ - ("meta.backend_info", (), {}, "GET", "/1", data({ - "version": "1", "commit": "c", "currentTime": NOW, "frontendUrl": "f", "shortLinkUrl": "s", - "turnstileSiteKey": "k", "isUserAuthenticated": True, "oAuthProviders": ["discord"], - }), lambda r: r.version == "1"), - ("meta.online_stats", (), {}, "GET", "/1/public/stats", - data({"devicesOnline": 4}), lambda r: r.devices_online == 4), - ("account.user_self", (), {}, "GET", "/1/users/self", - data({**USER, "email": "e", "roles": ["Admin"], "rank": "Admin"}), lambda r: r.roles == ["Admin"]), - ("account.token_self", (), {}, "GET", "/1/tokens/self", TOKEN, lambda r: r.name == "t"), - ("account.list_tokens", (), {}, "GET", "/1/tokens", [TOKEN], lambda r: len(r) == 1), - ("account.get_token", (A,), {}, "GET", f"/1/tokens/{A}", TOKEN, lambda r: r.id == UUID(A)), - ("account.edit_token", (A,), {"name": "n"}, "PATCH", f"/1/tokens/{A}", None, lambda r: r is None), - ("account.revoke_token", (A,), {}, "DELETE", f"/1/tokens/{A}", None, lambda r: r is None), - ("devices.list", (), {}, "GET", "/1/devices", - data([{"id": A, "name": "d", "createdOn": NOW}]), lambda r: r[0].name == "d"), - ("devices.edit", (A,), {"name": "n"}, "PATCH", f"/1/devices/{A}", None, lambda r: r is None), - ("devices.delete", (A,), {}, "DELETE", f"/1/devices/{A}", None, lambda r: r is None), - ("devices.regenerate_token", (A,), {}, "PUT", f"/1/devices/{A}", "newtoken", lambda r: r == "newtoken"), - ("devices.shockers", (A,), {}, "GET", f"/1/devices/{A}/shockers", data([SHOCKER]), lambda r: r[0].rf_id == 1), - ("devices.lcg_info", (A,), {}, "GET", f"/1/devices/{A}/lcg", - data({"gateway": "gw", "country": "DE"}), lambda r: r.gateway == "gw"), - ("devices.ota_history", (A,), {}, "GET", f"/1/devices/{A}/ota", - data([{"id": 1, "startedAt": NOW, "status": "Finished", "version": "1.0.0", "message": None}]), - lambda r: r[0].status is OtaUpdateStatus.FINISHED), - ("shockers.get", (B,), {}, "GET", f"/1/shockers/{B}", - data({**SHOCKER, "device": A, "permissions": PERMS, "limits": LIMITS}), lambda r: r.device == UUID(A)), - ("shockers.register", (), {"name": "s", "rf_id": 1, "device": A, "model": "caixianlin"}, - "POST", "/1/shockers", data(B), lambda r: r == UUID(B)), - ("shockers.edit", (B,), {"name": "n", "rf_id": 2, "device": A, "model": "PetTrainer"}, - "PATCH", f"/1/shockers/{B}", None, lambda r: r is None), - ("shockers.logs", (B,), {"limit": 5}, "GET", f"/1/shockers/{B}/logs", data([LOG]), lambda r: r[0].type == "Shock"), - ("shockers.all_logs", (), {}, "GET", "/1/shockers/logs", - data([{**LOG, "hubId": A, "hubName": "h", "shockerId": B, "shockerName": "s"}]), - lambda r: r[0].hub_name == "h" and r[0].shocker_id == UUID(B)), - ("shockers.get_shares", (B,), {}, "GET", f"/1/shockers/{B}/shares", - data([{"sharedWith": USER, "createdOn": NOW, "permissions": PERMS, "limits": LIMITS, "paused": False}]), - lambda r: r[0].shared_with.name == "user"), - ("shockers.create_share_code", (B,), {"permissions": P, "limits": L}, - "POST", f"/1/shockers/{B}/shares", data(A), lambda r: r == UUID(A)), - ("shockers.list_share_codes", (B,), {}, "GET", f"/1/shockers/{B}/shareCodes", - data([{"id": A, "createdOn": NOW}]), lambda r: r[0].id == UUID(A)), - ("shockers.update_share", (B, A), {"permissions": P, "limits": L}, - "PATCH", f"/1/shockers/{B}/shares/{A}", None, lambda r: r is None), - ("shockers.remove_share", (B, A), {}, "DELETE", f"/1/shockers/{B}/shares/{A}", None, lambda r: r is None), - ("shockers.pause_share", (B, A, True), {}, "POST", f"/1/shockers/{B}/shares/{A}/pause", - data(True), lambda r: r is True), - ("shares.list_public", (), {}, "GET", "/1/shares/links", - data([{"id": A, "name": "p", "createdOn": NOW, "expiresOn": None}]), lambda r: r[0].name == "p"), - ("shares.create_public", ("p",), {"expires_on": NOW}, "POST", "/1/shares/links", data(A), lambda r: r == UUID(A)), - ("shares.delete_public", (A,), {}, "DELETE", f"/1/shares/links/{A}", data(None), lambda r: r is None), - ("shares.public_get", (A,), {}, "GET", f"/1/public/shares/links/{A}", - data(PUBLIC_SHARE), lambda r: r.devices[0].shockers[0].paused is PauseReason.NONE), - ("shares.add_shocker", (A, B), {}, "POST", f"/1/shares/links/{A}/{B}", data(None), lambda r: r is None), - ("shares.edit_shocker", (A, B), {"permissions": P, "limits": L, "cooldown": 5}, - "PATCH", f"/1/shares/links/{A}/{B}", data(None), lambda r: r is None), - ("shares.remove_shocker", (A, B), {}, "DELETE", f"/1/shares/links/{A}/{B}", data(None), lambda r: r is None), - ("shares.pause_shocker", (A, B, True), {}, "POST", f"/1/shares/links/{A}/{B}/pause", - data(4), lambda r: r is PauseReason.PUBLIC_SHARE), - ("shares.link_code", (A,), {}, "POST", f"/1/shares/code/{A}", data(None), lambda r: r is None), - ("shares.delete_code", (A,), {}, "DELETE", f"/1/shares/code/{A}", data(None), lambda r: r is None), - ("sessions.list", (), {}, "GET", "/1/sessions", [SESSION], lambda r: r[0].ip == "::1"), - ("sessions.get_current", (), {}, "GET", "/1/sessions/self", SESSION, lambda r: r.user_agent == "ua"), - ("sessions.delete", (A,), {}, "DELETE", f"/1/sessions/{A}", None, lambda r: r is None), - ("user_shares.get", (), {}, "GET", "/2/shares/user", - {"outgoing": [USER_SHARE], "incoming": []}, lambda r: r.outgoing[0].shares[0].limits.intensity == 50), - ("user_shares.create_invite", ([ShareInviteShocker(permissions=P, limits=L, id=UUID(B))],), {"user": A}, - "POST", "/2/shares/user/invites", A, lambda r: r == UUID(A)), - ("user_shares.list_outgoing_invites", (), {}, "GET", "/2/shares/user/invites/outgoing", - [INVITE], lambda r: r[0].owner.name == "user"), - ("user_shares.list_incoming_invites", (), {}, "GET", "/2/shares/user/invites/incoming", - [INVITE], lambda r: r[0].shockers[0].id == UUID(B)), - ("user_shares.accept_invite", (A,), {}, "POST", f"/2/shares/user/invites/incoming/{A}", - USER_SHARE, lambda r: r.name == "user"), - ("user_shares.delete_outgoing_invite", (A,), {}, "DELETE", f"/2/shares/user/invites/outgoing/{A}", - None, lambda r: r is None), - ("user_shares.deny_incoming_invite", (A,), {}, "DELETE", f"/2/shares/user/invites/incoming/{A}", - None, lambda r: r is None), - ("user_shares.bulk_pause_shockers", (A, [B], True), {}, "POST", f"/2/shares/user/{A}/shockers/pause", - {"affectedRecords": 1, "pauseStates": {B: 2}}, - lambda r: r.affected_records == 1 and r.pause_states[UUID(B)] is PauseReason.USER_SHARE), - ("user_shares.bulk_remove_shockers", (A, [B]), {}, "DELETE", f"/2/shares/user/{A}/shockers", - {"affectedRecords": 3}, lambda r: r == 3), - ("user_shares.bulk_update_shockers", (A, [B]), {"permissions": P, "limits": L}, - "PATCH", f"/2/shares/user/{A}/shockers", None, lambda r: r is None), -] # fmt: skip - -HUB_CASES: list[tuple[str, tuple, dict, str, str, Any, Any]] = [ - ("hub.self_info", (), {}, "GET", "/1/device/self", - data({"id": A, "name": "d", "shockers": [{"id": B, "rfId": 1, "model": "CaiXianlin"}]}), - lambda r: r.shockers[0].id == UUID(B)), - ("hub.assign_lcg", (), {"version": 2}, "GET", "/2/device/assignLCG", - {"host": "gw", "port": 443, "path": "/2/ws/hub", "country": "DE"}, lambda r: r.host == "gw"), - ("hub.pair", ("123456",), {}, "GET", "/1/device/pair/123456", data("devicetoken"), lambda r: r == "devicetoken"), - ("meta.online_stats", (), {}, "GET", "/1/public/stats", - data({"devicesOnline": 4}), lambda r: r.devices_online == 4), -] # fmt: skip - - -def _transport(seen: list[httpx.Request], body: Any) -> httpx.MockTransport: - def handler(request: httpx.Request) -> httpx.Response: - seen.append(request) - if body is None: - return httpx.Response(200) - return httpx.Response(200, content=json.dumps(body), headers={"Content-Type": "application/json"}) - - return httpx.MockTransport(handler) - - -def _method(client: Any, name: str) -> Any: - resource, method = name.split(".") - return getattr(getattr(client, resource), method) - - -CASES = [(OpenShockClient, AsyncOpenShockClient, "api_token", c) for c in USER_CASES] + [ - (OpenShockHubClient, AsyncOpenShockHubClient, "hub_token", c) for c in HUB_CASES -] -IDS = [c[3][0] for c in CASES] - - -@pytest.mark.parametrize(("sync_cls", "async_cls", "token_arg", "case"), CASES, ids=IDS) -async def test_endpoint(sync_cls, async_cls, token_arg, case): - name, args, kwargs, http_method, path, body, check = case - - seen: list[httpx.Request] = [] - with sync_cls(**{token_arg: "tok"}, transport=_transport(seen, body)) as client: - assert check(_method(client, name)(*args, **kwargs)), "sync result" - assert (seen[0].method, seen[0].url.path) == (http_method, path) - - seen_async: list[httpx.Request] = [] - async with async_cls(**{token_arg: "tok"}, transport=_transport(seen_async, body)) as aclient: - assert check(await _method(aclient, name)(*args, **kwargs)), "async result" - assert (seen_async[0].method, seen_async[0].url.path) == (http_method, path) - assert seen_async[0].content == seen[0].content - - -def test_every_public_method_is_covered(): - """Fails when a resource method is added without a case above (or in test_rest.py).""" - covered = {c[0] for c in USER_CASES + HUB_CASES} | { - "shockers.list_own", - "shockers.list_shared", - "shockers.control", - "shockers.pause", - "shockers.delete", - "devices.gateway", - "devices.create", - "devices.get", - "devices.pair_code", - "account.create_token", - } - actual = set() - for client in (OpenShockClient(api_token="t"), OpenShockHubClient(hub_token="t")): - for resource_name, resource in vars(client).items(): - if resource_name.startswith("_"): - continue - for method_name, _ in inspect.getmembers(resource, inspect.ismethod): - if not method_name.startswith("_"): - actual.add(f"{resource_name}.{method_name}") - client.close() - assert actual - covered == set() diff --git a/tests/test_enums.py b/tests/test_enums.py deleted file mode 100644 index d5fd04d..0000000 --- a/tests/test_enums.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Wire enums: string compatibility, integer wire form and forward compatibility.""" - -import json - -import pytest - -from openshock import Control, ControlType, PauseReason, PermissionType, ShockerModelType -from openshock.models.common import parse_pause_reason -from openshock.realtime.models import HubUpdateType, LiveResponseType - - -def test_members_equal_their_wire_string(): - assert ControlType.SHOCK == "Shock" - assert str(ControlType.SHOCK) == "Shock" - assert f"{ControlType.SHOCK}" == "Shock" - assert json.dumps({"type": ControlType.SHOCK}) == '{"type": "Shock"}' - - -def test_lookup_is_case_insensitive_and_accepts_integers(): - assert ControlType("vibrate") is ControlType.VIBRATE - assert ControlType("VIBRATE") is ControlType.VIBRATE - assert ControlType(0) is ControlType.STOP - assert ControlType(3) is ControlType.SOUND - assert ControlType("2") is ControlType.VIBRATE - assert HubUpdateType(4) is HubUpdateType.PAIRED - assert ShockerModelType("Petrainer998DR") is ShockerModelType.PETRAINER_998DR - - -def test_to_int_matches_backend_values(): - assert [t.to_int() for t in ControlType] == [0, 1, 2, 3] - assert PermissionType.PUBLICSHARES_EDIT.to_int() == 8 - - -def test_unknown_values_do_not_raise(): - value = PermissionType("future.permission") - assert value == "future.permission" - assert not value.is_known - assert PermissionType.SHOCKERS_USE.is_known - assert ControlType(99) == "99" - with pytest.raises(ValueError): - value.to_int() - - -def test_control_wire_forms(): - control = Control(id="abc", type="vibrate", intensity=10, duration=500) - assert control.to_dict()["type"] == "Vibrate" - assert control.to_signalr()["type"] == 2 - - -def test_pause_reason_parsing(): - assert parse_pause_reason(None) is PauseReason.NONE - assert parse_pause_reason(3) == PauseReason.SHOCKER | PauseReason.USER_SHARE - assert parse_pause_reason("5") == PauseReason.SHOCKER | PauseReason.PUBLIC_SHARE - assert parse_pause_reason("Shocker, UserShare") == PauseReason.SHOCKER | PauseReason.USER_SHARE - - -def test_live_response_type_parsing(): - assert LiveResponseType.parse("TPS") is LiveResponseType.TPS - assert LiveResponseType.parse("DeviceConnected") is LiveResponseType.DEVICE_CONNECTED - assert LiveResponseType.parse(1000) is LiveResponseType.PING - assert LiveResponseType.parse("Nonsense") is None - assert LiveResponseType.SHOCKER_PAUSED.is_rejection - assert not LiveResponseType.PING.is_rejection diff --git a/tests/test_generated.py b/tests/test_generated.py new file mode 100644 index 0000000..d960601 --- /dev/null +++ b/tests/test_generated.py @@ -0,0 +1,70 @@ +"""The generated package matches the committed OpenAPI document.""" + +import importlib +import importlib.util +import json +import pkgutil +import sys +from pathlib import Path + +import openshock.rest.api + +ROOT = Path(__file__).resolve().parent.parent +SPEC = json.loads((ROOT / "openapi" / "openapi.json").read_text(encoding="utf-8")) +METHODS = {"get", "put", "post", "delete", "patch", "head", "options", "trace"} + + +def operation_modules(): + for tag in pkgutil.iter_modules(openshock.rest.api.__path__): + package = importlib.import_module(f"openshock.rest.api.{tag.name}") + for module in pkgutil.iter_modules(package.__path__): + yield importlib.import_module(f"{package.__name__}.{module.name}") + + +def test_every_operation_has_a_module_with_sync_and_async_variants(): + operations = [op for item in SPEC["paths"].values() for method, op in item.items() if method in METHODS] + modules = list(operation_modules()) + assert len(modules) == len(operations) > 100 + for module in modules: + # Operations without a response body only get the *_detailed pair. + for variant in ("sync_detailed", "asyncio_detailed"): + assert callable(getattr(module, variant, None)), f"{module.__name__}.{variant}" + assert hasattr(module, "sync") == hasattr(module, "asyncio") + + +def test_every_schema_has_a_model(): + import openshock.rest.models as models + + assert len(models.__all__) >= len(SPEC["components"]["schemas"]) + + +def test_spec_preparation(): + spec = importlib.util.spec_from_file_location("generate", ROOT / "scripts" / "generate.py") + assert spec and spec.loader + generate = importlib.util.module_from_spec(spec) + sys.modules["generate"] = generate + spec.loader.exec_module(generate) + + document = { + "openapi": "3.2.0", + "paths": { + "/x": { + "parameters": [], + "post": { + "requestBody": { + "content": {"application/json": {"a": 1}, "text/json": {}, "application/*+json": {}} + }, + "responses": { + "200": {"content": {"application/json": {"b": 2}, "text/plain": {}}}, + "201": {"content": {"text/plain": {"c": 3}}}, + "204": {}, + }, + }, + } + }, + } + post = generate.prepare(document)["paths"]["/x"]["post"] + assert document["openapi"] == "3.1.0" + assert post["requestBody"]["content"] == {"application/json": {"a": 1}} + assert post["responses"]["200"]["content"] == {"application/json": {"b": 2}} + assert post["responses"]["201"]["content"] == {"text/plain": {"c": 3}} diff --git a/tests/test_live_control.py b/tests/test_live_control.py index eb1c797..87fdcaf 100644 --- a/tests/test_live_control.py +++ b/tests/test_live_control.py @@ -3,11 +3,12 @@ import asyncio from uuid import UUID -import httpx +import httpx2 import pytest -from openshock import AsyncOpenShockClient, ControlType, HubGateway, HubNotFound, OpenShockAuthError +from openshock import HubNotFound, OpenShockAuthError, OpenShockClient from openshock.realtime import ConnectionState, LiveControlClient, LiveResponseType, StepRetryPolicy +from openshock.rest.models import ControlType, LcgResponseV2 from .fakes import TOKEN, FakeLiveGateway, eventually @@ -191,45 +192,45 @@ async def resolver() -> str: async def test_gateway_lookup_through_the_rest_api(): gateway = {"host": "gw.example", "port": 8443, "pathPrefix": "/lcg/", "country": "DE"} - lookups: list[httpx.Request] = [] + lookups: list[httpx2.Request] = [] - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: lookups.append(request) - return httpx.Response(200, json=gateway) + return httpx2.Response(200, json=gateway) - client = AsyncOpenShockClient(api_token=TOKEN, transport=httpx.MockTransport(handler)) + client = OpenShockClient(TOKEN, httpx_args={"transport": httpx2.MockTransport(handler)}) live = LiveControlClient(HUB, client=client) resolved = await live._resolve_gateway() - assert isinstance(resolved, HubGateway) + assert isinstance(resolved, LcgResponseV2) assert lookups[0].url.path == f"/2/devices/{HUB}/lcg" assert live._url_for(resolved) == f"wss://gw.example:8443/lcg/1/ws/live/{HUB}" assert live._headers["OpenShockToken"] == TOKEN - await client.aclose() + await client.get_async_httpx_client().aclose() async def test_hub_offline_at_lookup_is_retried(): async with FakeLiveGateway() as server: answers = iter([404, 404, 200]) - def handler(request: httpx.Request) -> httpx.Response: + def handler(request: httpx2.Request) -> httpx2.Response: if next(answers) == 404: - return httpx.Response( + return httpx2.Response( 404, json={"type": "Device.NotOnline", "title": "Hub is not online", "status": 404} ) - return httpx.Response(200, json={"host": "unused", "port": 443, "pathPrefix": "", "country": "DE"}) + return httpx2.Response(200, json={"host": "unused", "port": 443, "pathPrefix": "", "country": "DE"}) - client = AsyncOpenShockClient(api_token=TOKEN, transport=httpx.MockTransport(handler)) + client = OpenShockClient(TOKEN, httpx_args={"transport": httpx2.MockTransport(handler)}) live = LiveControlClient(HUB, client=client, retry_policy=FAST) # Point the socket at the fake while keeping the real REST lookup in the loop. live._url_for = lambda gateway: f"{server.ws_url}/1/ws/live/{HUB}" # type: ignore[method-assign] async with live: await live.wait_connected(3) - await client.aclose() + await client.get_async_httpx_client().aclose() def test_argument_validation(): with pytest.raises(ValueError, match="not both"): - LiveControlClient(HUB, api_token="a", client=AsyncOpenShockClient(api_token="b")) + LiveControlClient(HUB, api_token="a", client=OpenShockClient("b")) with pytest.raises(ValueError, match="tps"): LiveControlClient(HUB, api_token="a", tps=50) with pytest.raises(ValueError): diff --git a/tests/test_models.py b/tests/test_models.py deleted file mode 100644 index 36ad8c9..0000000 --- a/tests/test_models.py +++ /dev/null @@ -1,247 +0,0 @@ -"""Tests for model parsing (from_dict / to_dict).""" - -from datetime import datetime -from uuid import UUID - -from openshock.models import ( - BackendInfo, - Control, - Device, - DeviceWithToken, - LcgNodeV2, - PauseReason, - Session, - ShareInviteShocker, - Shocker, - ShockerLimits, - ShockerLog, - ShockerPermissions, - Stats, - Token, - User, - UserShares, -) - - -class TestBackendInfo: - def test_from_any(self): - data = { - "version": "3.15.0", - "commit": "abc123", - "currentTime": "2024-06-01T12:00:00Z", - "frontendUrl": "https://openshock.app", - "shortLinkUrl": "https://os.link", - "turnstileSiteKey": "key123", - "isUserAuthenticated": True, - "oAuthProviders": ["discord"], - } - info = BackendInfo.from_any(data) - assert info.version == "3.15.0" - assert info.commit == "abc123" - assert info.is_user_authenticated is True - assert info.o_auth_providers == ["discord"] - assert isinstance(info.current_time, datetime) - - -class TestStats: - def test_from_any(self): - stats = Stats.from_any({"devicesOnline": 42}) - assert stats.devices_online == 42 - - -class TestUser: - def test_from_dict(self): - data = { - "id": "550e8400-e29b-41d4-a716-446655440000", - "name": "testuser", - "email": "test@example.com", - "image": "https://example.com/img.png", - "roles": ["Admin"], - "rank": "1", - } - user = User.from_dict(data) - assert user.name == "testuser" - assert isinstance(user.id, UUID) - assert user.roles == ["Admin"] - - -class TestToken: - def test_from_dict(self): - data = { - "id": "550e8400-e29b-41d4-a716-446655440000", - "name": "my-token", - "createdOn": "2024-01-01T00:00:00Z", - "validUntil": None, - "lastUsed": "2024-06-01T00:00:00Z", - "permissions": ["shockers.use"], - } - token = Token.from_dict(data) - assert token.name == "my-token" - assert token.valid_until is None - assert isinstance(token.last_used, datetime) - - -class TestDevice: - def test_from_dict(self): - data = { - "id": "550e8400-e29b-41d4-a716-446655440000", - "name": "My Hub", - "createdOn": "2024-01-01T00:00:00Z", - } - device = Device.from_dict(data) - assert device.name == "My Hub" - assert isinstance(device.id, UUID) - - def test_with_token(self): - data = { - "id": "550e8400-e29b-41d4-a716-446655440000", - "name": "New Hub", - "createdOn": "2024-01-01T00:00:00Z", - "token": "secret-token-123", - } - dt = DeviceWithToken.from_dict(data) - assert dt.token == "secret-token-123" - - -class TestShocker: - def test_from_dict(self): - data = { - "id": "550e8400-e29b-41d4-a716-446655440000", - "name": "Test Shocker", - "rfId": 12345, - "model": "CaiXianlin", - "createdOn": "2024-01-01T00:00:00Z", - "isPaused": True, - } - shocker = Shocker.from_dict(data) - assert shocker.name == "Test Shocker" - assert shocker.rf_id == 12345 - assert shocker.is_paused is True - - -class TestShockerPermissions: - def test_round_trip(self): - perms = ShockerPermissions(vibrate=True, sound=True, shock=False, live=False) - d = perms.to_dict() - assert d == {"vibrate": True, "sound": True, "shock": False, "live": False} - restored = ShockerPermissions.from_dict(d) - assert restored == perms - - -class TestShockerLimits: - def test_round_trip(self): - limits = ShockerLimits(intensity=80, duration=5000) - d = limits.to_dict() - restored = ShockerLimits.from_dict(d) - assert restored == limits - - -class TestControl: - def test_to_dict(self): - ctrl = Control( - id="550e8400-e29b-41d4-a716-446655440000", - type="Vibrate", - intensity=50, - duration=1000, - ) - d = ctrl.to_dict() - assert d["type"] == "Vibrate" - assert d["intensity"] == 50 - assert d["exclusive"] is False - - -class TestShockerLog: - def test_from_dict(self): - data = { - "id": "550e8400-e29b-41d4-a716-446655440000", - "createdOn": "2024-06-01T12:00:00Z", - "type": "Shock", - "controlledBy": { - "id": "660e8400-e29b-41d4-a716-446655440000", - "name": "user1", - "image": "https://example.com/img.png", - "customName": None, - }, - "intensity": 75, - "duration": 2000, - } - log = ShockerLog.from_dict(data) - assert log.type == "Shock" - assert log.intensity == 75 - assert log.controlled_by.name == "user1" - - -class TestSession: - def test_from_dict(self): - data = { - "id": "550e8400-e29b-41d4-a716-446655440000", - "ip": "192.168.1.1", - "userAgent": "Mozilla/5.0", - "created": "2024-01-01T00:00:00Z", - "expires": "2024-02-01T00:00:00Z", - "lastUsed": "2024-01-15T00:00:00Z", - } - session = Session.from_dict(data) - assert session.ip == "192.168.1.1" - assert isinstance(session.expires, datetime) - - -class TestPauseReason: - def test_bitfield(self): - reason = PauseReason.SHOCKER | PauseReason.USER_SHARE - assert reason & PauseReason.SHOCKER - assert reason & PauseReason.USER_SHARE - assert not (reason & PauseReason.PUBLIC_SHARE) - - def test_from_int(self): - reason = PauseReason(6) # USER_SHARE | PUBLIC_SHARE - assert reason & PauseReason.USER_SHARE - assert reason & PauseReason.PUBLIC_SHARE - - -class TestLcgNodeV2: - def test_from_dict(self): - data = {"host": "gw.example.com", "port": 443, "path": "/ws", "country": "DE"} - node = LcgNodeV2.from_dict(data) - assert node.host == "gw.example.com" - assert node.port == 443 - - -class TestUserShares: - def test_from_dict(self): - data = { - "outgoing": [ - { - "id": "550e8400-e29b-41d4-a716-446655440000", - "name": "user2", - "image": "https://example.com/img.png", - "shares": [ - { - "id": "660e8400-e29b-41d4-a716-446655440000", - "name": "Shocker 1", - "createdOn": "2024-01-01T00:00:00Z", - "permissions": {"vibrate": True, "sound": True, "shock": False}, - "limits": {"intensity": 80, "duration": 5000}, - "paused": 0, - } - ], - } - ], - "incoming": [], - } - shares = UserShares.from_dict(data) - assert len(shares.outgoing) == 1 - assert len(shares.incoming) == 0 - assert shares.outgoing[0].shares[0].name == "Shocker 1" - - -class TestShareInviteShocker: - def test_round_trip(self): - s = ShareInviteShocker( - permissions=ShockerPermissions(vibrate=True, sound=False, shock=False), - limits=ShockerLimits(intensity=50, duration=3000), - id=UUID("550e8400-e29b-41d4-a716-446655440000"), - ) - d = s.to_dict() - assert "permissions" in d - assert d["id"] == "550e8400-e29b-41d4-a716-446655440000" diff --git a/tests/test_rest.py b/tests/test_rest.py deleted file mode 100644 index 929efed..0000000 --- a/tests/test_rest.py +++ /dev/null @@ -1,323 +0,0 @@ -"""REST client behaviour against a mocked transport: requests sent, responses parsed, errors mapped.""" - -import json -from uuid import UUID - -import httpx -import pytest - -from openshock import ( - AsyncOpenShockClient, - Control, - ControlType, - HubOffline, - OpenShockApiError, - OpenShockAuthError, - OpenShockClient, - OpenShockNotFound, - OpenShockRateLimited, - PermissionType, - ShockerModelType, - ShockerNoPermission, - ShockerNotFoundOrNoAccess, - ShockerPaused, - TokenPermissionMissing, -) - -HUB = "11111111-1111-1111-1111-111111111111" -SHOCKER = "22222222-2222-2222-2222-222222222222" -USER = "33333333-3333-3333-3333-333333333333" - -OWN_SHOCKERS = { - "message": "", - "data": [ - { - "id": HUB, - "name": "My Hub", - "createdOn": "2024-06-01T12:00:00.1234567Z", - "shockers": [ - { - "id": SHOCKER, - "rfId": 1234, - "model": "CaiXianlin", - "name": "Leg", - "isPaused": False, - "createdOn": "2024-06-01T12:00:00Z", - "permissions": {"vibrate": True, "sound": True, "shock": False, "live": True}, - "limits": {"intensity": 50, "duration": None}, - } - ], - } - ], -} - - -def problem(type_: str, status: int, **extra): - body = {"type": type_, "title": "Nope", "status": status, "requestId": "req-1", **extra} - return httpx.Response(status, json=body, headers={"Content-Type": "application/problem+json"}) - - -class Recorder: - """Mock transport handler that records requests and answers from a route table.""" - - def __init__(self, routes): - self.routes = routes - self.requests: list[httpx.Request] = [] - - def __call__(self, request: httpx.Request) -> httpx.Response: - self.requests.append(request) - response = self.routes[(request.method, request.url.path)] - return response(request) if callable(response) else response - - @property - def last(self) -> httpx.Request: - return self.requests[-1] - - def last_json(self): - return json.loads(self.last.content) - - -def sync_client(routes, **kwargs): - recorder = Recorder(routes) - return OpenShockClient(api_token="tok", transport=httpx.MockTransport(recorder), **kwargs), recorder - - -def async_client(routes, **kwargs): - recorder = Recorder(routes) - return AsyncOpenShockClient(api_token="tok", transport=httpx.MockTransport(recorder), **kwargs), recorder - - -class TestRequests: - def test_auth_and_user_agent_headers(self): - client, rec = sync_client( - {("GET", "/1/shockers/own"): httpx.Response(200, json=OWN_SHOCKERS)}, - app_name="MyApp", - app_version="1.2.3", - ) - client.shockers.list_own() - assert rec.last.headers["OpenShockToken"] == "tok" - ua = rec.last.headers["User-Agent"] - assert ua.startswith("OpenShock.SDK.Python/") - assert "MyApp 1.2.3" in ua - assert "httpx" in ua - - def test_list_own_is_typed(self): - client, _ = sync_client({("GET", "/1/shockers/own"): httpx.Response(200, json=OWN_SHOCKERS)}) - hubs = client.shockers.list_own() - assert len(hubs) == 1 - assert hubs[0].id == UUID(HUB) - assert hubs[0].created_on.microsecond == 123456 - shocker = hubs[0].shockers[0] - assert shocker.id == UUID(SHOCKER) - assert shocker.model is ShockerModelType.CAIXIANLIN - assert shocker.permissions is not None and shocker.permissions.live - assert shocker.limits is not None and shocker.limits.intensity == 50 - - def test_list_shared_is_typed(self): - payload = { - "data": [ - { - "id": USER, - "name": "Owner", - "image": "https://img", - "devices": [ - { - "id": HUB, - "name": "Their Hub", - "shockers": [ - { - "id": SHOCKER, - "name": "Arm", - "isPaused": True, - "permissions": {"vibrate": True, "sound": False, "shock": False}, - "limits": {"intensity": None, "duration": 5000}, - } - ], - } - ], - } - ] - } - client, _ = sync_client({("GET", "/1/shockers/shared"): httpx.Response(200, json=payload)}) - owners = client.shockers.list_shared() - shocker = owners[0].devices[0].shockers[0] - assert owners[0].name == "Owner" - assert shocker.is_paused - assert shocker.limits.duration == 5000 - - def test_control_body(self): - client, rec = sync_client({("POST", "/2/shockers/control"): httpx.Response(200, json={"message": "ok"})}) - result = client.shockers.control( - [ - Control(id=SHOCKER, type=ControlType.VIBRATE, intensity=25, duration=1000), - Control(id=SHOCKER, type="shock", intensity=5, duration=300, exclusive=True), - ], - custom_name="Bot", - ) - assert result is None - assert rec.last_json() == { - "shocks": [ - {"id": SHOCKER, "type": "Vibrate", "intensity": 25, "duration": 1000, "exclusive": False}, - {"id": SHOCKER, "type": "Shock", "intensity": 5, "duration": 300, "exclusive": True}, - ], - "customName": "Bot", - } - - def test_control_accepts_single_control_and_rejects_empty(self): - client, rec = sync_client({("POST", "/2/shockers/control"): httpx.Response(200, json={})}) - client.shockers.control(Control(id=SHOCKER, type="Sound", intensity=1, duration=300)) - assert len(rec.last_json()["shocks"]) == 1 - with pytest.raises(ValueError): - client.shockers.control([]) - - def test_pause_returns_state(self): - client, rec = sync_client( - {("POST", f"/1/shockers/{SHOCKER}/pause"): httpx.Response(200, json={"message": "", "data": True})} - ) - assert client.shockers.pause(SHOCKER, True) is True - assert rec.last_json() == {"pause": True} - - def test_gateway_v2(self): - client, _ = sync_client( - { - ("GET", f"/2/devices/{HUB}/lcg"): httpx.Response( - 200, json={"host": "de1-gateway.openshock.app", "port": 443, "pathPrefix": "", "country": "DE"} - ) - } - ) - gateway = client.devices.gateway(HUB) - assert gateway.ws_url == "wss://de1-gateway.openshock.app" - assert gateway.country == "DE" - - def test_create_device_returns_uuid_from_plain_text(self): - client, rec = sync_client({("POST", "/2/devices"): httpx.Response(201, text=HUB)}) - assert client.devices.create("New hub") == UUID(HUB) - assert rec.last_json() == {"name": "New hub"} - - def test_create_device_returns_uuid_from_json_string(self): - client, _ = sync_client({("POST", "/2/devices"): httpx.Response(201, json=HUB)}) - assert client.devices.create("New hub") == UUID(HUB) - - def test_get_device_token_optional(self): - data = {"id": HUB, "name": "Hub", "createdOn": "2024-06-01T12:00:00Z", "token": None} - client, _ = sync_client({("GET", f"/1/devices/{HUB}"): httpx.Response(200, json={"data": data})}) - assert client.devices.get(HUB).token is None - - def test_pair_code_is_string(self): - client, _ = sync_client({("GET", f"/1/devices/{HUB}/pair"): httpx.Response(200, json={"data": "123456"})}) - assert client.devices.pair_code(HUB) == "123456" - - def test_create_token(self): - created = { - "id": USER, - "name": "bot", - "token": "secret", - "createdAt": "2024-06-01T12:00:00Z", - "validUntil": None, - "lastUsed": "2024-06-01T12:00:00Z", - "permissions": ["shockers.use", "something.new"], - } - client, rec = sync_client({("POST", "/1/tokens"): httpx.Response(200, json=created)}) - token = client.account.create_token("bot", [PermissionType.SHOCKERS_USE, "shockers.pause"]) - assert token.token == "secret" - assert token.permissions[0] is PermissionType.SHOCKERS_USE - assert token.permissions[1] == "something.new" and not token.permissions[1].is_known - assert rec.last_json() == {"name": "bot", "permissions": ["shockers.use", "shockers.pause"]} - - def test_empty_body_is_ok(self): - client, _ = sync_client({("DELETE", f"/1/shockers/{SHOCKER}"): httpx.Response(200)}) - assert client.shockers.delete(SHOCKER) is None - - -class TestErrors: - @pytest.mark.parametrize( - ("type_", "status", "expected"), - [ - ("Shocker.Control.NotFound", 404, ShockerNotFoundOrNoAccess), - ("Shocker.Control.Paused", 412, ShockerPaused), - ("Shocker.Control.NoPermission", 403, ShockerNoPermission), - ], - ) - def test_control_problems(self, type_, status, expected): - client, _ = sync_client({("POST", "/2/shockers/control"): problem(type_, status, shockerId=SHOCKER)}) - with pytest.raises(expected) as info: - client.shockers.control([Control(id=SHOCKER, type="Shock", intensity=1, duration=300)]) - err = info.value - assert err.shocker_id == UUID(SHOCKER) - assert err.status_code == status - assert err.problem_type == type_ - assert err.problem is not None and err.problem.request_id == "req-1" - assert isinstance(err, OpenShockApiError) - - def test_specific_errors_keep_their_generic_base(self): - assert issubclass(ShockerNotFoundOrNoAccess, OpenShockNotFound) - assert issubclass(ShockerNoPermission, OpenShockAuthError) - assert issubclass(HubOffline, OpenShockNotFound) - - def test_hub_offline(self): - client, _ = sync_client({("GET", f"/2/devices/{HUB}/lcg"): problem("Device.NotOnline", 404)}) - with pytest.raises(HubOffline): - client.devices.gateway(HUB) - - def test_token_permission_missing(self): - client, _ = sync_client( - { - ("GET", "/1/devices"): problem( - "Authorization.Token.PermissionMissing", - 403, - requiredPermission="devices.edit", - grantedPermissions=["shockers.use"], - ) - } - ) - with pytest.raises(TokenPermissionMissing) as info: - client.devices.list() - assert info.value.required_permission == "devices.edit" - assert info.value.granted_permissions == ["shockers.use"] - - def test_status_fallbacks(self): - client, _ = sync_client( - { - ("GET", "/1/users/self"): httpx.Response(401, text=""), - ("GET", "/1/devices"): httpx.Response(404, text="gone"), - ("GET", "/1/tokens"): httpx.Response(429, text="slow down", headers={"Retry-After": "7"}), - ("GET", "/1"): httpx.Response(500, text="boom"), - } - ) - with pytest.raises(OpenShockAuthError): - client.account.user_self() - with pytest.raises(OpenShockNotFound): - client.devices.list() - with pytest.raises(OpenShockRateLimited) as info: - client.account.list_tokens() - assert info.value.retry_after == 7 - with pytest.raises(OpenShockApiError) as generic: - client.meta.backend_info() - assert generic.value.status_code == 500 - assert "boom" in str(generic.value) - - -class TestAsyncClient: - async def test_async_matches_sync(self): - client, rec = async_client({("GET", "/1/shockers/own"): httpx.Response(200, json=OWN_SHOCKERS)}) - async with client: - hubs = await client.shockers.list_own() - assert hubs[0].shockers[0].name == "Leg" - assert rec.last.headers["OpenShockToken"] == "tok" - - async def test_async_errors(self): - client, _ = async_client( - {("POST", "/2/shockers/control"): problem("Shocker.Control.Paused", 412, shockerId=SHOCKER)} - ) - async with client: - with pytest.raises(ShockerPaused): - await client.shockers.control([Control(id=SHOCKER, type="Shock", intensity=1, duration=300)]) - - def test_sync_and_async_expose_the_same_api(self): - sync, _ = sync_client({}) - asyn, _ = async_client({}) - for resource in ("meta", "account", "devices", "shockers", "shares", "sessions", "user_shares"): - sync_methods = {m for m in dir(getattr(sync, resource)) if not m.startswith("_")} - async_methods = {m for m in dir(getattr(asyn, resource)) if not m.startswith("_")} - assert sync_methods == async_methods, resource - sync.close() diff --git a/tests/test_user_hub.py b/tests/test_user_hub.py index b26ca2e..d54250d 100644 --- a/tests/test_user_hub.py +++ b/tests/test_user_hub.py @@ -5,8 +5,9 @@ import pytest -from openshock import Control, ControlType, HubInvocationError, OpenShockAuthError, OpenShockConnectionError +from openshock import HubInvocationError, OpenShockAuthError, OpenShockConnectionError from openshock.realtime import ConnectionState, HubUpdateType, OtaUpdateProgressTask, StepRetryPolicy, UserHubClient +from openshock.rest.models import Control, ControlType from .fakes import TOKEN, FakeSignalRHub, eventually @@ -114,7 +115,7 @@ async def test_control_sends_integers_and_waits_for_completion(): async with FakeSignalRHub() as server: async with make(server) as hub: await hub.control( - [Control(id=SHOCKER, type=ControlType.SHOCK, intensity=10, duration=300, exclusive=True)], + [Control(id=UUID(SHOCKER), type_=ControlType.SHOCK, intensity=10, duration=300, exclusive=True)], custom_name="Bot", ) await hub.reboot(HUB) @@ -173,7 +174,7 @@ async def test_reconnects_after_connection_loss(): await eventually(lambda: hub.connection_id == "conn-2") assert hub.state is ConnectionState.CONNECTED # The new connection is fully usable. - await hub.control(Control(id=SHOCKER, type="Vibrate", intensity=1, duration=300)) + await hub.control(Control(id=UUID(SHOCKER), type_=ControlType.VIBRATE, intensity=1, duration=300)) assert events == ["connected", "reconnecting", "reconnected", "closed:None"] From 3781f062e93407e6e8d32379e661d4938d5978cd Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 15:25:58 +0100 Subject: [PATCH 4/9] fix: address review findings in realtime lifecycle, errors and examples - refuse concurrent start(), let stop() abort a connection attempt - bind each event dispatcher to its own queue; bound dispatcher shutdown - honour allowReconnect for a close sent with the SignalR handshake - reject non-finite hold_for in live control - redact credentials in URLs put into exception messages - tolerate a malformed problem status; ASCII-only User-Agent fields - pin example requirements; make pure-Python install skip pip's cache - replace fixed sleeps in live control tests with observed ticks --- README.md | 7 +- examples/async_control/requirements.txt | 2 +- examples/live_control/requirements.txt | 2 +- examples/realtime_events/requirements.txt | 2 +- examples/rest_quickstart/requirements.txt | 2 +- openshock/_core.py | 3 +- openshock/exceptions.py | 25 ++++- openshock/realtime/_transport.py | 117 +++++++++++++++------- openshock/realtime/live_control.py | 5 + tests/fakes.py | 11 ++ tests/test_client.py | 43 +++++++- tests/test_live_control.py | 42 ++++++-- tests/test_user_hub.py | 96 ++++++++++++++++++ 13 files changed, 304 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index 24f15ba..35863ce 100644 --- a/README.md +++ b/README.md @@ -26,16 +26,19 @@ include an optional C accelerator. To install without any compiled code, build i source with the extension switched off (no compiler needed): ```bash -BUILD_EXTENSION=no pip install --no-binary websockets "openshock[realtime]" +BUILD_EXTENSION=no pip install --no-cache-dir --no-binary websockets "openshock[realtime]" ``` On Windows PowerShell: ```powershell $env:BUILD_EXTENSION = "no" -pip install --no-binary websockets "openshock[realtime]" +pip install --no-cache-dir --no-binary websockets "openshock[realtime]" ``` +`--no-cache-dir` keeps pip from reusing a compiled wheel it built or downloaded earlier. If +`websockets` is already installed, add `--force-reinstall` so it is actually rebuilt. + ## Quick start ```python diff --git a/examples/async_control/requirements.txt b/examples/async_control/requirements.txt index 3512a09..444664f 100644 --- a/examples/async_control/requirements.txt +++ b/examples/async_control/requirements.txt @@ -1 +1 @@ -openshock +openshock>=0.2.0b1 diff --git a/examples/live_control/requirements.txt b/examples/live_control/requirements.txt index 8fa2d32..db9ee67 100644 --- a/examples/live_control/requirements.txt +++ b/examples/live_control/requirements.txt @@ -1 +1 @@ -openshock[realtime] +openshock[realtime]>=0.2.0b1 diff --git a/examples/realtime_events/requirements.txt b/examples/realtime_events/requirements.txt index 8fa2d32..db9ee67 100644 --- a/examples/realtime_events/requirements.txt +++ b/examples/realtime_events/requirements.txt @@ -1 +1 @@ -openshock[realtime] +openshock[realtime]>=0.2.0b1 diff --git a/examples/rest_quickstart/requirements.txt b/examples/rest_quickstart/requirements.txt index 3512a09..444664f 100644 --- a/examples/rest_quickstart/requirements.txt +++ b/examples/rest_quickstart/requirements.txt @@ -1 +1 @@ -openshock +openshock>=0.2.0b1 diff --git a/openshock/_core.py b/openshock/_core.py index 168edc7..94f7a1a 100644 --- a/openshock/_core.py +++ b/openshock/_core.py @@ -11,7 +11,8 @@ DEFAULT_BASE_URL = "https://api.openshock.app" DEFAULT_TIMEOUT = 10.0 -_UA_UNSAFE = re.compile(r"[^\w.\-+ ]") +# ASCII only: HTTP header values cannot carry anything else. +_UA_UNSAFE = re.compile(r"[^\w.\-+ ]", re.ASCII) def _os_name() -> str: diff --git a/openshock/exceptions.py b/openshock/exceptions.py index 9ebdfb4..cde1426 100644 --- a/openshock/exceptions.py +++ b/openshock/exceptions.py @@ -2,6 +2,7 @@ import contextlib import json +import re from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, TypeVar, overload from uuid import UUID @@ -13,6 +14,25 @@ _T = TypeVar("_T") +def _status(value: Any, fallback: int | None) -> int: + if isinstance(value, bool): + value = None + try: + return int(value) if value else int(fallback or 0) + except (TypeError, ValueError): + return int(fallback or 0) + + +# Routes that carry a credential in the path. Exception messages end up in logs, so the +# credential is replaced before the URL is put into one. +_SECRET_PATHS = re.compile(r"(/device/pair/|/shares/code/|/password-reset/[^/?#]+/)[^/?#]+") + + +def redact_url(url: str) -> str: + """Remove credentials (pair codes, reset secrets, share codes, the query string) from a URL.""" + return _SECRET_PATHS.sub(r"\1***", url.split("?", 1)[0]) + + @dataclass(frozen=True) class Problem: """An RFC 7807 problem document as returned by the OpenShock backend.""" @@ -27,11 +47,12 @@ class Problem: @classmethod def from_dict(cls, data: dict[str, Any], *, status: int | None = None) -> Problem: + """Build from a decoded body. A missing or malformed ``status`` falls back to the HTTP status.""" known = {"type", "title", "status", "detail", "requestid", "traceid"} return cls( type=str(data.get("type") or ""), title=str(data.get("title") or ""), - status=int(data.get("status") or status or 0), + status=_status(data.get("status"), status), detail=data.get("detail"), request_id=data.get("requestId") or data.get("traceId"), extensions={k: v for k, v in data.items() if k.lower() not in known}, @@ -184,7 +205,7 @@ def error_from_response( text = body_json.get("message") or body_json.get("detail") or body_json.get("title") text = text or body_text or f"HTTP {status_code}" - where = f" calling {method} {url}" if method or url else "" + where = f" calling {method} {redact_url(url)}".rstrip() if method or url else "" message = f"{status_code}{where}: {text}" kwargs: dict[str, Any] = {"status_code": status_code, "problem": problem, "body": body_text} diff --git a/openshock/realtime/_transport.py b/openshock/realtime/_transport.py index 035f84c..c126c7d 100644 --- a/openshock/realtime/_transport.py +++ b/openshock/realtime/_transport.py @@ -120,6 +120,8 @@ class WebSocketSession: #: Keep retrying when the very first connection attempt fails with a non-fatal error. _retry_initial = False _name = "websocket" + #: How long stop() lets event handlers finish before cancelling them, in seconds. + _drain_timeout = 5.0 def __init__(self, *, retry_policy: RetryPolicy, logger: logging.Logger | None = None) -> None: self._retry_policy = retry_policy @@ -140,6 +142,9 @@ def __init__(self, *, retry_policy: RetryPolicy, logger: logging.Logger | None = self._closed.set() self._close_error: BaseException | None = None self._finalized = True + self._starting = False + self._abort_start = False + self._startup: asyncio.Future[ClientConnection] | None = None # --- public API -------------------------------------------------------- @@ -158,41 +163,74 @@ async def start(self) -> None: Raises :class:`~openshock.exceptions.OpenShockAuthError` (or another :class:`~openshock.exceptions.OpenShockError`) if the connection is refused. """ - if self._runner is not None and not self._runner.done(): + if self._starting or (self._runner is not None and not self._runner.done()): raise RuntimeError(f"{type(self).__name__} is already started") - self._queue = asyncio.Queue() - self._closed.clear() - self._close_error = None - self._state = ConnectionState.CONNECTING - - ws: ClientConnection | None = None - error: BaseException | None = None + # Claim the session before the first await, so a concurrent start() is refused and + # stop() knows there is a connection attempt to abort. + self._starting = True + self._abort_start = False try: - ws = await self._open() - except asyncio.CancelledError: - self._state = ConnectionState.DISCONNECTED - self._closed.set() - raise - except Exception as exc: - if not self._retry_initial or self._is_fatal(exc): - self._state = ConnectionState.DISCONNECTED - self._closed.set() - if isinstance(exc, OpenShockApiError | OpenShockConnectionError): - raise - raise OpenShockConnectionError(f"Could not connect: {exc}") from exc - self._log.info("Initial connection failed (%s), retrying in the background", exc) - error = exc + self._closed.clear() + self._close_error = None + self._state = ConnectionState.CONNECTING - self._finalized = False - if ws is not None: - # Be usable as soon as start() returns, before the background task first runs. - self._mark_connected(ws) - self._dispatcher = asyncio.create_task(self._dispatch_loop(), name=f"openshock-{self._name}-dispatch") - self._runner = asyncio.create_task(self._run(ws, error), name=f"openshock-{self._name}") + ws: ClientConnection | None = None + error: BaseException | None = None + self._startup = asyncio.ensure_future(self._open()) + try: + ws = await self._startup + except asyncio.CancelledError: + self._startup.cancel() + self._abandon_start() + if self._abort_start: + raise OpenShockConnectionError("stop() was called while connecting") from None + raise + except Exception as exc: + if self._abort_start or not self._retry_initial or self._is_fatal(exc): + self._abandon_start() + if isinstance(exc, OpenShockApiError | OpenShockConnectionError): + raise + raise OpenShockConnectionError(f"Could not connect: {exc}") from exc + self._log.info("Initial connection failed (%s), retrying in the background", exc) + error = exc + + if self._abort_start: + # stop() ran after the connection attempt finished but before we resumed. + if ws is not None: + await self._close_ws(ws) + self._abandon_start() + raise OpenShockConnectionError("stop() was called while connecting") + + # No awaits from here on: the session becomes visible to stop() in one step. + # Each dispatcher owns its queue, so one left over from an earlier session + # (still inside a slow handler) can never consume this session's events. + self._queue = asyncio.Queue() + self._finalized = False + if ws is not None: + # Be usable as soon as start() returns, before the background task first runs. + self._mark_connected(ws) + self._dispatcher = asyncio.create_task( + self._dispatch_loop(self._queue), name=f"openshock-{self._name}-dispatch" + ) + self._runner = asyncio.create_task(self._run(ws, error), name=f"openshock-{self._name}") + finally: + self._starting = False + self._startup = None + + def _abandon_start(self) -> None: + self._state = ConnectionState.DISCONNECTED + self._closed.set() async def stop(self) -> None: """Close the connection and stop reconnecting. Safe to call more than once.""" + if self._starting: + # start() is still connecting: abort it. It raises in the task that called it. + self._abort_start = True + startup = self._startup + if startup is not None and not startup.done(): + startup.cancel() + await asyncio.gather(startup, return_exceptions=True) runner, self._runner = self._runner, None if runner is not None: runner.cancel() @@ -201,6 +239,12 @@ async def stop(self) -> None: await self._finalize(None) dispatcher, self._dispatcher = self._dispatcher, None if dispatcher is not None and dispatcher is not asyncio.current_task(): + # Let queued events (including on_closed) be delivered, but do not let a handler + # that never returns keep stop() from returning. + await asyncio.wait({dispatcher}, timeout=self._drain_timeout) + if not dispatcher.done(): + self._log.warning("An event handler did not finish within %ss, cancelling it", self._drain_timeout) + dispatcher.cancel() await asyncio.gather(dispatcher, return_exceptions=True) async def wait_connected(self, timeout: float | None = None) -> None: @@ -302,9 +346,9 @@ def _emit(self, event: Callable[..., Awaitable[None]], *args: Any) -> None: # --- internals --------------------------------------------------------- - async def _dispatch_loop(self) -> None: + async def _dispatch_loop(self, queue: asyncio.Queue[Any]) -> None: while True: - item = await self._queue.get() + item = await queue.get() if item is _SENTINEL: return emit, args = item @@ -332,10 +376,15 @@ async def _run(self, ws: ClientConnection | None, error: BaseException | None) - self._mark_connected(ws) try: - await self._after_open() - self._emit(self.on_reconnected.emit if ever_connected else self.on_connected.emit) - ever_connected = True - error = await self._pump(ws) + try: + await self._after_open() + self._emit(self.on_reconnected.emit if ever_connected else self.on_connected.emit) + ever_connected = True + error = await self._pump(ws) + except _ServerClose as exc: + # A close that arrived together with the handshake gets the same + # reconnect decision as one received later. + error = exc finally: self._ws = None self._connected.clear() diff --git a/openshock/realtime/live_control.py b/openshock/realtime/live_control.py index a52242b..8c9292f 100644 --- a/openshock/realtime/live_control.py +++ b/openshock/realtime/live_control.py @@ -3,6 +3,7 @@ import asyncio import json import logging +import math from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass from typing import Any @@ -151,6 +152,7 @@ def __init__( self._hub_connected = False self._states: dict[UUID, _ShockerState] = {} self._ticker: asyncio.Task[None] | None = None + self._ticks = 0 # completed tick waits, for diagnostics and tests #: ``()`` — the hub is connected to the gateway and accepts frames. self.on_hub_connected: Event[[]] = Event("on_hub_connected") @@ -212,6 +214,8 @@ def intake_frame( if not 0 <= intensity <= 100: raise ValueError("intensity must be between 0 and 100") control_type = _control_type(type) + if hold_for is not None and not (math.isfinite(hold_for) and hold_for >= 0): + raise ValueError("hold_for must be a finite, non-negative number of seconds") window = hold_for if hold_for is not None else FRAME_HOLD_TICKS / (self._tps or DEFAULT_TPS) self._states[UUID(str(shocker))] = _ShockerState( type=control_type, @@ -343,6 +347,7 @@ async def _tick_loop(self) -> None: next_tick = max(next_tick + 1.0 / tps, loop.time()) await asyncio.sleep(max(0.0, next_tick - loop.time())) + self._ticks += 1 now = loop.time() frames = [] diff --git a/tests/fakes.py b/tests/fakes.py index 79d74c3..c366f30 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -66,6 +66,10 @@ def __init__(self) -> None: self.pings = 0 self.fail_targets: set[str] = set() self.handshake_error: str | None = None + #: Close messages to append to the handshake frame of the next connections. + self.close_with_handshake: list[bool] = [] + #: Seconds to wait before answering the handshake. + self.handshake_delay = 0.0 @property def http_url(self) -> str: @@ -88,6 +92,13 @@ async def _handler(self, connection: ServerConnection) -> None: if self.handshake_error: await connection.send(json.dumps({"error": self.handshake_error}) + RS) return + if self.handshake_delay: + await asyncio.sleep(self.handshake_delay) + if self.close_with_handshake: + allow = self.close_with_handshake.pop(0) + close = json.dumps({"type": 7, "error": "Draining", "allowReconnect": allow}) + await connection.send("{}" + RS + close + RS) + return index = len(self.requests) # The real server may put the first invocation in the same frame as the handshake response. welcome = json.dumps({"type": 1, "target": "Welcome", "arguments": [f"conn-{index}"]}) diff --git a/tests/test_client.py b/tests/test_client.py index cd15387..888765f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -20,7 +20,9 @@ TokenPermissionMissing, unwrap, ) -from openshock.rest.api.hub_endpoints import device_get_self +from openshock._core import build_user_agent +from openshock.exceptions import redact_url +from openshock.rest.api.hub_endpoints import device_get_self, device_pair from openshock.rest.api.hub_management import devices_get_live_control_gateway_info_v2, devices_list_devices from openshock.rest.api.shockers import shocker_list_shockers, shocker_send_control from openshock.rest.client import AuthenticatedClient @@ -239,3 +241,42 @@ def test_raise_on_error_can_be_turned_off(self): assert info.value.shocker_id == UUID(SHOCKER) with pytest.raises(ShockerPaused): unwrap(shocker_send_control.sync_detailed(client=client, body=CONTROL)) + + +class TestErrorDetails: + def test_malformed_problem_status_falls_back_to_the_http_status(self): + body = {"title": "Unavailable", "status": "unknown"} + client, _ = client_for(httpx2.Response(503, json=body)) + with client, pytest.raises(OpenShockApiError) as info: + shocker_list_shockers.sync(client=client) + assert info.value.status_code == 503 + assert info.value.problem is not None and info.value.problem.status == 503 + + def test_credentials_in_the_path_are_not_put_into_messages(self): + client, seen = client_for(httpx2.Response(401, text=""), cls=OpenShockHubClient) + with client, pytest.raises(OpenShockAuthError) as info: + device_pair.sync(client=client, pair_code="123456") + assert seen[0].url.path == "/1/device/pair/123456" + assert "123456" not in str(info.value) + assert "GET https://api.openshock.app/1/device/pair/***" in str(info.value) + + @pytest.mark.parametrize( + ("url", "expected"), + [ + ( + "https://x/1/account/password-reset/abc/s3cret/complete", + "https://x/1/account/password-reset/abc/***/complete", + ), + ("https://x/1/shares/code/abc", "https://x/1/shares/code/***"), + ("https://x/1/shockers/own?token=abc", "https://x/1/shockers/own"), + ("https://x/2/shockers/control", "https://x/2/shockers/control"), + ], + ) + def test_redact_url(self, url, expected): + assert redact_url(url) == expected + + def test_user_agent_is_ascii(self): + client = OpenShockClient("tok", app_name="Café Ünïcode", app_version="1.0β") + agent = client.get_httpx_client().headers["User-Agent"] + assert agent.isascii() and "Caf ncode 1.0" in agent + assert "MyApp 1.2" in build_user_agent(app_name="MyApp", app_version="1.2") diff --git a/tests/test_live_control.py b/tests/test_live_control.py index 87fdcaf..0aa7241 100644 --- a/tests/test_live_control.py +++ b/tests/test_live_control.py @@ -47,23 +47,32 @@ async def test_connects_and_learns_tps(): assert live.tps == 0 and not live.hub_connected +async def ticks(live: LiveControlClient, count: int) -> None: + """Wait for ``count`` more ticks to complete, plus time for what they sent to arrive.""" + target = live._ticks + count + await eventually(lambda: live._ticks >= target) + await asyncio.sleep(0.05) + + async def test_frames_are_sent_each_tick_and_expire(): async with FakeLiveGateway(tps=10) as server, make(server) as live: await eventually(lambda: live.tps == 10) - live.intake_frame(SHOCKER, ControlType.VIBRATE, 40, hold_for=0.35) - live.intake_frame(OTHER, "shock", 5, hold_for=0.35) - await asyncio.sleep(0.8) + live.intake_frame(SHOCKER, ControlType.VIBRATE, 40, hold_for=0.6) + live.intake_frame(OTHER, "shock", 5, hold_for=0.6) + # Repeated on every tick while held... + await eventually(lambda: len(server.frames()) >= 2) + # ...and dropped by the first tick after the hold window. + await eventually(lambda: not live._states) frames = server.frames() - # ~3 ticks fit in the hold window at 10 TPS; allow for scheduling jitter. - assert 2 <= len(frames) <= 5 assert frames[0] == [ {"shocker": SHOCKER, "intensity": 40, "type": "Vibrate"}, {"shocker": OTHER, "intensity": 5, "type": "Shock"}, ] # Nothing more is sent once the frames expired. - count = len(frames) - await asyncio.sleep(0.3) + await ticks(live, 2) + count = len(server.frames()) + await ticks(live, 3) assert len(server.frames()) == count @@ -76,9 +85,9 @@ async def test_latest_value_wins_and_release_stops(): assert server.frames()[0] == [{"shocker": SHOCKER, "intensity": 20, "type": "Vibrate"}] live.release(SHOCKER) - await asyncio.sleep(0.15) + await ticks(live, 2) count = len(server.frames()) - await asyncio.sleep(0.3) + await ticks(live, 3) assert len(server.frames()) == count @@ -250,3 +259,18 @@ async def test_intake_frame_validates(): live.intake_frame(SHOCKER, ControlType.SHOCK, 101) with pytest.raises(ValueError): live.intake_frame(SHOCKER, "Zap", 10) + + +@pytest.mark.parametrize("hold_for", [float("nan"), float("inf"), -1.0]) +async def test_hold_for_must_be_finite(hold_for): + live = LiveControlClient(HUB, api_token=TOKEN, gateway="ws://127.0.0.1:1") + with pytest.raises(ValueError, match="hold_for"): + live.intake_frame(SHOCKER, ControlType.VIBRATE, 10, hold_for=hold_for) + + +async def test_unknown_control_type_is_rejected_everywhere(): + live = LiveControlClient(HUB, api_token=TOKEN, gateway="ws://127.0.0.1:1") + with pytest.raises(ValueError, match="Zap"): + live.intake_frame(SHOCKER, "Zap", 10) + with pytest.raises(ValueError, match="Zap"): + await live.send_frame(SHOCKER, "Zap", 10) diff --git a/tests/test_user_hub.py b/tests/test_user_hub.py index d54250d..8577ac4 100644 --- a/tests/test_user_hub.py +++ b/tests/test_user_hub.py @@ -227,6 +227,102 @@ async def test_server_close_with_reconnect_reconnects(): await eventually(lambda: hub.connection_id == "conn-2") +async def test_close_in_the_handshake_frame_reconnects_when_allowed(): + async with FakeSignalRHub() as server: + server.close_with_handshake = [True] + async with make(server) as hub: + await eventually(lambda: hub.connection_id == "conn-2") + assert hub.is_connected + + +async def test_close_in_the_handshake_frame_ends_the_session_when_not_allowed(): + async with FakeSignalRHub() as server: + server.close_with_handshake = [False] + hub = make(server) + await hub.start() + with pytest.raises(OpenShockConnectionError, match="Draining"): + await asyncio.wait_for(hub.wait_closed(), 3) + await hub.stop() + + +async def test_concurrent_start_is_refused(): + async with FakeSignalRHub() as server: + server.handshake_delay = 0.2 + hub = make(server) + first = asyncio.create_task(hub.start()) + await eventually(lambda: hub.state is ConnectionState.CONNECTING) + with pytest.raises(RuntimeError, match="already started"): + await hub.start() + await first + assert len(server.requests) == 1 + await hub.stop() + + +async def test_stop_during_start_aborts_the_connection(): + async with FakeSignalRHub() as server: + server.handshake_delay = 0.5 + hub = make(server) + starting = asyncio.create_task(hub.start()) + await eventually(lambda: hub.state is ConnectionState.CONNECTING) + await hub.stop() + with pytest.raises(OpenShockConnectionError, match="stop"): + await starting + assert hub.state is ConnectionState.DISCONNECTED + await asyncio.sleep(0.6) + assert not hub.is_connected and not server.connections + # The client is reusable afterwards. + server.handshake_delay = 0 + async with hub: + assert hub.is_connected + + +async def test_stop_does_not_wait_forever_for_a_stuck_handler(): + async with FakeSignalRHub() as server: + hub = make(server) + hub._drain_timeout = 0.1 + entered = asyncio.Event() + + @hub.on_welcome + async def stuck(_connection_id: str) -> None: + entered.set() + await asyncio.Event().wait() + + await hub.start() + await asyncio.wait_for(entered.wait(), 3) + await asyncio.wait_for(hub.stop(), 2) + assert hub.state is ConnectionState.DISCONNECTED + + +async def test_restart_does_not_share_events_with_a_leftover_dispatcher(): + async with FakeSignalRHub() as server: + hub = make(server) + release = asyncio.Event() + welcomes: list[str] = [] + + @hub.on_welcome + async def slow_first(connection_id: str) -> None: + welcomes.append(connection_id) + if connection_id == "conn-1": + await release.wait() + + await hub.start() + await eventually(lambda: welcomes == ["conn-1"]) + old_dispatcher = hub._dispatcher + assert old_dispatcher is not None + # The session ends on its own while the first handler is still running. + await server.send_close("bye", allow_reconnect=False) + await eventually(lambda: hub.state is ConnectionState.DISCONNECTED) + + await hub.start() + await eventually(lambda: welcomes == ["conn-1", "conn-2"]) + release.set() + # The old dispatcher finishes with its own queue and exits instead of lingering. + await asyncio.wait_for(old_dispatcher, 3) + await server.push("DeviceUpdate", HUB, 0) + await hub.stop() + assert welcomes == ["conn-1", "conn-2"] + + async def test_handler_may_stop_the_client(): async with FakeSignalRHub() as server: hub = make(server) From 47d5d4d5d7873a5472eec75d7baf2a604341fcd9 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 15:35:44 +0100 Subject: [PATCH 5/9] feat!: leave admin and session-only endpoints out of the generated client The SDK authenticates with API tokens or a hub's device token. Operations tagged Admin and operations that only accept the browser session cookie are removed from the OpenAPI document before generation, together with the models only they used (134 -> 75 operations). --- README.md | 19 +- .../authenticated_account_change_email.py | 189 -------- .../authenticated_account_change_password.py | 170 ------- .../authenticated_account_change_username.py | 175 ------- .../authenticated_account_deactivate.py | 133 ------ .../authenticated_account_get_audit_log.py | 226 --------- ...ticated_account_list_o_auth_connections.py | 134 ------ ...icated_account_remove_o_auth_connection.py | 158 ------- openshock/rest/api/admin/__init__.py | 2 - .../admin_add_email_provider_blacklist.py | 102 ----- .../api/admin/admin_add_username_blacklist.py | 102 ----- openshock/rest/api/admin/admin_add_webhook.py | 167 ------- .../admin/admin_bulk_cancel_email_outbox.py | 177 ------- .../admin/admin_bulk_delete_email_outbox.py | 173 ------- .../admin/admin_bulk_requeue_email_outbox.py | 177 ------- .../api/admin/admin_cancel_email_outbox.py | 172 ------- .../rest/api/admin/admin_configuration_add.py | 174 ------- .../api/admin/admin_configuration_delete.py | 169 ------- .../api/admin/admin_configuration_list.py | 138 ------ .../api/admin/admin_configuration_update.py | 191 -------- .../admin/admin_create_automation_token.py | 161 ------- .../rest/api/admin/admin_deactivate_user.py | 127 ----- .../rest/api/admin/admin_delete_api_token.py | 103 ----- .../admin/admin_delete_automation_token.py | 168 ------- .../api/admin/admin_delete_email_outbox.py | 167 ------- openshock/rest/api/admin/admin_delete_user.py | 118 ----- .../api/admin/admin_get_admin_audit_log.py | 263 ----------- .../rest/api/admin/admin_get_email_outbox.py | 218 --------- .../api/admin/admin_get_email_outbox_stats.py | 133 ------ .../api/admin/admin_get_online_devices.py | 135 ------ .../api/admin/admin_get_online_gateways.py | 138 ------ .../rest/api/admin/admin_get_user_by_id.py | 167 ------- openshock/rest/api/admin/admin_get_users.py | 210 --------- .../api/admin/admin_list_automation_tokens.py | 134 ------ .../admin_list_email_provider_blacklist.py | 162 ------- .../admin/admin_list_username_blacklist.py | 162 ------- .../rest/api/admin/admin_list_webhooks.py | 138 ------ openshock/rest/api/admin/admin_modify_user.py | 121 ----- .../api/admin/admin_patch_automation_token.py | 184 -------- .../rest/api/admin/admin_reactivate_user.py | 118 ----- .../admin_remove_email_provider_blacklist.py | 155 ------- .../admin/admin_remove_username_blacklist.py | 155 ------- .../rest/api/admin/admin_remove_webhook.py | 163 ------- .../api/admin/admin_requeue_email_outbox.py | 172 ------- .../admin/admin_rotate_automation_token.py | 163 ------- .../rest/api/admin/admin_send_test_email.py | 191 -------- .../rest/api/admin/admin_set_user_email.py | 184 -------- .../rest/api/admin/admin_set_user_name.py | 192 -------- .../rest/api/admin/admin_set_user_password.py | 192 -------- .../api/api_tokens/tokens_create_token_v2.py | 161 ------- .../api/api_tokens/tokens_edit_token_v2.py | 182 -------- .../api_tokens/tokens_get_token_by_id_v2.py | 163 ------- .../api/api_tokens/tokens_list_tokens_v2.py | 132 ------ .../api/api_tokens/tokens_report_tokens.py | 104 ----- .../api/api_tokens/tokens_set_token_paused.py | 184 -------- .../devices_ota_get_ota_update_history.py | 165 ------- openshock/rest/api/sessions/__init__.py | 2 - .../api/sessions/sessions_delete_session.py | 157 ------- .../api/sessions/sessions_get_self_session.py | 127 ----- .../api/sessions/sessions_list_sessions.py | 130 ------ openshock/rest/api/shocker_shares/__init__.py | 2 - .../shares_delete_share_code.py | 163 ------- .../shocker_shares/shares_link_share_code.py | 172 ------- openshock/rest/models/__init__.py | 180 -------- .../add_email_provider_blacklist_dto.py | 62 --- .../rest/models/add_username_blacklist_dto.py | 72 --- openshock/rest/models/add_webhook_dto.py | 70 --- .../models/admin_online_device_response.py | 216 --------- .../models/admin_online_gateway_response.py | 146 ------ openshock/rest/models/admin_user_view.py | 324 ------------- .../rest/models/admin_user_view_api_token.py | 156 ------- .../models/admin_user_view_email_change.py | 105 ----- openshock/rest/models/admin_user_view_hub.py | 102 ----- .../models/admin_user_view_name_change.py | 79 ---- .../models/admin_user_view_password_reset.py | 97 ---- .../rest/models/admin_user_view_shocker.py | 80 ---- ...admin_user_view_user_activation_request.py | 71 --- .../admin_user_view_user_deactivation.py | 102 ----- .../rest/models/admin_user_view_user_ref.py | 71 --- openshock/rest/models/admin_users_view.py | 304 ------------ openshock/rest/models/audit_action.py | 26 -- .../rest/models/audit_log_entry_response.py | 432 ------------------ ...t_metadata_account_deactivated_metadata.py | 81 ---- ...metadata_account_deactivated_metadata_t.py | 9 - ...dit_metadata_api_token_created_metadata.py | 98 ---- ...t_metadata_api_token_created_metadata_t.py | 9 - ...dit_metadata_api_token_deleted_metadata.py | 90 ---- ...t_metadata_api_token_deleted_metadata_t.py | 9 - ...adata_automation_token_created_metadata.py | 120 ----- ...ata_automation_token_created_metadata_t.py | 9 - ...adata_automation_token_deleted_metadata.py | 99 ---- ...ata_automation_token_deleted_metadata_t.py | 9 - ...adata_automation_token_rotated_metadata.py | 90 ---- ...ata_automation_token_rotated_metadata_t.py | 9 - ...adata_automation_token_updated_metadata.py | 121 ----- ...ata_automation_token_updated_metadata_t.py | 9 - ...metadata_automation_token_used_metadata.py | 100 ---- ...tadata_automation_token_used_metadata_t.py | 9 - ...etadata_email_change_requested_metadata.py | 81 ---- ...adata_email_change_requested_metadata_t.py | 9 - .../audit_metadata_email_changed_metadata.py | 89 ---- ...audit_metadata_email_changed_metadata_t.py | 9 - .../models/audit_metadata_login_metadata.py | 82 ---- .../models/audit_metadata_login_metadata_t.py | 9 - ...udit_metadata_o_auth_connected_metadata.py | 81 ---- ...it_metadata_o_auth_connected_metadata_t.py | 9 - ...t_metadata_o_auth_disconnected_metadata.py | 81 ---- ...metadata_o_auth_disconnected_metadata_t.py | 9 - ...udit_metadata_username_changed_metadata.py | 89 ---- ...it_metadata_username_changed_metadata_t.py | 9 - openshock/rest/models/automation_token_dto.py | 197 -------- .../rest/models/automation_token_type.py | 11 - openshock/rest/models/change_email_request.py | 70 --- .../rest/models/change_password_request.py | 70 --- .../models/configuration_add_item_request.py | 91 ---- .../rest/models/configuration_item_dto.py | 106 ----- .../configuration_update_item_request.py | 110 ----- .../rest/models/configuration_value_type.py | 13 - .../models/create_automation_token_dto.py | 112 ----- .../rest/models/create_token_request_v2.py | 127 ----- .../models/created_automation_token_dto.py | 166 ------- .../rest/models/edit_token_request_v2.py | 95 ---- .../rest/models/email_outbox_bulk_request.py | 72 --- .../models/email_outbox_bulk_result_dto.py | 72 --- .../rest/models/email_outbox_message_dto.py | 226 --------- .../email_outbox_message_dto_payload.py | 46 -- .../rest/models/email_outbox_stats_dto.py | 103 ----- .../models/email_provider_blacklist_dto.py | 80 ---- openshock/rest/models/email_status.py | 13 - openshock/rest/models/email_type.py | 12 - ...f_array_of_admin_online_device_response.py | 84 ---- ...e_of_i_read_only_collection_of_ota_item.py | 84 ---- .../rest/models/login_session_response.py | 203 -------- openshock/rest/models/match_type_enum.py | 10 - .../rest/models/o_auth_connection_response.py | 93 ---- openshock/rest/models/ota_item.py | 103 ----- openshock/rest/models/ota_update_status.py | 13 - ...aged_result_of_audit_log_entry_response.py | 112 ----- .../models/paginated_of_admin_users_view.py | 100 ---- .../paginated_of_email_outbox_message_dto.py | 100 ---- .../rest/models/password_hashing_algorithm.py | 11 - .../rest/models/patch_automation_token_dto.py | 154 ------- .../rest/models/report_tokens_request.py | 70 --- openshock/rest/models/send_test_email_dto.py | 98 ---- .../rest/models/set_token_paused_request.py | 62 --- .../models/set_user_email_request_body.py | 62 --- .../rest/models/set_user_name_request_body.py | 62 --- .../models/set_user_password_request_body.py | 62 --- .../rest/models/token_created_response_v2.py | 171 ------- .../rest/models/token_paused_response.py | 62 --- .../rest/models/user_name_blacklist_dto.py | 90 ---- openshock/rest/models/user_patch_dto.py | 94 ---- openshock/rest/models/webhook_dto.py | 88 ---- scripts/generate.py | 54 +++ tests/test_generated.py | 76 ++- 155 files changed, 134 insertions(+), 17385 deletions(-) delete mode 100644 openshock/rest/api/account/authenticated_account_change_email.py delete mode 100644 openshock/rest/api/account/authenticated_account_change_password.py delete mode 100644 openshock/rest/api/account/authenticated_account_change_username.py delete mode 100644 openshock/rest/api/account/authenticated_account_deactivate.py delete mode 100644 openshock/rest/api/account/authenticated_account_get_audit_log.py delete mode 100644 openshock/rest/api/account/authenticated_account_list_o_auth_connections.py delete mode 100644 openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py delete mode 100644 openshock/rest/api/admin/__init__.py delete mode 100644 openshock/rest/api/admin/admin_add_email_provider_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_add_username_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_add_webhook.py delete mode 100644 openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_bulk_delete_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_cancel_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_configuration_add.py delete mode 100644 openshock/rest/api/admin/admin_configuration_delete.py delete mode 100644 openshock/rest/api/admin/admin_configuration_list.py delete mode 100644 openshock/rest/api/admin/admin_configuration_update.py delete mode 100644 openshock/rest/api/admin/admin_create_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_deactivate_user.py delete mode 100644 openshock/rest/api/admin/admin_delete_api_token.py delete mode 100644 openshock/rest/api/admin/admin_delete_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_delete_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_delete_user.py delete mode 100644 openshock/rest/api/admin/admin_get_admin_audit_log.py delete mode 100644 openshock/rest/api/admin/admin_get_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_get_email_outbox_stats.py delete mode 100644 openshock/rest/api/admin/admin_get_online_devices.py delete mode 100644 openshock/rest/api/admin/admin_get_online_gateways.py delete mode 100644 openshock/rest/api/admin/admin_get_user_by_id.py delete mode 100644 openshock/rest/api/admin/admin_get_users.py delete mode 100644 openshock/rest/api/admin/admin_list_automation_tokens.py delete mode 100644 openshock/rest/api/admin/admin_list_email_provider_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_list_username_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_list_webhooks.py delete mode 100644 openshock/rest/api/admin/admin_modify_user.py delete mode 100644 openshock/rest/api/admin/admin_patch_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_reactivate_user.py delete mode 100644 openshock/rest/api/admin/admin_remove_email_provider_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_remove_username_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_remove_webhook.py delete mode 100644 openshock/rest/api/admin/admin_requeue_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_rotate_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_send_test_email.py delete mode 100644 openshock/rest/api/admin/admin_set_user_email.py delete mode 100644 openshock/rest/api/admin/admin_set_user_name.py delete mode 100644 openshock/rest/api/admin/admin_set_user_password.py delete mode 100644 openshock/rest/api/api_tokens/tokens_create_token_v2.py delete mode 100644 openshock/rest/api/api_tokens/tokens_edit_token_v2.py delete mode 100644 openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py delete mode 100644 openshock/rest/api/api_tokens/tokens_list_tokens_v2.py delete mode 100644 openshock/rest/api/api_tokens/tokens_report_tokens.py delete mode 100644 openshock/rest/api/api_tokens/tokens_set_token_paused.py delete mode 100644 openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py delete mode 100644 openshock/rest/api/sessions/__init__.py delete mode 100644 openshock/rest/api/sessions/sessions_delete_session.py delete mode 100644 openshock/rest/api/sessions/sessions_get_self_session.py delete mode 100644 openshock/rest/api/sessions/sessions_list_sessions.py delete mode 100644 openshock/rest/api/shocker_shares/__init__.py delete mode 100644 openshock/rest/api/shocker_shares/shares_delete_share_code.py delete mode 100644 openshock/rest/api/shocker_shares/shares_link_share_code.py delete mode 100644 openshock/rest/models/add_email_provider_blacklist_dto.py delete mode 100644 openshock/rest/models/add_username_blacklist_dto.py delete mode 100644 openshock/rest/models/add_webhook_dto.py delete mode 100644 openshock/rest/models/admin_online_device_response.py delete mode 100644 openshock/rest/models/admin_online_gateway_response.py delete mode 100644 openshock/rest/models/admin_user_view.py delete mode 100644 openshock/rest/models/admin_user_view_api_token.py delete mode 100644 openshock/rest/models/admin_user_view_email_change.py delete mode 100644 openshock/rest/models/admin_user_view_hub.py delete mode 100644 openshock/rest/models/admin_user_view_name_change.py delete mode 100644 openshock/rest/models/admin_user_view_password_reset.py delete mode 100644 openshock/rest/models/admin_user_view_shocker.py delete mode 100644 openshock/rest/models/admin_user_view_user_activation_request.py delete mode 100644 openshock/rest/models/admin_user_view_user_deactivation.py delete mode 100644 openshock/rest/models/admin_user_view_user_ref.py delete mode 100644 openshock/rest/models/admin_users_view.py delete mode 100644 openshock/rest/models/audit_action.py delete mode 100644 openshock/rest/models/audit_log_entry_response.py delete mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_login_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_login_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata_t.py delete mode 100644 openshock/rest/models/automation_token_dto.py delete mode 100644 openshock/rest/models/automation_token_type.py delete mode 100644 openshock/rest/models/change_email_request.py delete mode 100644 openshock/rest/models/change_password_request.py delete mode 100644 openshock/rest/models/configuration_add_item_request.py delete mode 100644 openshock/rest/models/configuration_item_dto.py delete mode 100644 openshock/rest/models/configuration_update_item_request.py delete mode 100644 openshock/rest/models/configuration_value_type.py delete mode 100644 openshock/rest/models/create_automation_token_dto.py delete mode 100644 openshock/rest/models/create_token_request_v2.py delete mode 100644 openshock/rest/models/created_automation_token_dto.py delete mode 100644 openshock/rest/models/edit_token_request_v2.py delete mode 100644 openshock/rest/models/email_outbox_bulk_request.py delete mode 100644 openshock/rest/models/email_outbox_bulk_result_dto.py delete mode 100644 openshock/rest/models/email_outbox_message_dto.py delete mode 100644 openshock/rest/models/email_outbox_message_dto_payload.py delete mode 100644 openshock/rest/models/email_outbox_stats_dto.py delete mode 100644 openshock/rest/models/email_provider_blacklist_dto.py delete mode 100644 openshock/rest/models/email_status.py delete mode 100644 openshock/rest/models/email_type.py delete mode 100644 openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py delete mode 100644 openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py delete mode 100644 openshock/rest/models/login_session_response.py delete mode 100644 openshock/rest/models/match_type_enum.py delete mode 100644 openshock/rest/models/o_auth_connection_response.py delete mode 100644 openshock/rest/models/ota_item.py delete mode 100644 openshock/rest/models/ota_update_status.py delete mode 100644 openshock/rest/models/paged_result_of_audit_log_entry_response.py delete mode 100644 openshock/rest/models/paginated_of_admin_users_view.py delete mode 100644 openshock/rest/models/paginated_of_email_outbox_message_dto.py delete mode 100644 openshock/rest/models/password_hashing_algorithm.py delete mode 100644 openshock/rest/models/patch_automation_token_dto.py delete mode 100644 openshock/rest/models/report_tokens_request.py delete mode 100644 openshock/rest/models/send_test_email_dto.py delete mode 100644 openshock/rest/models/set_token_paused_request.py delete mode 100644 openshock/rest/models/set_user_email_request_body.py delete mode 100644 openshock/rest/models/set_user_name_request_body.py delete mode 100644 openshock/rest/models/set_user_password_request_body.py delete mode 100644 openshock/rest/models/token_created_response_v2.py delete mode 100644 openshock/rest/models/token_paused_response.py delete mode 100644 openshock/rest/models/user_name_blacklist_dto.py delete mode 100644 openshock/rest/models/user_patch_dto.py delete mode 100644 openshock/rest/models/webhook_dto.py diff --git a/README.md b/README.md index 35863ce..7e80f02 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ The official OpenShock Python SDK to integrate with an OpenShock backend easily. -- **REST API** — every endpoint and model, generated from the backend's OpenAPI document, sync and async +- **REST API** — every endpoint an API token can call, generated from the backend's OpenAPI document, sync and async - **Realtime events** — SignalR user hub: hub online state, executed commands, firmware updates - **Live control** — stream intensity to shockers in real time - Typed models and enums, typed errors, automatic reconnects, Python 3.11+ @@ -73,7 +73,11 @@ OpenShock team tell integrations apart. `openshock.rest` is generated from the backend's OpenAPI document with [openapi-python-client](https://github.com/openapi-generators/openapi-python-client). Nothing -in it is written by hand, so it always covers the whole API. +in it is written by hand. + +It covers everything you can call with an API token or a hub's device token, plus the +endpoints that need no authentication. Admin endpoints and endpoints that only accept a +browser login session (managing API tokens and login sessions, account settings) are left out. - **Operations** live in `openshock.rest.api.`, one module per endpoint. The module name is the endpoint's operation ID in snake case. @@ -85,13 +89,13 @@ in it is written by hand, so it always covers the whole API. |-------------------------------|--------| | `shockers` | Shocker CRUD, control, pause, logs, share codes | | `hub_management` | Hubs: list, create, edit, pair code, gateway lookup, OTA history | -| `user_shocker_shares`, `shocker_shares` | User-to-user shares and invites | +| `user_shocker_shares` | User-to-user shares and invites | | `public_shocker_shares` | Public share links | -| `api_tokens` | API tokens | -| `users`, `account`, `sessions` | Profile, account settings, login sessions | +| `api_tokens` | The token you are using: inspect it, delete a token | +| `users`, `account` | Profile, and the unauthenticated account flows (sign-up, password reset) | | `meta` | Backend version and public stats | | `hub_endpoints` | What a hub device itself calls (see below) | -| `integrations`, `admin` | Integrations and admin endpoints | +| `integrations` | Integrations | Each operation module offers the same functions: @@ -305,7 +309,8 @@ python scripts/generate.py # regenerate from the committed snapshot python scripts/generate.py --check # what CI runs; fails if openshock/rest is out of date ``` -The generator and formatter versions are pinned in the `codegen` extra because they decide +The script drops admin and session-only operations (and the models only they use) from the +document before generating. The generator and formatter versions are pinned in the `codegen` extra because they decide the output. The script fails rather than emit a partial client if the generator skips anything. Hand-written code is limited to what the OpenAPI document cannot describe: the preconfigured diff --git a/openshock/rest/api/account/authenticated_account_change_email.py b/openshock/rest/api/account/authenticated_account_change_email.py deleted file mode 100644 index 61c9030..0000000 --- a/openshock/rest/api/account/authenticated_account_change_email.py +++ /dev/null @@ -1,189 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.change_email_request import ChangeEmailRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ChangeEmailRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/email-change", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = OpenShockProblem.from_dict(response.json()) - - return response_401 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if response.status_code == 429: - response_429 = OpenShockProblem.from_dict(response.json()) - - return response_429 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Response[Any | OpenShockProblem]: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. - - Args: - body (ChangeEmailRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Any | OpenShockProblem | None: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. - - Args: - body (ChangeEmailRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Response[Any | OpenShockProblem]: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. - - Args: - body (ChangeEmailRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Any | OpenShockProblem | None: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. - - Args: - body (ChangeEmailRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_password.py b/openshock/rest/api/account/authenticated_account_change_password.py deleted file mode 100644 index 278a24f..0000000 --- a/openshock/rest/api/account/authenticated_account_change_password.py +++ /dev/null @@ -1,170 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.change_password_request import ChangePasswordRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ChangePasswordRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/password", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Response[Any | OpenShockProblem]: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Any | OpenShockProblem | None: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Response[Any | OpenShockProblem]: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Any | OpenShockProblem | None: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_username.py b/openshock/rest/api/account/authenticated_account_change_username.py deleted file mode 100644 index 4f5f5c2..0000000 --- a/openshock/rest/api/account/authenticated_account_change_username.py +++ /dev/null @@ -1,175 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.change_username_request import ChangeUsernameRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ChangeUsernameRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/username", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Response[Any | OpenShockProblem]: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Any | OpenShockProblem | None: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Response[Any | OpenShockProblem]: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Any | OpenShockProblem | None: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_deactivate.py b/openshock/rest/api/account/authenticated_account_deactivate.py deleted file mode 100644 index 1c590a1..0000000 --- a/openshock/rest/api/account/authenticated_account_deactivate.py +++ /dev/null @@ -1,133 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/account", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 204: - response_204 = cast(Any, None) - return response_204 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_get_audit_log.py b/openshock/rest/api/account/authenticated_account_get_audit_log.py deleted file mode 100644 index 36ca1f4..0000000 --- a/openshock/rest/api/account/authenticated_account_get_audit_log.py +++ /dev/null @@ -1,226 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse -from ...models.sort_direction import SortDirection -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["page"] = page - - params["pageSize"] = page_size - - params["search"] = search - - params["sort"] = sort - - json_sort_dir: str | Unset = UNSET - if not isinstance(sort_dir, Unset): - json_sort_dir = sort_dir.value - - params["sortDir"] = json_sort_dir - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/account/audit-log", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> PagedResultOfAuditLogEntryResponse | None: - if response.status_code == 200: - response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[PagedResultOfAuditLogEntryResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return sync_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return ( - await asyncio_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py b/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py deleted file mode 100644 index 4bed30e..0000000 --- a/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py +++ /dev/null @@ -1,134 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.o_auth_connection_response import OAuthConnectionResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/account/connections", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[OAuthConnectionResponse] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = OAuthConnectionResponse.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[OAuthConnectionResponse]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[OAuthConnectionResponse]]: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[OAuthConnectionResponse]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[OAuthConnectionResponse] | None: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[OAuthConnectionResponse] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[OAuthConnectionResponse]]: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[OAuthConnectionResponse]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[OAuthConnectionResponse] | None: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[OAuthConnectionResponse] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py b/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py deleted file mode 100644 index d91c1ca..0000000 --- a/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py +++ /dev/null @@ -1,158 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - provider: str, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/account/connections/{provider}".format( - provider=quote(str(provider), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 204: - response_204 = cast(Any, None) - return response_204 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - provider: str, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - provider=provider, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - provider: str, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - provider=provider, - client=client, - ).parsed - - -async def asyncio_detailed( - provider: str, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - provider=provider, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - provider: str, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - provider=provider, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/__init__.py b/openshock/rest/api/admin/__init__.py deleted file mode 100644 index 181fdd9..0000000 --- a/openshock/rest/api/admin/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/admin/admin_add_email_provider_blacklist.py b/openshock/rest/api/admin/admin_add_email_provider_blacklist.py deleted file mode 100644 index 2dcec86..0000000 --- a/openshock/rest/api/admin/admin_add_email_provider_blacklist.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto -from ...types import Response - - -def _get_kwargs( - *, - body: AddEmailProviderBlacklistDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/blacklist/emailProviders", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: AddEmailProviderBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddEmailProviderBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: AddEmailProviderBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddEmailProviderBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_username_blacklist.py b/openshock/rest/api/admin/admin_add_username_blacklist.py deleted file mode 100644 index c5fbddb..0000000 --- a/openshock/rest/api/admin/admin_add_username_blacklist.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.add_username_blacklist_dto import AddUsernameBlacklistDto -from ...types import Response - - -def _get_kwargs( - *, - body: AddUsernameBlacklistDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/blacklist/usernames", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: AddUsernameBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddUsernameBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: AddUsernameBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddUsernameBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_webhook.py b/openshock/rest/api/admin/admin_add_webhook.py deleted file mode 100644 index 833d05d..0000000 --- a/openshock/rest/api/admin/admin_add_webhook.py +++ /dev/null @@ -1,167 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.add_webhook_dto import AddWebhookDto -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - *, - body: AddWebhookDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/webhooks", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = ProblemDetails.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Response[Any | ProblemDetails]: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Any | ProblemDetails | None: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Response[Any | ProblemDetails]: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Any | ProblemDetails | None: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py b/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py deleted file mode 100644 index a4c511e..0000000 --- a/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py +++ /dev/null @@ -1,177 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest -from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from ...types import Response - - -def _get_kwargs( - *, - body: EmailOutboxBulkRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/bulk/cancel", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxBulkResultDto | None: - if response.status_code == 200: - response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxBulkResultDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py b/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py deleted file mode 100644 index 775933d..0000000 --- a/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py +++ /dev/null @@ -1,173 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest -from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from ...types import Response - - -def _get_kwargs( - *, - body: EmailOutboxBulkRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/bulk/delete", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxBulkResultDto | None: - if response.status_code == 200: - response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxBulkResultDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py b/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py deleted file mode 100644 index 5e3f3ed..0000000 --- a/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py +++ /dev/null @@ -1,177 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest -from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from ...types import Response - - -def _get_kwargs( - *, - body: EmailOutboxBulkRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/bulk/requeue", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxBulkResultDto | None: - if response.status_code == 200: - response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxBulkResultDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_cancel_email_outbox.py b/openshock/rest/api/admin/admin_cancel_email_outbox.py deleted file mode 100644 index 6257ab1..0000000 --- a/openshock/rest/api/admin/admin_cancel_email_outbox.py +++ /dev/null @@ -1,172 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/{id}/cancel".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = ProblemDetails.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_add.py b/openshock/rest/api/admin/admin_configuration_add.py deleted file mode 100644 index 4347d91..0000000 --- a/openshock/rest/api/admin/admin_configuration_add.py +++ /dev/null @@ -1,174 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.configuration_add_item_request import ConfigurationAddItemRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ConfigurationAddItemRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/config", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Response[Any | OpenShockProblem]: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Any | OpenShockProblem | None: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Response[Any | OpenShockProblem]: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Any | OpenShockProblem | None: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_delete.py b/openshock/rest/api/admin/admin_configuration_delete.py deleted file mode 100644 index 7161385..0000000 --- a/openshock/rest/api/admin/admin_configuration_delete.py +++ /dev/null @@ -1,169 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - name: str, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/config/{name}".format( - name=quote(str(name), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - name: str, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - name=name, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - name: str, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - name=name, - client=client, - ).parsed - - -async def asyncio_detailed( - name: str, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - name=name, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - name: str, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - name=name, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_list.py b/openshock/rest/api/admin/admin_configuration_list.py deleted file mode 100644 index 39dc4fd..0000000 --- a/openshock/rest/api/admin/admin_configuration_list.py +++ /dev/null @@ -1,138 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.configuration_item_dto import ConfigurationItemDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/config", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | list[ConfigurationItemDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = ConfigurationItemDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | list[ConfigurationItemDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[ConfigurationItemDto]]: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[ConfigurationItemDto]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | list[ConfigurationItemDto] | None: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[ConfigurationItemDto] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[ConfigurationItemDto]]: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[ConfigurationItemDto]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | list[ConfigurationItemDto] | None: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[ConfigurationItemDto] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_update.py b/openshock/rest/api/admin/admin_configuration_update.py deleted file mode 100644 index 93f5294..0000000 --- a/openshock/rest/api/admin/admin_configuration_update.py +++ /dev/null @@ -1,191 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.configuration_update_item_request import ConfigurationUpdateItemRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ConfigurationUpdateItemRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/config", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Response[Any | OpenShockProblem]: - """Updates an existing configuration - - Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Any | OpenShockProblem | None: - """Updates an existing configuration - - Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Response[Any | OpenShockProblem]: - """Updates an existing configuration - - Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Any | OpenShockProblem | None: - """Updates an existing configuration - - Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_create_automation_token.py b/openshock/rest/api/admin/admin_create_automation_token.py deleted file mode 100644 index 8ebddfe..0000000 --- a/openshock/rest/api/admin/admin_create_automation_token.py +++ /dev/null @@ -1,161 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.create_automation_token_dto import CreateAutomationTokenDto -from ...models.created_automation_token_dto import CreatedAutomationTokenDto -from ...types import Response - - -def _get_kwargs( - *, - body: CreateAutomationTokenDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/automationTokens", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> CreatedAutomationTokenDto | None: - if response.status_code == 200: - response_200 = CreatedAutomationTokenDto.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[CreatedAutomationTokenDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> Response[CreatedAutomationTokenDto]: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> CreatedAutomationTokenDto | None: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> Response[CreatedAutomationTokenDto]: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> CreatedAutomationTokenDto | None: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_deactivate_user.py b/openshock/rest/api/admin/admin_deactivate_user.py deleted file mode 100644 index fb92e0d..0000000 --- a/openshock/rest/api/admin/admin_deactivate_user.py +++ /dev/null @@ -1,127 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - user_id: UUID, - *, - delete_later: bool | Unset = UNSET, - reason: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["deleteLater"] = delete_later - - params["reason"] = reason - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/deactivate".format( - user_id=quote(str(user_id), safe=""), - ), - "params": params, - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - delete_later: bool | Unset = UNSET, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deactivates a user - - Args: - user_id (UUID): - delete_later (bool | Unset): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - delete_later=delete_later, - reason=reason, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - delete_later: bool | Unset = UNSET, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deactivates a user - - Args: - user_id (UUID): - delete_later (bool | Unset): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - delete_later=delete_later, - reason=reason, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_api_token.py b/openshock/rest/api/admin/admin_delete_api_token.py deleted file mode 100644 index aa2c018..0000000 --- a/openshock/rest/api/admin/admin_delete_api_token.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import Response - - -def _get_kwargs( - token_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/apitokens/{token_id}".format( - token_id=quote(str(token_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any]: - """Deletes an API token - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - token_id=token_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any]: - """Deletes an API token - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - token_id=token_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_automation_token.py b/openshock/rest/api/admin/admin_delete_automation_token.py deleted file mode 100644 index 0bc899c..0000000 --- a/openshock/rest/api/admin/admin_delete_automation_token.py +++ /dev/null @@ -1,168 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/automationTokens/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = ProblemDetails.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_delete_email_outbox.py b/openshock/rest/api/admin/admin_delete_email_outbox.py deleted file mode 100644 index 6a9034d..0000000 --- a/openshock/rest/api/admin/admin_delete_email_outbox.py +++ /dev/null @@ -1,167 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/email/outbox/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_delete_user.py b/openshock/rest/api/admin/admin_delete_user.py deleted file mode 100644 index 4de0110..0000000 --- a/openshock/rest/api/admin/admin_delete_user.py +++ /dev/null @@ -1,118 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - user_id: UUID, - *, - reason: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["reason"] = reason - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/users/{user_id}".format( - user_id=quote(str(user_id), safe=""), - ), - "params": params, - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deletes a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deletes a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_get_admin_audit_log.py b/openshock/rest/api/admin/admin_get_admin_audit_log.py deleted file mode 100644 index 55d480b..0000000 --- a/openshock/rest/api/admin/admin_get_admin_audit_log.py +++ /dev/null @@ -1,263 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse -from ...models.sort_direction import SortDirection -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["page"] = page - - params["pageSize"] = page_size - - params["search"] = search - - params["sort"] = sort - - json_sort_dir: str | Unset = UNSET - if not isinstance(sort_dir, Unset): - json_sort_dir = sort_dir.value - - params["sortDir"] = json_sort_dir - - json_user_id: str | Unset = UNSET - if not isinstance(user_id, Unset): - json_user_id = str(user_id) - params["userId"] = json_user_id - - json_actor_id: str | Unset = UNSET - if not isinstance(actor_id, Unset): - json_actor_id = str(actor_id) - params["actorId"] = json_actor_id - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/audit-log", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> PagedResultOfAuditLogEntryResponse | None: - if response.status_code == 200: - response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[PagedResultOfAuditLogEntryResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return sync_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return ( - await asyncio_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox.py b/openshock/rest/api/admin/admin_get_email_outbox.py deleted file mode 100644 index af7ea09..0000000 --- a/openshock/rest/api/admin/admin_get_email_outbox.py +++ /dev/null @@ -1,218 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["$filter"] = filter_ - - params["$orderby"] = orderby - - params["$offset"] = offset - - params["$limit"] = limit - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/email/outbox", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | PaginatedOfEmailOutboxMessageDto | None: - if response.status_code == 200: - response_200 = PaginatedOfEmailOutboxMessageDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfEmailOutboxMessageDto] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfEmailOutboxMessageDto | None: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfEmailOutboxMessageDto - """ - - return sync_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfEmailOutboxMessageDto] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfEmailOutboxMessageDto | None: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfEmailOutboxMessageDto - """ - - return ( - await asyncio_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox_stats.py b/openshock/rest/api/admin/admin_get_email_outbox_stats.py deleted file mode 100644 index 1e97d6d..0000000 --- a/openshock/rest/api/admin/admin_get_email_outbox_stats.py +++ /dev/null @@ -1,133 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_stats_dto import EmailOutboxStatsDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/email/outbox/stats", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxStatsDto | None: - if response.status_code == 200: - response_200 = EmailOutboxStatsDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxStatsDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | EmailOutboxStatsDto]: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxStatsDto] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | EmailOutboxStatsDto | None: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxStatsDto - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | EmailOutboxStatsDto]: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxStatsDto] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | EmailOutboxStatsDto | None: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxStatsDto - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_devices.py b/openshock/rest/api/admin/admin_get_online_devices.py deleted file mode 100644 index 038a002..0000000 --- a/openshock/rest/api/admin/admin_get_online_devices.py +++ /dev/null @@ -1,135 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_data_response_of_array_of_admin_online_device_response import ( - LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, -) -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/monitoring/onlineDevices", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: - if response.status_code == 200: - response_200 = LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_gateways.py b/openshock/rest/api/admin/admin_get_online_gateways.py deleted file mode 100644 index 8e655a1..0000000 --- a/openshock/rest/api/admin/admin_get_online_gateways.py +++ /dev/null @@ -1,138 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.admin_online_gateway_response import AdminOnlineGatewayResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/monitoring/gateways", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | list[AdminOnlineGatewayResponse] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = AdminOnlineGatewayResponse.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | list[AdminOnlineGatewayResponse]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[AdminOnlineGatewayResponse]]: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[AdminOnlineGatewayResponse]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | list[AdminOnlineGatewayResponse] | None: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[AdminOnlineGatewayResponse] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[AdminOnlineGatewayResponse]]: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[AdminOnlineGatewayResponse]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | list[AdminOnlineGatewayResponse] | None: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[AdminOnlineGatewayResponse] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_user_by_id.py b/openshock/rest/api/admin/admin_get_user_by_id.py deleted file mode 100644 index 0cdfef5..0000000 --- a/openshock/rest/api/admin/admin_get_user_by_id.py +++ /dev/null @@ -1,167 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.admin_user_view import AdminUserView -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - user_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/users/{user_id}".format( - user_id=quote(str(user_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> AdminUserView | Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = AdminUserView.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[AdminUserView | Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[AdminUserView | Any | ProblemDetails]: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AdminUserView | Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> AdminUserView | Any | ProblemDetails | None: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AdminUserView | Any | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[AdminUserView | Any | ProblemDetails]: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AdminUserView | Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> AdminUserView | Any | ProblemDetails | None: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AdminUserView | Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_users.py b/openshock/rest/api/admin/admin_get_users.py deleted file mode 100644 index 87e1045..0000000 --- a/openshock/rest/api/admin/admin_get_users.py +++ /dev/null @@ -1,210 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paginated_of_admin_users_view import PaginatedOfAdminUsersView -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["$filter"] = filter_ - - params["$orderby"] = orderby - - params["$offset"] = offset - - params["$limit"] = limit - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/users", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | PaginatedOfAdminUsersView | None: - if response.status_code == 200: - response_200 = PaginatedOfAdminUsersView.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | PaginatedOfAdminUsersView]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfAdminUsersView]: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfAdminUsersView] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfAdminUsersView | None: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfAdminUsersView - """ - - return sync_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfAdminUsersView]: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfAdminUsersView] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfAdminUsersView | None: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfAdminUsersView - """ - - return ( - await asyncio_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_automation_tokens.py b/openshock/rest/api/admin/admin_list_automation_tokens.py deleted file mode 100644 index 23171a0..0000000 --- a/openshock/rest/api/admin/admin_list_automation_tokens.py +++ /dev/null @@ -1,134 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.automation_token_dto import AutomationTokenDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/automationTokens", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[AutomationTokenDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = AutomationTokenDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[AutomationTokenDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[AutomationTokenDto]]: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[AutomationTokenDto]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[AutomationTokenDto] | None: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[AutomationTokenDto] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[AutomationTokenDto]]: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[AutomationTokenDto]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[AutomationTokenDto] | None: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[AutomationTokenDto] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_email_provider_blacklist.py b/openshock/rest/api/admin/admin_list_email_provider_blacklist.py deleted file mode 100644 index f6011ba..0000000 --- a/openshock/rest/api/admin/admin_list_email_provider_blacklist.py +++ /dev/null @@ -1,162 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_provider_blacklist_dto import EmailProviderBlacklistDto -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - match: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["match"] = match - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/blacklist/emailProviders", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[EmailProviderBlacklistDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = EmailProviderBlacklistDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[EmailProviderBlacklistDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[EmailProviderBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[EmailProviderBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[EmailProviderBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[EmailProviderBlacklistDto] - """ - - return sync_detailed( - client=client, - match=match, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[EmailProviderBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[EmailProviderBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[EmailProviderBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[EmailProviderBlacklistDto] - """ - - return ( - await asyncio_detailed( - client=client, - match=match, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_username_blacklist.py b/openshock/rest/api/admin/admin_list_username_blacklist.py deleted file mode 100644 index c1f1b45..0000000 --- a/openshock/rest/api/admin/admin_list_username_blacklist.py +++ /dev/null @@ -1,162 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.user_name_blacklist_dto import UserNameBlacklistDto -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - match: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["match"] = match - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/blacklist/usernames", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[UserNameBlacklistDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = UserNameBlacklistDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[UserNameBlacklistDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[UserNameBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[UserNameBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[UserNameBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[UserNameBlacklistDto] - """ - - return sync_detailed( - client=client, - match=match, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[UserNameBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[UserNameBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[UserNameBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[UserNameBlacklistDto] - """ - - return ( - await asyncio_detailed( - client=client, - match=match, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_webhooks.py b/openshock/rest/api/admin/admin_list_webhooks.py deleted file mode 100644 index 87efc54..0000000 --- a/openshock/rest/api/admin/admin_list_webhooks.py +++ /dev/null @@ -1,138 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.webhook_dto import WebhookDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/webhooks", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | list[WebhookDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = WebhookDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | list[WebhookDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[WebhookDto]]: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[WebhookDto]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | list[WebhookDto] | None: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[WebhookDto] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[WebhookDto]]: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[WebhookDto]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | list[WebhookDto] | None: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[WebhookDto] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_modify_user.py b/openshock/rest/api/admin/admin_modify_user.py deleted file mode 100644 index fa09ec9..0000000 --- a/openshock/rest/api/admin/admin_modify_user.py +++ /dev/null @@ -1,121 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.user_patch_dto import UserPatchDto -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: UserPatchDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/1/admin/users/{user_id}".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if response.status_code == 404: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: UserPatchDto, -) -> Response[Any]: - """Edits a user - - Args: - user_id (UUID): - body (UserPatchDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: UserPatchDto, -) -> Response[Any]: - """Edits a user - - Args: - user_id (UUID): - body (UserPatchDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_patch_automation_token.py b/openshock/rest/api/admin/admin_patch_automation_token.py deleted file mode 100644 index 53798c1..0000000 --- a/openshock/rest/api/admin/admin_patch_automation_token.py +++ /dev/null @@ -1,184 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.automation_token_dto import AutomationTokenDto -from ...models.patch_automation_token_dto import PatchAutomationTokenDto -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, - *, - body: PatchAutomationTokenDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/1/admin/automationTokens/{id}".format( - id=quote(str(id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> AutomationTokenDto | ProblemDetails | None: - if response.status_code == 200: - response_200 = AutomationTokenDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[AutomationTokenDto | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> Response[AutomationTokenDto | ProblemDetails]: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> AutomationTokenDto | ProblemDetails | None: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AutomationTokenDto | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> Response[AutomationTokenDto | ProblemDetails]: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> AutomationTokenDto | ProblemDetails | None: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AutomationTokenDto | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_reactivate_user.py b/openshock/rest/api/admin/admin_reactivate_user.py deleted file mode 100644 index 8a950b1..0000000 --- a/openshock/rest/api/admin/admin_reactivate_user.py +++ /dev/null @@ -1,118 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - user_id: UUID, - *, - reason: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["reason"] = reason - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/reactivate".format( - user_id=quote(str(user_id), safe=""), - ), - "params": params, - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Reactivates a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Reactivates a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py b/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py deleted file mode 100644 index e38dd29..0000000 --- a/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py +++ /dev/null @@ -1,155 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/blacklist/emailProviders/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_remove_username_blacklist.py b/openshock/rest/api/admin/admin_remove_username_blacklist.py deleted file mode 100644 index c019ba9..0000000 --- a/openshock/rest/api/admin/admin_remove_username_blacklist.py +++ /dev/null @@ -1,155 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/blacklist/usernames/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_remove_webhook.py b/openshock/rest/api/admin/admin_remove_webhook.py deleted file mode 100644 index 3248192..0000000 --- a/openshock/rest/api/admin/admin_remove_webhook.py +++ /dev/null @@ -1,163 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/webhooks/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_requeue_email_outbox.py b/openshock/rest/api/admin/admin_requeue_email_outbox.py deleted file mode 100644 index 4922023..0000000 --- a/openshock/rest/api/admin/admin_requeue_email_outbox.py +++ /dev/null @@ -1,172 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/{id}/requeue".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = ProblemDetails.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_rotate_automation_token.py b/openshock/rest/api/admin/admin_rotate_automation_token.py deleted file mode 100644 index 38a1b67..0000000 --- a/openshock/rest/api/admin/admin_rotate_automation_token.py +++ /dev/null @@ -1,163 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.created_automation_token_dto import CreatedAutomationTokenDto -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/automationTokens/{id}/rotate".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> CreatedAutomationTokenDto | ProblemDetails | None: - if response.status_code == 200: - response_200 = CreatedAutomationTokenDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[CreatedAutomationTokenDto | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[CreatedAutomationTokenDto | ProblemDetails]: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> CreatedAutomationTokenDto | ProblemDetails | None: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[CreatedAutomationTokenDto | ProblemDetails]: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> CreatedAutomationTokenDto | ProblemDetails | None: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_send_test_email.py b/openshock/rest/api/admin/admin_send_test_email.py deleted file mode 100644 index 90bf759..0000000 --- a/openshock/rest/api/admin/admin_send_test_email.py +++ /dev/null @@ -1,191 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_message_dto import EmailOutboxMessageDto -from ...models.problem_details import ProblemDetails -from ...models.send_test_email_dto import SendTestEmailDto -from ...types import Response - - -def _get_kwargs( - *, - body: SendTestEmailDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/test", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxMessageDto | ProblemDetails | None: - if response.status_code == 200: - response_200 = EmailOutboxMessageDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 400: - response_400 = ProblemDetails.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxMessageDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Any | EmailOutboxMessageDto | ProblemDetails | None: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxMessageDto | ProblemDetails - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxMessageDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Any | EmailOutboxMessageDto | ProblemDetails | None: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxMessageDto | ProblemDetails - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_email.py b/openshock/rest/api/admin/admin_set_user_email.py deleted file mode 100644 index a8fee2d..0000000 --- a/openshock/rest/api/admin/admin_set_user_email.py +++ /dev/null @@ -1,184 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...models.set_user_email_request_body import SetUserEmailRequestBody -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: SetUserEmailRequestBody, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/email".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Response[Any | ProblemDetails]: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Any | ProblemDetails | None: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Response[Any | ProblemDetails]: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Any | ProblemDetails | None: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_name.py b/openshock/rest/api/admin/admin_set_user_name.py deleted file mode 100644 index fc6ff10..0000000 --- a/openshock/rest/api/admin/admin_set_user_name.py +++ /dev/null @@ -1,192 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.problem_details import ProblemDetails -from ...models.set_user_name_request_body import SetUserNameRequestBody -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: SetUserNameRequestBody, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/name".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_password.py b/openshock/rest/api/admin/admin_set_user_password.py deleted file mode 100644 index 60ab728..0000000 --- a/openshock/rest/api/admin/admin_set_user_password.py +++ /dev/null @@ -1,192 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.problem_details import ProblemDetails -from ...models.set_user_password_request_body import SetUserPasswordRequestBody -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: SetUserPasswordRequestBody, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/password".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_create_token_v2.py b/openshock/rest/api/api_tokens/tokens_create_token_v2.py deleted file mode 100644 index 3c43d0b..0000000 --- a/openshock/rest/api/api_tokens/tokens_create_token_v2.py +++ /dev/null @@ -1,161 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.create_token_request_v2 import CreateTokenRequestV2 -from ...models.token_created_response_v2 import TokenCreatedResponseV2 -from ...types import Response - - -def _get_kwargs( - *, - body: CreateTokenRequestV2, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/2/tokens", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> TokenCreatedResponseV2 | None: - if response.status_code == 200: - response_200 = TokenCreatedResponseV2.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[TokenCreatedResponseV2]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> Response[TokenCreatedResponseV2]: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[TokenCreatedResponseV2] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> TokenCreatedResponseV2 | None: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - TokenCreatedResponseV2 - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> Response[TokenCreatedResponseV2]: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[TokenCreatedResponseV2] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> TokenCreatedResponseV2 | None: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - TokenCreatedResponseV2 - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_edit_token_v2.py b/openshock/rest/api/api_tokens/tokens_edit_token_v2.py deleted file mode 100644 index 6c71df2..0000000 --- a/openshock/rest/api/api_tokens/tokens_edit_token_v2.py +++ /dev/null @@ -1,182 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.edit_token_request_v2 import EditTokenRequestV2 -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - token_id: UUID, - *, - body: EditTokenRequestV2, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/2/tokens/{token_id}".format( - token_id=quote(str(token_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Response[Any | OpenShockProblem]: - """Edit a token - - Args: - token_id (UUID): - body (EditTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token_id=token_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - token_id: UUID, - *, - client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Any | OpenShockProblem | None: - """Edit a token - - Args: - token_id (UUID): - body (EditTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - token_id=token_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Response[Any | OpenShockProblem]: - """Edit a token - - Args: - token_id (UUID): - body (EditTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token_id=token_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - token_id: UUID, - *, - client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Any | OpenShockProblem | None: - """Edit a token - - Args: - token_id (UUID): - body (EditTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - token_id=token_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py b/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py deleted file mode 100644 index 651c565..0000000 --- a/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py +++ /dev/null @@ -1,163 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.token_response_v2 import TokenResponseV2 -from ...types import Response - - -def _get_kwargs( - token_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/2/tokens/{token_id}".format( - token_id=quote(str(token_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> OpenShockProblem | TokenResponseV2 | None: - if response.status_code == 200: - response_200 = TokenResponseV2.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[OpenShockProblem | TokenResponseV2]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[OpenShockProblem | TokenResponseV2]: - """Get a token by id - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[OpenShockProblem | TokenResponseV2] - """ - - kwargs = _get_kwargs( - token_id=token_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> OpenShockProblem | TokenResponseV2 | None: - """Get a token by id - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - OpenShockProblem | TokenResponseV2 - """ - - return sync_detailed( - token_id=token_id, - client=client, - ).parsed - - -async def asyncio_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[OpenShockProblem | TokenResponseV2]: - """Get a token by id - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[OpenShockProblem | TokenResponseV2] - """ - - kwargs = _get_kwargs( - token_id=token_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> OpenShockProblem | TokenResponseV2 | None: - """Get a token by id - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - OpenShockProblem | TokenResponseV2 - """ - - return ( - await asyncio_detailed( - token_id=token_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py b/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py deleted file mode 100644 index f0a4125..0000000 --- a/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py +++ /dev/null @@ -1,132 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.token_response_v2 import TokenResponseV2 -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/2/tokens", - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> list[TokenResponseV2] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = TokenResponseV2.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[TokenResponseV2]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[TokenResponseV2]]: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[TokenResponseV2]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[TokenResponseV2] | None: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[TokenResponseV2] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[TokenResponseV2]]: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[TokenResponseV2]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[TokenResponseV2] | None: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[TokenResponseV2] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_report_tokens.py b/openshock/rest/api/api_tokens/tokens_report_tokens.py deleted file mode 100644 index b505c71..0000000 --- a/openshock/rest/api/api_tokens/tokens_report_tokens.py +++ /dev/null @@ -1,104 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.report_tokens_request import ReportTokensRequest -from ...types import Response - - -def _get_kwargs( - *, - body: ReportTokensRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/tokens/report", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ReportTokensRequest, -) -> Response[Any]: - """Endpoint to delete potentially compromised api tokens - - Args: - body (ReportTokensRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ReportTokensRequest, -) -> Response[Any]: - """Endpoint to delete potentially compromised api tokens - - Args: - body (ReportTokensRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/api_tokens/tokens_set_token_paused.py b/openshock/rest/api/api_tokens/tokens_set_token_paused.py deleted file mode 100644 index feefc15..0000000 --- a/openshock/rest/api/api_tokens/tokens_set_token_paused.py +++ /dev/null @@ -1,184 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.set_token_paused_request import SetTokenPausedRequest -from ...models.token_paused_response import TokenPausedResponse -from ...types import Response - - -def _get_kwargs( - token_id: UUID, - *, - body: SetTokenPausedRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/2/tokens/{token_id}/paused".format( - token_id=quote(str(token_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> OpenShockProblem | TokenPausedResponse | None: - if response.status_code == 200: - response_200 = TokenPausedResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[OpenShockProblem | TokenPausedResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> Response[OpenShockProblem | TokenPausedResponse]: - """Set whether a token is paused. A paused token may not send shocker control messages. - - Args: - token_id (UUID): - body (SetTokenPausedRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[OpenShockProblem | TokenPausedResponse] - """ - - kwargs = _get_kwargs( - token_id=token_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - token_id: UUID, - *, - client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> OpenShockProblem | TokenPausedResponse | None: - """Set whether a token is paused. A paused token may not send shocker control messages. - - Args: - token_id (UUID): - body (SetTokenPausedRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - OpenShockProblem | TokenPausedResponse - """ - - return sync_detailed( - token_id=token_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> Response[OpenShockProblem | TokenPausedResponse]: - """Set whether a token is paused. A paused token may not send shocker control messages. - - Args: - token_id (UUID): - body (SetTokenPausedRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[OpenShockProblem | TokenPausedResponse] - """ - - kwargs = _get_kwargs( - token_id=token_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - token_id: UUID, - *, - client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> OpenShockProblem | TokenPausedResponse | None: - """Set whether a token is paused. A paused token may not send shocker control messages. - - Args: - token_id (UUID): - body (SetTokenPausedRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - OpenShockProblem | TokenPausedResponse - """ - - return ( - await asyncio_detailed( - token_id=token_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py b/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py deleted file mode 100644 index ce2caf2..0000000 --- a/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py +++ /dev/null @@ -1,165 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_data_response_of_i_read_only_collection_of_ota_item import ( - LegacyDataResponseOfIReadOnlyCollectionOfOtaItem, -) -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - device_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/devices/{device_id}/ota".format( - device_id=quote(str(device_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LegacyDataResponseOfIReadOnlyCollectionOfOtaItem.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] - """ - - kwargs = _get_kwargs( - device_id=device_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem - """ - - return sync_detailed( - device_id=device_id, - client=client, - ).parsed - - -async def asyncio_detailed( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] - """ - - kwargs = _get_kwargs( - device_id=device_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem - """ - - return ( - await asyncio_detailed( - device_id=device_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/sessions/__init__.py b/openshock/rest/api/sessions/__init__.py deleted file mode 100644 index 181fdd9..0000000 --- a/openshock/rest/api/sessions/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/sessions/sessions_delete_session.py b/openshock/rest/api/sessions/sessions_delete_session.py deleted file mode 100644 index f5f1179..0000000 --- a/openshock/rest/api/sessions/sessions_delete_session.py +++ /dev/null @@ -1,157 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - session_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/sessions/{session_id}".format( - session_id=quote(str(session_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - session_id=session_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - session_id=session_id, - client=client, - ).parsed - - -async def asyncio_detailed( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - session_id=session_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - session_id=session_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/sessions/sessions_get_self_session.py b/openshock/rest/api/sessions/sessions_get_self_session.py deleted file mode 100644 index 70302aa..0000000 --- a/openshock/rest/api/sessions/sessions_get_self_session.py +++ /dev/null @@ -1,127 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.login_session_response import LoginSessionResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/sessions/self", - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> LoginSessionResponse | None: - if response.status_code == 200: - response_200 = LoginSessionResponse.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LoginSessionResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[LoginSessionResponse]: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LoginSessionResponse] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> LoginSessionResponse | None: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LoginSessionResponse - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[LoginSessionResponse]: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LoginSessionResponse] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> LoginSessionResponse | None: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LoginSessionResponse - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/sessions/sessions_list_sessions.py b/openshock/rest/api/sessions/sessions_list_sessions.py deleted file mode 100644 index 48a8244..0000000 --- a/openshock/rest/api/sessions/sessions_list_sessions.py +++ /dev/null @@ -1,130 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.login_session_response import LoginSessionResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/sessions", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[LoginSessionResponse] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = LoginSessionResponse.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[LoginSessionResponse]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[LoginSessionResponse]]: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[LoginSessionResponse]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[LoginSessionResponse] | None: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[LoginSessionResponse] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[LoginSessionResponse]]: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[LoginSessionResponse]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[LoginSessionResponse] | None: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[LoginSessionResponse] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/shocker_shares/__init__.py b/openshock/rest/api/shocker_shares/__init__.py deleted file mode 100644 index 181fdd9..0000000 --- a/openshock/rest/api/shocker_shares/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/shocker_shares/shares_delete_share_code.py b/openshock/rest/api/shocker_shares/shares_delete_share_code.py deleted file mode 100644 index 4f89f58..0000000 --- a/openshock/rest/api/shocker_shares/shares_delete_share_code.py +++ /dev/null @@ -1,163 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_empty_response import LegacyEmptyResponse -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - share_code_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/shares/code/{share_code_id}".format( - share_code_id=quote(str(share_code_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LegacyEmptyResponse | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LegacyEmptyResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyEmptyResponse | OpenShockProblem - """ - - return sync_detailed( - share_code_id=share_code_id, - client=client, - ).parsed - - -async def asyncio_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyEmptyResponse | OpenShockProblem - """ - - return ( - await asyncio_detailed( - share_code_id=share_code_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/shocker_shares/shares_link_share_code.py b/openshock/rest/api/shocker_shares/shares_link_share_code.py deleted file mode 100644 index a6463ae..0000000 --- a/openshock/rest/api/shocker_shares/shares_link_share_code.py +++ /dev/null @@ -1,172 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_empty_response import LegacyEmptyResponse -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - share_code_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/shares/code/{share_code_id}".format( - share_code_id=quote(str(share_code_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | LegacyEmptyResponse | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LegacyEmptyResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if response.status_code == 500: - response_500 = cast(Any, None) - return response_500 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | LegacyEmptyResponse | OpenShockProblem | None: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyEmptyResponse | OpenShockProblem - """ - - return sync_detailed( - share_code_id=share_code_id, - client=client, - ).parsed - - -async def asyncio_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | LegacyEmptyResponse | OpenShockProblem | None: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyEmptyResponse | OpenShockProblem - """ - - return ( - await asyncio_detailed( - share_code_id=share_code_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/models/__init__.py b/openshock/rest/models/__init__.py index ab386b7..6f13201 100644 --- a/openshock/rest/models/__init__.py +++ b/openshock/rest/models/__init__.py @@ -1,64 +1,10 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. """Contains all the data models used in inputs/outputs""" -from .add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto -from .add_username_blacklist_dto import AddUsernameBlacklistDto -from .add_webhook_dto import AddWebhookDto -from .admin_online_device_response import AdminOnlineDeviceResponse -from .admin_online_gateway_response import AdminOnlineGatewayResponse -from .admin_user_view import AdminUserView -from .admin_user_view_api_token import AdminUserViewApiToken -from .admin_user_view_email_change import AdminUserViewEmailChange -from .admin_user_view_hub import AdminUserViewHub -from .admin_user_view_name_change import AdminUserViewNameChange -from .admin_user_view_password_reset import AdminUserViewPasswordReset -from .admin_user_view_shocker import AdminUserViewShocker -from .admin_user_view_user_activation_request import AdminUserViewUserActivationRequest -from .admin_user_view_user_deactivation import AdminUserViewUserDeactivation -from .admin_user_view_user_ref import AdminUserViewUserRef -from .admin_users_view import AdminUsersView -from .audit_action import AuditAction -from .audit_log_entry_response import AuditLogEntryResponse -from .audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata -from .audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT -from .audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata -from .audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT -from .audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata -from .audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT -from .audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata -from .audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT -from .audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata -from .audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT -from .audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata -from .audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT -from .audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata -from .audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT -from .audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata -from .audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT -from .audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata -from .audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT -from .audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata -from .audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT -from .audit_metadata_login_metadata import AuditMetadataLoginMetadata -from .audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT -from .audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata -from .audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT -from .audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata -from .audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT -from .audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata -from .audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT -from .automation_token_dto import AutomationTokenDto -from .automation_token_type import AutomationTokenType from .backend_info_response import BackendInfoResponse from .basic_user_info import BasicUserInfo from .bulk_user_share_shockers_update_request import BulkUserShareShockersUpdateRequest -from .change_email_request import ChangeEmailRequest -from .change_password_request import ChangePasswordRequest from .change_username_request import ChangeUsernameRequest -from .configuration_add_item_request import ConfigurationAddItemRequest -from .configuration_item_dto import ConfigurationItemDto -from .configuration_update_item_request import ConfigurationUpdateItemRequest -from .configuration_value_type import ConfigurationValueType from .control import Control from .control_limit_mode import ControlLimitMode from .control_log_sender_light import ControlLogSenderLight @@ -68,34 +14,19 @@ from .control_stat_totals import ControlStatTotals from .control_stats_response import ControlStatsResponse from .control_type import ControlType -from .create_automation_token_dto import CreateAutomationTokenDto from .create_share_request import CreateShareRequest -from .create_token_request_v2 import CreateTokenRequestV2 -from .created_automation_token_dto import CreatedAutomationTokenDto from .daily_control_stats import DailyControlStats from .device_response import DeviceResponse from .device_self_response import DeviceSelfResponse from .device_with_shockers_response import DeviceWithShockersResponse from .device_with_token_response import DeviceWithTokenResponse from .duration_limit_settings import DurationLimitSettings -from .edit_token_request_v2 import EditTokenRequestV2 -from .email_outbox_bulk_request import EmailOutboxBulkRequest -from .email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from .email_outbox_message_dto import EmailOutboxMessageDto -from .email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload -from .email_outbox_stats_dto import EmailOutboxStatsDto -from .email_provider_blacklist_dto import EmailProviderBlacklistDto -from .email_status import EmailStatus -from .email_type import EmailType from .given_control_stats import GivenControlStats from .hub_create_request import HubCreateRequest from .hub_edit_request import HubEditRequest from .intensity_limit_settings import IntensityLimitSettings from .lcg_node_response_v2 import LcgNodeResponseV2 from .lcg_response_v2 import LcgResponseV2 -from .legacy_data_response_of_array_of_admin_online_device_response import ( - LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, -) from .legacy_data_response_of_array_of_device_response import LegacyDataResponseOfArrayOfDeviceResponse from .legacy_data_response_of_array_of_device_with_shockers_response import ( LegacyDataResponseOfArrayOfDeviceWithShockersResponse, @@ -112,7 +43,6 @@ from .legacy_data_response_of_device_self_response import LegacyDataResponseOfDeviceSelfResponse from .legacy_data_response_of_device_with_token_response import LegacyDataResponseOfDeviceWithTokenResponse from .legacy_data_response_of_guid import LegacyDataResponseOfGuid -from .legacy_data_response_of_i_read_only_collection_of_ota_item import LegacyDataResponseOfIReadOnlyCollectionOfOtaItem from .legacy_data_response_of_legacy_user_self_response import LegacyDataResponseOfLegacyUserSelfResponse from .legacy_data_response_of_pause_reason import LegacyDataResponseOfPauseReason from .legacy_data_response_of_public_share_response import LegacyDataResponseOfPublicShareResponse @@ -124,26 +54,16 @@ from .legacy_user_self_response import LegacyUserSelfResponse from .log_entry import LogEntry from .log_entry_with_hub import LogEntryWithHub -from .login_session_response import LoginSessionResponse from .login_v2 import LoginV2 from .login_v2_ok_response import LoginV2OkResponse -from .match_type_enum import MatchTypeEnum from .minimal_shocker import MinimalShocker from .new_shocker import NewShocker -from .o_auth_connection_response import OAuthConnectionResponse from .open_shock_problem import OpenShockProblem -from .ota_item import OtaItem -from .ota_update_status import OtaUpdateStatus from .own_public_share_response import OwnPublicShareResponse from .owner_shocker_response import OwnerShockerResponse -from .paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse from .paged_result_of_log_entry_with_hub import PagedResultOfLogEntryWithHub -from .paginated_of_admin_users_view import PaginatedOfAdminUsersView -from .paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto -from .password_hashing_algorithm import PasswordHashingAlgorithm from .password_reset_process_data import PasswordResetProcessData from .password_reset_request_v2 import PasswordResetRequestV2 -from .patch_automation_token_dto import PatchAutomationTokenDto from .pause_request import PauseRequest from .pause_user_share_shockers_request import PauseUserShareShockersRequest from .pause_user_share_shockers_response import PauseUserShareShockersResponse @@ -157,13 +77,7 @@ from .public_share_shocker import PublicShareShocker from .received_control_stats import ReceivedControlStats from .remove_user_shares_response import RemoveUserSharesResponse -from .report_tokens_request import ReportTokensRequest from .role_type import RoleType -from .send_test_email_dto import SendTestEmailDto -from .set_token_paused_request import SetTokenPausedRequest -from .set_user_email_request_body import SetUserEmailRequestBody -from .set_user_name_request_body import SetUserNameRequestBody -from .set_user_password_request_body import SetUserPasswordRequestBody from .share_code_info import ShareCodeInfo from .share_info import ShareInfo from .share_invite_base_details import ShareInviteBaseDetails @@ -182,13 +96,9 @@ from .sign_up_v2 import SignUpV2 from .sort_direction import SortDirection from .stats_response import StatsResponse -from .token_created_response_v2 import TokenCreatedResponseV2 -from .token_paused_response import TokenPausedResponse from .token_response_v2 import TokenResponseV2 from .user_control_stat_totals import UserControlStatTotals from .user_control_stats import UserControlStats -from .user_name_blacklist_dto import UserNameBlacklistDto -from .user_patch_dto import UserPatchDto from .user_self_response import UserSelfResponse from .user_share_info import UserShareInfo from .username_availability import UsernameAvailability @@ -197,67 +107,12 @@ from .username_error_type import UsernameErrorType from .v2_user_shares import V2UserShares from .v2_user_shares_list_item import V2UserSharesListItem -from .webhook_dto import WebhookDto __all__ = ( - "AddEmailProviderBlacklistDto", - "AddUsernameBlacklistDto", - "AddWebhookDto", - "AdminOnlineDeviceResponse", - "AdminOnlineGatewayResponse", - "AdminUsersView", - "AdminUserView", - "AdminUserViewApiToken", - "AdminUserViewEmailChange", - "AdminUserViewHub", - "AdminUserViewNameChange", - "AdminUserViewPasswordReset", - "AdminUserViewShocker", - "AdminUserViewUserActivationRequest", - "AdminUserViewUserDeactivation", - "AdminUserViewUserRef", - "AuditAction", - "AuditLogEntryResponse", - "AuditMetadataAccountDeactivatedMetadata", - "AuditMetadataAccountDeactivatedMetadataT", - "AuditMetadataApiTokenCreatedMetadata", - "AuditMetadataApiTokenCreatedMetadataT", - "AuditMetadataApiTokenDeletedMetadata", - "AuditMetadataApiTokenDeletedMetadataT", - "AuditMetadataAutomationTokenCreatedMetadata", - "AuditMetadataAutomationTokenCreatedMetadataT", - "AuditMetadataAutomationTokenDeletedMetadata", - "AuditMetadataAutomationTokenDeletedMetadataT", - "AuditMetadataAutomationTokenRotatedMetadata", - "AuditMetadataAutomationTokenRotatedMetadataT", - "AuditMetadataAutomationTokenUpdatedMetadata", - "AuditMetadataAutomationTokenUpdatedMetadataT", - "AuditMetadataAutomationTokenUsedMetadata", - "AuditMetadataAutomationTokenUsedMetadataT", - "AuditMetadataEmailChangedMetadata", - "AuditMetadataEmailChangedMetadataT", - "AuditMetadataEmailChangeRequestedMetadata", - "AuditMetadataEmailChangeRequestedMetadataT", - "AuditMetadataLoginMetadata", - "AuditMetadataLoginMetadataT", - "AuditMetadataOAuthConnectedMetadata", - "AuditMetadataOAuthConnectedMetadataT", - "AuditMetadataOAuthDisconnectedMetadata", - "AuditMetadataOAuthDisconnectedMetadataT", - "AuditMetadataUsernameChangedMetadata", - "AuditMetadataUsernameChangedMetadataT", - "AutomationTokenDto", - "AutomationTokenType", "BackendInfoResponse", "BasicUserInfo", "BulkUserShareShockersUpdateRequest", - "ChangeEmailRequest", - "ChangePasswordRequest", "ChangeUsernameRequest", - "ConfigurationAddItemRequest", - "ConfigurationItemDto", - "ConfigurationUpdateItemRequest", - "ConfigurationValueType", "Control", "ControlLimitMode", "ControlLogSenderLight", @@ -267,32 +122,19 @@ "ControlStatsResponse", "ControlStatTotals", "ControlType", - "CreateAutomationTokenDto", - "CreatedAutomationTokenDto", "CreateShareRequest", - "CreateTokenRequestV2", "DailyControlStats", "DeviceResponse", "DeviceSelfResponse", "DeviceWithShockersResponse", "DeviceWithTokenResponse", "DurationLimitSettings", - "EditTokenRequestV2", - "EmailOutboxBulkRequest", - "EmailOutboxBulkResultDto", - "EmailOutboxMessageDto", - "EmailOutboxMessageDtoPayload", - "EmailOutboxStatsDto", - "EmailProviderBlacklistDto", - "EmailStatus", - "EmailType", "GivenControlStats", "HubCreateRequest", "HubEditRequest", "IntensityLimitSettings", "LcgNodeResponseV2", "LcgResponseV2", - "LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse", "LegacyDataResponseOfArrayOfDeviceResponse", "LegacyDataResponseOfArrayOfDeviceWithShockersResponse", "LegacyDataResponseOfArrayOfLogEntry", @@ -306,7 +148,6 @@ "LegacyDataResponseOfDeviceSelfResponse", "LegacyDataResponseOfDeviceWithTokenResponse", "LegacyDataResponseOfGuid", - "LegacyDataResponseOfIReadOnlyCollectionOfOtaItem", "LegacyDataResponseOfLegacyUserSelfResponse", "LegacyDataResponseOfPauseReason", "LegacyDataResponseOfPublicShareResponse", @@ -317,26 +158,16 @@ "LegacyUserSelfResponse", "LogEntry", "LogEntryWithHub", - "LoginSessionResponse", "LoginV2", "LoginV2OkResponse", - "MatchTypeEnum", "MinimalShocker", "NewShocker", - "OAuthConnectionResponse", "OpenShockProblem", - "OtaItem", - "OtaUpdateStatus", "OwnerShockerResponse", "OwnPublicShareResponse", - "PagedResultOfAuditLogEntryResponse", "PagedResultOfLogEntryWithHub", - "PaginatedOfAdminUsersView", - "PaginatedOfEmailOutboxMessageDto", - "PasswordHashingAlgorithm", "PasswordResetProcessData", "PasswordResetRequestV2", - "PatchAutomationTokenDto", "PauseRequest", "PauseUserShareShockersRequest", "PauseUserShareShockersResponse", @@ -350,13 +181,7 @@ "PublicShareShocker", "ReceivedControlStats", "RemoveUserSharesResponse", - "ReportTokensRequest", "RoleType", - "SendTestEmailDto", - "SetTokenPausedRequest", - "SetUserEmailRequestBody", - "SetUserNameRequestBody", - "SetUserPasswordRequestBody", "ShareCodeInfo", "SharedDevice", "SharedShocker", @@ -375,20 +200,15 @@ "SignUpV2", "SortDirection", "StatsResponse", - "TokenCreatedResponseV2", - "TokenPausedResponse", "TokenResponseV2", "UserControlStats", "UserControlStatTotals", "UsernameAvailability", - "UserNameBlacklistDto", "UsernameCheckResponse", "UsernameError", "UsernameErrorType", - "UserPatchDto", "UserSelfResponse", "UserShareInfo", "V2UserShares", "V2UserSharesListItem", - "WebhookDto", ) diff --git a/openshock/rest/models/add_email_provider_blacklist_dto.py b/openshock/rest/models/add_email_provider_blacklist_dto.py deleted file mode 100644 index fb17ea7..0000000 --- a/openshock/rest/models/add_email_provider_blacklist_dto.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AddEmailProviderBlacklistDto") - - -@_attrs_define -class AddEmailProviderBlacklistDto: - """ - Attributes: - domains (list[str]): - """ - - domains: list[str] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - domains = self.domains - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "domains": domains, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - domains = cast(list[str], d.pop("domains")) - - add_email_provider_blacklist_dto = cls( - domains=domains, - ) - - add_email_provider_blacklist_dto.additional_properties = d - return add_email_provider_blacklist_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/add_username_blacklist_dto.py b/openshock/rest/models/add_username_blacklist_dto.py deleted file mode 100644 index e962cb9..0000000 --- a/openshock/rest/models/add_username_blacklist_dto.py +++ /dev/null @@ -1,72 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.match_type_enum import MatchTypeEnum - -T = TypeVar("T", bound="AddUsernameBlacklistDto") - - -@_attrs_define -class AddUsernameBlacklistDto: - """ - Attributes: - value (str): - match_type (MatchTypeEnum): - """ - - value: str - match_type: MatchTypeEnum - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - value = self.value - - match_type = self.match_type.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "value": value, - "matchType": match_type, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - value = d.pop("value") - - match_type = MatchTypeEnum(d.pop("matchType")) - - add_username_blacklist_dto = cls( - value=value, - match_type=match_type, - ) - - add_username_blacklist_dto.additional_properties = d - return add_username_blacklist_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/add_webhook_dto.py b/openshock/rest/models/add_webhook_dto.py deleted file mode 100644 index de3ff55..0000000 --- a/openshock/rest/models/add_webhook_dto.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AddWebhookDto") - - -@_attrs_define -class AddWebhookDto: - """ - Attributes: - name (str): - url (str): - """ - - name: str - url: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - url = self.url - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "url": url, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - url = d.pop("url") - - add_webhook_dto = cls( - name=name, - url=url, - ) - - add_webhook_dto.additional_properties = d - return add_webhook_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_device_response.py b/openshock/rest/models/admin_online_device_response.py deleted file mode 100644 index 5a60cd5..0000000 --- a/openshock/rest/models/admin_online_device_response.py +++ /dev/null @@ -1,216 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.basic_user_info import BasicUserInfo - - -T = TypeVar("T", bound="AdminOnlineDeviceResponse") - - -@_attrs_define -class AdminOnlineDeviceResponse: - """ - Attributes: - id (UUID): - name (str): - owner (BasicUserInfo): - firmware_version (str): - gateway (str): - connected_at (datetime.datetime): - user_agent (None | str): - booted_at (datetime.datetime): - latency_ms (int | None): - rssi (int | None): - country (None | str): - ip (None | str): An IPv4 or IPv6 address in its textual form. - asn (int | None): - asn_org (None | str): - """ - - id: UUID - name: str - owner: BasicUserInfo - firmware_version: str - gateway: str - connected_at: datetime.datetime - user_agent: None | str - booted_at: datetime.datetime - latency_ms: int | None - rssi: int | None - country: None | str - ip: None | str - asn: int | None - asn_org: None | str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - owner = self.owner.to_dict() - - firmware_version = self.firmware_version - - gateway = self.gateway - - connected_at = self.connected_at.isoformat() - - user_agent: None | str - user_agent = self.user_agent - - booted_at = self.booted_at.isoformat() - - latency_ms: int | None - latency_ms = self.latency_ms - - rssi: int | None - rssi = self.rssi - - country: None | str - country = self.country - - ip: None | str - ip = self.ip - - asn: int | None - asn = self.asn - - asn_org: None | str - asn_org = self.asn_org - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "owner": owner, - "firmwareVersion": firmware_version, - "gateway": gateway, - "connectedAt": connected_at, - "userAgent": user_agent, - "bootedAt": booted_at, - "latencyMs": latency_ms, - "rssi": rssi, - "country": country, - "ip": ip, - "asn": asn, - "asnOrg": asn_org, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - owner = BasicUserInfo.from_dict(d.pop("owner")) - - firmware_version = d.pop("firmwareVersion") - - gateway = d.pop("gateway") - - connected_at = datetime.datetime.fromisoformat(d.pop("connectedAt")) - - def _parse_user_agent(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - user_agent = _parse_user_agent(d.pop("userAgent")) - - booted_at = datetime.datetime.fromisoformat(d.pop("bootedAt")) - - def _parse_latency_ms(data: object) -> int | None: - if data is None: - return data - return cast(int | None, data) - - latency_ms = _parse_latency_ms(d.pop("latencyMs")) - - def _parse_rssi(data: object) -> int | None: - if data is None: - return data - return cast(int | None, data) - - rssi = _parse_rssi(d.pop("rssi")) - - def _parse_country(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - country = _parse_country(d.pop("country")) - - def _parse_ip(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - ip = _parse_ip(d.pop("ip")) - - def _parse_asn(data: object) -> int | None: - if data is None: - return data - return cast(int | None, data) - - asn = _parse_asn(d.pop("asn")) - - def _parse_asn_org(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - asn_org = _parse_asn_org(d.pop("asnOrg")) - - admin_online_device_response = cls( - id=id, - name=name, - owner=owner, - firmware_version=firmware_version, - gateway=gateway, - connected_at=connected_at, - user_agent=user_agent, - booted_at=booted_at, - latency_ms=latency_ms, - rssi=rssi, - country=country, - ip=ip, - asn=asn, - asn_org=asn_org, - ) - - admin_online_device_response.additional_properties = d - return admin_online_device_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_gateway_response.py b/openshock/rest/models/admin_online_gateway_response.py deleted file mode 100644 index e4452ad..0000000 --- a/openshock/rest/models/admin_online_gateway_response.py +++ /dev/null @@ -1,146 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminOnlineGatewayResponse") - - -@_attrs_define -class AdminOnlineGatewayResponse: - """ - Attributes: - id (str): - host (str): - port (int): - path_prefix (str): - country (str): - latitude (float | None): - longitude (float | None): - load (int): Load the gateway advertises for hub assignment, in percent - environment (str): - connected_hubs (int): - """ - - id: str - host: str - port: int - path_prefix: str - country: str - latitude: float | None - longitude: float | None - load: int - environment: str - connected_hubs: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = self.id - - host = self.host - - port = self.port - - path_prefix = self.path_prefix - - country = self.country - - latitude: float | None - latitude = self.latitude - - longitude: float | None - longitude = self.longitude - - load = self.load - - environment = self.environment - - connected_hubs = self.connected_hubs - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "host": host, - "port": port, - "pathPrefix": path_prefix, - "country": country, - "latitude": latitude, - "longitude": longitude, - "load": load, - "environment": environment, - "connectedHubs": connected_hubs, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = d.pop("id") - - host = d.pop("host") - - port = d.pop("port") - - path_prefix = d.pop("pathPrefix") - - country = d.pop("country") - - def _parse_latitude(data: object) -> float | None: - if data is None: - return data - return cast(float | None, data) - - latitude = _parse_latitude(d.pop("latitude")) - - def _parse_longitude(data: object) -> float | None: - if data is None: - return data - return cast(float | None, data) - - longitude = _parse_longitude(d.pop("longitude")) - - load = d.pop("load") - - environment = d.pop("environment") - - connected_hubs = d.pop("connectedHubs") - - admin_online_gateway_response = cls( - id=id, - host=host, - port=port, - path_prefix=path_prefix, - country=country, - latitude=latitude, - longitude=longitude, - load=load, - environment=environment, - connected_hubs=connected_hubs, - ) - - admin_online_gateway_response.additional_properties = d - return admin_online_gateway_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view.py b/openshock/rest/models/admin_user_view.py deleted file mode 100644 index f173c58..0000000 --- a/openshock/rest/models/admin_user_view.py +++ /dev/null @@ -1,324 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.password_hashing_algorithm import PasswordHashingAlgorithm -from ..models.role_type import RoleType - -if TYPE_CHECKING: - from ..models.admin_user_view_api_token import AdminUserViewApiToken - from ..models.admin_user_view_email_change import AdminUserViewEmailChange - from ..models.admin_user_view_hub import AdminUserViewHub - from ..models.admin_user_view_name_change import AdminUserViewNameChange - from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset - from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest - from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation - - -T = TypeVar("T", bound="AdminUserView") - - -@_attrs_define -class AdminUserView: - """ - Attributes: - id (UUID): - name (str): - email (str): - password_hash_type (PasswordHashingAlgorithm): - roles (list[RoleType]): - created_at (datetime.datetime): - activated_at (datetime.datetime | None): - created_by_automation_token_id (None | UUID): - activation_request (AdminUserViewUserActivationRequest | None): - deactivation (AdminUserViewUserDeactivation | None): - hubs (list[AdminUserViewHub]): - api_tokens (list[AdminUserViewApiToken]): - users_name_changes (list[AdminUserViewNameChange]): - users_email_changes (list[AdminUserViewEmailChange]): - password_resets (list[AdminUserViewPasswordReset]): - shocker_control_logs_count (int): - """ - - id: UUID - name: str - email: str - password_hash_type: PasswordHashingAlgorithm - roles: list[RoleType] - created_at: datetime.datetime - activated_at: datetime.datetime | None - created_by_automation_token_id: None | UUID - activation_request: AdminUserViewUserActivationRequest | None - deactivation: AdminUserViewUserDeactivation | None - hubs: list[AdminUserViewHub] - api_tokens: list[AdminUserViewApiToken] - users_name_changes: list[AdminUserViewNameChange] - users_email_changes: list[AdminUserViewEmailChange] - password_resets: list[AdminUserViewPasswordReset] - shocker_control_logs_count: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 - from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 - - id = str(self.id) - - name = self.name - - email = self.email - - password_hash_type = self.password_hash_type.value - - roles = [] - for roles_item_data in self.roles: - roles_item = roles_item_data.value - roles.append(roles_item) - - created_at = self.created_at.isoformat() - - activated_at: None | str - if isinstance(self.activated_at, datetime.datetime): - activated_at = self.activated_at.isoformat() - else: - activated_at = self.activated_at - - created_by_automation_token_id: None | str - if isinstance(self.created_by_automation_token_id, UUID): - created_by_automation_token_id = str(self.created_by_automation_token_id) - else: - created_by_automation_token_id = self.created_by_automation_token_id - - activation_request: dict[str, Any] | None - if isinstance(self.activation_request, AdminUserViewUserActivationRequest): - activation_request = self.activation_request.to_dict() - else: - activation_request = self.activation_request - - deactivation: dict[str, Any] | None - if isinstance(self.deactivation, AdminUserViewUserDeactivation): - deactivation = self.deactivation.to_dict() - else: - deactivation = self.deactivation - - hubs = [] - for hubs_item_data in self.hubs: - hubs_item = hubs_item_data.to_dict() - hubs.append(hubs_item) - - api_tokens = [] - for api_tokens_item_data in self.api_tokens: - api_tokens_item = api_tokens_item_data.to_dict() - api_tokens.append(api_tokens_item) - - users_name_changes = [] - for users_name_changes_item_data in self.users_name_changes: - users_name_changes_item = users_name_changes_item_data.to_dict() - users_name_changes.append(users_name_changes_item) - - users_email_changes = [] - for users_email_changes_item_data in self.users_email_changes: - users_email_changes_item = users_email_changes_item_data.to_dict() - users_email_changes.append(users_email_changes_item) - - password_resets = [] - for password_resets_item_data in self.password_resets: - password_resets_item = password_resets_item_data.to_dict() - password_resets.append(password_resets_item) - - shocker_control_logs_count = self.shocker_control_logs_count - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "email": email, - "passwordHashType": password_hash_type, - "roles": roles, - "createdAt": created_at, - "activatedAt": activated_at, - "createdByAutomationTokenId": created_by_automation_token_id, - "activationRequest": activation_request, - "deactivation": deactivation, - "hubs": hubs, - "apiTokens": api_tokens, - "usersNameChanges": users_name_changes, - "usersEmailChanges": users_email_changes, - "passwordResets": password_resets, - "shockerControlLogsCount": shocker_control_logs_count, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_user_view_api_token import AdminUserViewApiToken # noqa: PLC0415 - from ..models.admin_user_view_email_change import AdminUserViewEmailChange # noqa: PLC0415 - from ..models.admin_user_view_hub import AdminUserViewHub # noqa: PLC0415 - from ..models.admin_user_view_name_change import AdminUserViewNameChange # noqa: PLC0415 - from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset # noqa: PLC0415 - from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 - from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - email = d.pop("email") - - password_hash_type = PasswordHashingAlgorithm(d.pop("passwordHashType")) - - roles = [] - _roles = d.pop("roles") - for roles_item_data in _roles: - roles_item = RoleType(roles_item_data) - - roles.append(roles_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_activated_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - activated_at_type_1 = datetime.datetime.fromisoformat(data) - - return activated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - activated_at = _parse_activated_at(d.pop("activatedAt")) - - def _parse_created_by_automation_token_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - created_by_automation_token_id_type_1 = UUID(data) - - return created_by_automation_token_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) - - def _parse_activation_request(data: object) -> AdminUserViewUserActivationRequest | None: - if data is None: - return data - try: - if not isinstance(data, dict): - raise TypeError() - activation_request_type_1 = AdminUserViewUserActivationRequest.from_dict(data) - - return activation_request_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(AdminUserViewUserActivationRequest | None, data) - - activation_request = _parse_activation_request(d.pop("activationRequest")) - - def _parse_deactivation(data: object) -> AdminUserViewUserDeactivation | None: - if data is None: - return data - try: - if not isinstance(data, dict): - raise TypeError() - deactivation_type_1 = AdminUserViewUserDeactivation.from_dict(data) - - return deactivation_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(AdminUserViewUserDeactivation | None, data) - - deactivation = _parse_deactivation(d.pop("deactivation")) - - hubs = [] - _hubs = d.pop("hubs") - for hubs_item_data in _hubs: - hubs_item = AdminUserViewHub.from_dict(hubs_item_data) - - hubs.append(hubs_item) - - api_tokens = [] - _api_tokens = d.pop("apiTokens") - for api_tokens_item_data in _api_tokens: - api_tokens_item = AdminUserViewApiToken.from_dict(api_tokens_item_data) - - api_tokens.append(api_tokens_item) - - users_name_changes = [] - _users_name_changes = d.pop("usersNameChanges") - for users_name_changes_item_data in _users_name_changes: - users_name_changes_item = AdminUserViewNameChange.from_dict(users_name_changes_item_data) - - users_name_changes.append(users_name_changes_item) - - users_email_changes = [] - _users_email_changes = d.pop("usersEmailChanges") - for users_email_changes_item_data in _users_email_changes: - users_email_changes_item = AdminUserViewEmailChange.from_dict(users_email_changes_item_data) - - users_email_changes.append(users_email_changes_item) - - password_resets = [] - _password_resets = d.pop("passwordResets") - for password_resets_item_data in _password_resets: - password_resets_item = AdminUserViewPasswordReset.from_dict(password_resets_item_data) - - password_resets.append(password_resets_item) - - shocker_control_logs_count = d.pop("shockerControlLogsCount") - - admin_user_view = cls( - id=id, - name=name, - email=email, - password_hash_type=password_hash_type, - roles=roles, - created_at=created_at, - activated_at=activated_at, - created_by_automation_token_id=created_by_automation_token_id, - activation_request=activation_request, - deactivation=deactivation, - hubs=hubs, - api_tokens=api_tokens, - users_name_changes=users_name_changes, - users_email_changes=users_email_changes, - password_resets=password_resets, - shocker_control_logs_count=shocker_control_logs_count, - ) - - admin_user_view.additional_properties = d - return admin_user_view - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_api_token.py b/openshock/rest/models/admin_user_view_api_token.py deleted file mode 100644 index ca254d6..0000000 --- a/openshock/rest/models/admin_user_view_api_token.py +++ /dev/null @@ -1,156 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType - -T = TypeVar("T", bound="AdminUserViewApiToken") - - -@_attrs_define -class AdminUserViewApiToken: - """ - Attributes: - id (UUID): - name (str): - permissions (list[PermissionType]): - valid_until (datetime.datetime | None): - last_used (datetime.datetime | None): - created_at (datetime.datetime): - created_by_ip (str): An IPv4 or IPv6 address in its textual form. - """ - - id: UUID - name: str - permissions: list[PermissionType] - valid_until: datetime.datetime | None - last_used: datetime.datetime | None - created_at: datetime.datetime - created_by_ip: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - valid_until: None | str - if isinstance(self.valid_until, datetime.datetime): - valid_until = self.valid_until.isoformat() - else: - valid_until = self.valid_until - - last_used: None | str - if isinstance(self.last_used, datetime.datetime): - last_used = self.last_used.isoformat() - else: - last_used = self.last_used - - created_at = self.created_at.isoformat() - - created_by_ip = self.created_by_ip - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "permissions": permissions, - "validUntil": valid_until, - "lastUsed": last_used, - "createdAt": created_at, - "createdByIp": created_by_ip, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - def _parse_valid_until(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - valid_until_type_1 = datetime.datetime.fromisoformat(data) - - return valid_until_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - valid_until = _parse_valid_until(d.pop("validUntil")) - - def _parse_last_used(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - last_used = _parse_last_used(d.pop("lastUsed")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - created_by_ip = d.pop("createdByIp") - - admin_user_view_api_token = cls( - id=id, - name=name, - permissions=permissions, - valid_until=valid_until, - last_used=last_used, - created_at=created_at, - created_by_ip=created_by_ip, - ) - - admin_user_view_api_token.additional_properties = d - return admin_user_view_api_token - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_email_change.py b/openshock/rest/models/admin_user_view_email_change.py deleted file mode 100644 index a43a754..0000000 --- a/openshock/rest/models/admin_user_view_email_change.py +++ /dev/null @@ -1,105 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewEmailChange") - - -@_attrs_define -class AdminUserViewEmailChange: - """ - Attributes: - id (UUID): - email (str): - created_at (datetime.datetime): - used_at (datetime.datetime | None): - """ - - id: UUID - email: str - created_at: datetime.datetime - used_at: datetime.datetime | None - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - email = self.email - - created_at = self.created_at.isoformat() - - used_at: None | str - if isinstance(self.used_at, datetime.datetime): - used_at = self.used_at.isoformat() - else: - used_at = self.used_at - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "email": email, - "createdAt": created_at, - "usedAt": used_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - email = d.pop("email") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_used_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - used_at_type_1 = datetime.datetime.fromisoformat(data) - - return used_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - used_at = _parse_used_at(d.pop("usedAt")) - - admin_user_view_email_change = cls( - id=id, - email=email, - created_at=created_at, - used_at=used_at, - ) - - admin_user_view_email_change.additional_properties = d - return admin_user_view_email_change - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_hub.py b/openshock/rest/models/admin_user_view_hub.py deleted file mode 100644 index e7620b7..0000000 --- a/openshock/rest/models/admin_user_view_hub.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_user_view_shocker import AdminUserViewShocker - - -T = TypeVar("T", bound="AdminUserViewHub") - - -@_attrs_define -class AdminUserViewHub: - """ - Attributes: - id (UUID): - name (str): - created_at (datetime.datetime): - shockers (list[AdminUserViewShocker]): - """ - - id: UUID - name: str - created_at: datetime.datetime - shockers: list[AdminUserViewShocker] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - created_at = self.created_at.isoformat() - - shockers = [] - for shockers_item_data in self.shockers: - shockers_item = shockers_item_data.to_dict() - shockers.append(shockers_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "createdAt": created_at, - "shockers": shockers, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_user_view_shocker import AdminUserViewShocker # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - shockers = [] - _shockers = d.pop("shockers") - for shockers_item_data in _shockers: - shockers_item = AdminUserViewShocker.from_dict(shockers_item_data) - - shockers.append(shockers_item) - - admin_user_view_hub = cls( - id=id, - name=name, - created_at=created_at, - shockers=shockers, - ) - - admin_user_view_hub.additional_properties = d - return admin_user_view_hub - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_name_change.py b/openshock/rest/models/admin_user_view_name_change.py deleted file mode 100644 index 00eb2fb..0000000 --- a/openshock/rest/models/admin_user_view_name_change.py +++ /dev/null @@ -1,79 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewNameChange") - - -@_attrs_define -class AdminUserViewNameChange: - """ - Attributes: - id (int): - old_name (str): - created_at (datetime.datetime): - """ - - id: int - old_name: str - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = self.id - - old_name = self.old_name - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "oldName": old_name, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = d.pop("id") - - old_name = d.pop("oldName") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - admin_user_view_name_change = cls( - id=id, - old_name=old_name, - created_at=created_at, - ) - - admin_user_view_name_change.additional_properties = d - return admin_user_view_name_change - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_password_reset.py b/openshock/rest/models/admin_user_view_password_reset.py deleted file mode 100644 index 4f0cc60..0000000 --- a/openshock/rest/models/admin_user_view_password_reset.py +++ /dev/null @@ -1,97 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewPasswordReset") - - -@_attrs_define -class AdminUserViewPasswordReset: - """ - Attributes: - id (UUID): - created_at (datetime.datetime): - used_at (datetime.datetime | None): - """ - - id: UUID - created_at: datetime.datetime - used_at: datetime.datetime | None - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - created_at = self.created_at.isoformat() - - used_at: None | str - if isinstance(self.used_at, datetime.datetime): - used_at = self.used_at.isoformat() - else: - used_at = self.used_at - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "createdAt": created_at, - "usedAt": used_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_used_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - used_at_type_1 = datetime.datetime.fromisoformat(data) - - return used_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - used_at = _parse_used_at(d.pop("usedAt")) - - admin_user_view_password_reset = cls( - id=id, - created_at=created_at, - used_at=used_at, - ) - - admin_user_view_password_reset.additional_properties = d - return admin_user_view_password_reset - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_shocker.py b/openshock/rest/models/admin_user_view_shocker.py deleted file mode 100644 index 996decd..0000000 --- a/openshock/rest/models/admin_user_view_shocker.py +++ /dev/null @@ -1,80 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewShocker") - - -@_attrs_define -class AdminUserViewShocker: - """ - Attributes: - id (UUID): - name (str): - created_at (datetime.datetime): - """ - - id: UUID - name: str - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - admin_user_view_shocker = cls( - id=id, - name=name, - created_at=created_at, - ) - - admin_user_view_shocker.additional_properties = d - return admin_user_view_shocker - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_activation_request.py b/openshock/rest/models/admin_user_view_user_activation_request.py deleted file mode 100644 index 89a85c8..0000000 --- a/openshock/rest/models/admin_user_view_user_activation_request.py +++ /dev/null @@ -1,71 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewUserActivationRequest") - - -@_attrs_define -class AdminUserViewUserActivationRequest: - """ - Attributes: - email_send_attempts (int): - created_at (datetime.datetime): - """ - - email_send_attempts: int - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - email_send_attempts = self.email_send_attempts - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "emailSendAttempts": email_send_attempts, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - email_send_attempts = d.pop("emailSendAttempts") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - admin_user_view_user_activation_request = cls( - email_send_attempts=email_send_attempts, - created_at=created_at, - ) - - admin_user_view_user_activation_request.additional_properties = d - return admin_user_view_user_activation_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_deactivation.py b/openshock/rest/models/admin_user_view_user_deactivation.py deleted file mode 100644 index a73d1b5..0000000 --- a/openshock/rest/models/admin_user_view_user_deactivation.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_user_view_user_ref import AdminUserViewUserRef - - -T = TypeVar("T", bound="AdminUserViewUserDeactivation") - - -@_attrs_define -class AdminUserViewUserDeactivation: - """ - Attributes: - deactivated_by (AdminUserViewUserRef): - scheduled_deletion_time (datetime.datetime | None): - deactivated_at (datetime.datetime): - """ - - deactivated_by: AdminUserViewUserRef - scheduled_deletion_time: datetime.datetime | None - deactivated_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - deactivated_by = self.deactivated_by.to_dict() - - scheduled_deletion_time: None | str - if isinstance(self.scheduled_deletion_time, datetime.datetime): - scheduled_deletion_time = self.scheduled_deletion_time.isoformat() - else: - scheduled_deletion_time = self.scheduled_deletion_time - - deactivated_at = self.deactivated_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "deactivatedBy": deactivated_by, - "scheduledDeletionTime": scheduled_deletion_time, - "deactivatedAt": deactivated_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_user_view_user_ref import AdminUserViewUserRef # noqa: PLC0415 - - d = dict(src_dict) - deactivated_by = AdminUserViewUserRef.from_dict(d.pop("deactivatedBy")) - - def _parse_scheduled_deletion_time(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - scheduled_deletion_time_type_1 = datetime.datetime.fromisoformat(data) - - return scheduled_deletion_time_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - scheduled_deletion_time = _parse_scheduled_deletion_time(d.pop("scheduledDeletionTime")) - - deactivated_at = datetime.datetime.fromisoformat(d.pop("deactivatedAt")) - - admin_user_view_user_deactivation = cls( - deactivated_by=deactivated_by, - scheduled_deletion_time=scheduled_deletion_time, - deactivated_at=deactivated_at, - ) - - admin_user_view_user_deactivation.additional_properties = d - return admin_user_view_user_deactivation - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_ref.py b/openshock/rest/models/admin_user_view_user_ref.py deleted file mode 100644 index 0faa90f..0000000 --- a/openshock/rest/models/admin_user_view_user_ref.py +++ /dev/null @@ -1,71 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewUserRef") - - -@_attrs_define -class AdminUserViewUserRef: - """ - Attributes: - id (UUID): - name (str): - """ - - id: UUID - name: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - admin_user_view_user_ref = cls( - id=id, - name=name, - ) - - admin_user_view_user_ref.additional_properties = d - return admin_user_view_user_ref - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_users_view.py b/openshock/rest/models/admin_users_view.py deleted file mode 100644 index 2dc3109..0000000 --- a/openshock/rest/models/admin_users_view.py +++ /dev/null @@ -1,304 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.password_hashing_algorithm import PasswordHashingAlgorithm -from ..models.role_type import RoleType - -T = TypeVar("T", bound="AdminUsersView") - - -@_attrs_define -class AdminUsersView: - """ - Attributes: - id (UUID): - name (str): - email (str): - password_hash_type (None | PasswordHashingAlgorithm): - roles (list[RoleType]): - created_at (datetime.datetime): - activated_at (datetime.datetime | None): - created_by_automation_token_id (None | UUID): - deactivated_at (datetime.datetime | None): - deactivated_by_user_id (None | UUID): - api_token_count (int): - password_reset_count (int): - shocker_user_share_count (int): - shocker_public_share_count (int): - email_change_request_count (int): - name_change_request_count (int): - device_count (int): - shocker_count (int): - shocker_control_log_count (int): - """ - - id: UUID - name: str - email: str - password_hash_type: None | PasswordHashingAlgorithm - roles: list[RoleType] - created_at: datetime.datetime - activated_at: datetime.datetime | None - created_by_automation_token_id: None | UUID - deactivated_at: datetime.datetime | None - deactivated_by_user_id: None | UUID - api_token_count: int - password_reset_count: int - shocker_user_share_count: int - shocker_public_share_count: int - email_change_request_count: int - name_change_request_count: int - device_count: int - shocker_count: int - shocker_control_log_count: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - email = self.email - - password_hash_type: None | str - if isinstance(self.password_hash_type, PasswordHashingAlgorithm): - password_hash_type = self.password_hash_type.value - else: - password_hash_type = self.password_hash_type - - roles = [] - for roles_item_data in self.roles: - roles_item = roles_item_data.value - roles.append(roles_item) - - created_at = self.created_at.isoformat() - - activated_at: None | str - if isinstance(self.activated_at, datetime.datetime): - activated_at = self.activated_at.isoformat() - else: - activated_at = self.activated_at - - created_by_automation_token_id: None | str - if isinstance(self.created_by_automation_token_id, UUID): - created_by_automation_token_id = str(self.created_by_automation_token_id) - else: - created_by_automation_token_id = self.created_by_automation_token_id - - deactivated_at: None | str - if isinstance(self.deactivated_at, datetime.datetime): - deactivated_at = self.deactivated_at.isoformat() - else: - deactivated_at = self.deactivated_at - - deactivated_by_user_id: None | str - if isinstance(self.deactivated_by_user_id, UUID): - deactivated_by_user_id = str(self.deactivated_by_user_id) - else: - deactivated_by_user_id = self.deactivated_by_user_id - - api_token_count = self.api_token_count - - password_reset_count = self.password_reset_count - - shocker_user_share_count = self.shocker_user_share_count - - shocker_public_share_count = self.shocker_public_share_count - - email_change_request_count = self.email_change_request_count - - name_change_request_count = self.name_change_request_count - - device_count = self.device_count - - shocker_count = self.shocker_count - - shocker_control_log_count = self.shocker_control_log_count - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "email": email, - "passwordHashType": password_hash_type, - "roles": roles, - "createdAt": created_at, - "activatedAt": activated_at, - "createdByAutomationTokenId": created_by_automation_token_id, - "deactivatedAt": deactivated_at, - "deactivatedByUserId": deactivated_by_user_id, - "apiTokenCount": api_token_count, - "passwordResetCount": password_reset_count, - "shockerUserShareCount": shocker_user_share_count, - "shockerPublicShareCount": shocker_public_share_count, - "emailChangeRequestCount": email_change_request_count, - "nameChangeRequestCount": name_change_request_count, - "deviceCount": device_count, - "shockerCount": shocker_count, - "shockerControlLogCount": shocker_control_log_count, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - email = d.pop("email") - - def _parse_password_hash_type(data: object) -> None | PasswordHashingAlgorithm: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - password_hash_type_type_1 = PasswordHashingAlgorithm(data) - - return password_hash_type_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | PasswordHashingAlgorithm, data) - - password_hash_type = _parse_password_hash_type(d.pop("passwordHashType")) - - roles = [] - _roles = d.pop("roles") - for roles_item_data in _roles: - roles_item = RoleType(roles_item_data) - - roles.append(roles_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_activated_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - activated_at_type_1 = datetime.datetime.fromisoformat(data) - - return activated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - activated_at = _parse_activated_at(d.pop("activatedAt")) - - def _parse_created_by_automation_token_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - created_by_automation_token_id_type_1 = UUID(data) - - return created_by_automation_token_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) - - def _parse_deactivated_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - deactivated_at_type_1 = datetime.datetime.fromisoformat(data) - - return deactivated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - deactivated_at = _parse_deactivated_at(d.pop("deactivatedAt")) - - def _parse_deactivated_by_user_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - deactivated_by_user_id_type_1 = UUID(data) - - return deactivated_by_user_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - deactivated_by_user_id = _parse_deactivated_by_user_id(d.pop("deactivatedByUserId")) - - api_token_count = d.pop("apiTokenCount") - - password_reset_count = d.pop("passwordResetCount") - - shocker_user_share_count = d.pop("shockerUserShareCount") - - shocker_public_share_count = d.pop("shockerPublicShareCount") - - email_change_request_count = d.pop("emailChangeRequestCount") - - name_change_request_count = d.pop("nameChangeRequestCount") - - device_count = d.pop("deviceCount") - - shocker_count = d.pop("shockerCount") - - shocker_control_log_count = d.pop("shockerControlLogCount") - - admin_users_view = cls( - id=id, - name=name, - email=email, - password_hash_type=password_hash_type, - roles=roles, - created_at=created_at, - activated_at=activated_at, - created_by_automation_token_id=created_by_automation_token_id, - deactivated_at=deactivated_at, - deactivated_by_user_id=deactivated_by_user_id, - api_token_count=api_token_count, - password_reset_count=password_reset_count, - shocker_user_share_count=shocker_user_share_count, - shocker_public_share_count=shocker_public_share_count, - email_change_request_count=email_change_request_count, - name_change_request_count=name_change_request_count, - device_count=device_count, - shocker_count=shocker_count, - shocker_control_log_count=shocker_control_log_count, - ) - - admin_users_view.additional_properties = d - return admin_users_view - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_action.py b/openshock/rest/models/audit_action.py deleted file mode 100644 index e7bcff5..0000000 --- a/openshock/rest/models/audit_action.py +++ /dev/null @@ -1,26 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditAction(StrEnum): - ACCOUNTDEACTIVATED = "AccountDeactivated" - ACCOUNTDELETED = "AccountDeleted" - ACCOUNTREACTIVATED = "AccountReactivated" - APITOKENCREATED = "ApiTokenCreated" - APITOKENDELETED = "ApiTokenDeleted" - AUTOMATIONTOKENCREATED = "AutomationTokenCreated" - AUTOMATIONTOKENDELETED = "AutomationTokenDeleted" - AUTOMATIONTOKENROTATED = "AutomationTokenRotated" - AUTOMATIONTOKENUPDATED = "AutomationTokenUpdated" - AUTOMATIONTOKENUSED = "AutomationTokenUsed" - EMAILCHANGED = "EmailChanged" - EMAILCHANGEREQUESTED = "EmailChangeRequested" - LOGIN = "Login" - LOGOUT = "Logout" - OAUTHCONNECTED = "OAuthConnected" - OAUTHDISCONNECTED = "OAuthDisconnected" - PASSWORDCHANGED = "PasswordChanged" - USERNAMECHANGED = "UsernameChanged" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_log_entry_response.py b/openshock/rest/models/audit_log_entry_response.py deleted file mode 100644 index 382f07a..0000000 --- a/openshock/rest/models/audit_log_entry_response.py +++ /dev/null @@ -1,432 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_action import AuditAction - -if TYPE_CHECKING: - from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata - from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata - from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata - from ..models.audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata - from ..models.audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata - from ..models.audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata - from ..models.audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata - from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata - from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata - from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata - from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata - from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata - from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata - from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata - - -T = TypeVar("T", bound="AuditLogEntryResponse") - - -@_attrs_define -class AuditLogEntryResponse: - """ - Attributes: - id (UUID): - user_id (UUID): - actor_id (None | UUID): - action (AuditAction): - reason (None | str): - ip_address (None | str): An IPv4 or IPv6 address in its textual form. - user_agent (None | str): - metadata (AuditMetadataAccountDeactivatedMetadata | AuditMetadataApiTokenCreatedMetadata | - AuditMetadataApiTokenDeletedMetadata | AuditMetadataAutomationTokenCreatedMetadata | - AuditMetadataAutomationTokenDeletedMetadata | AuditMetadataAutomationTokenRotatedMetadata | - AuditMetadataAutomationTokenUpdatedMetadata | AuditMetadataAutomationTokenUsedMetadata | - AuditMetadataEmailChangedMetadata | AuditMetadataEmailChangeRequestedMetadata | AuditMetadataLoginMetadata | - AuditMetadataOAuthConnectedMetadata | AuditMetadataOAuthDisconnectedMetadata | - AuditMetadataUsernameChangedMetadata | None): - created_at (datetime.datetime): - """ - - id: UUID - user_id: UUID - actor_id: None | UUID - action: AuditAction - reason: None | str - ip_address: None | str - user_agent: None | str - metadata: ( - AuditMetadataAccountDeactivatedMetadata - | AuditMetadataApiTokenCreatedMetadata - | AuditMetadataApiTokenDeletedMetadata - | AuditMetadataAutomationTokenCreatedMetadata - | AuditMetadataAutomationTokenDeletedMetadata - | AuditMetadataAutomationTokenRotatedMetadata - | AuditMetadataAutomationTokenUpdatedMetadata - | AuditMetadataAutomationTokenUsedMetadata - | AuditMetadataEmailChangedMetadata - | AuditMetadataEmailChangeRequestedMetadata - | AuditMetadataLoginMetadata - | AuditMetadataOAuthConnectedMetadata - | AuditMetadataOAuthDisconnectedMetadata - | AuditMetadataUsernameChangedMetadata - | None - ) - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 - from ..models.audit_metadata_automation_token_created_metadata import ( - AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_deleted_metadata import ( - AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_rotated_metadata import ( - AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_updated_metadata import ( - AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 - from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 - - id = str(self.id) - - user_id = str(self.user_id) - - actor_id: None | str - if isinstance(self.actor_id, UUID): - actor_id = str(self.actor_id) - else: - actor_id = self.actor_id - - action = self.action.value - - reason: None | str - reason = self.reason - - ip_address: None | str - ip_address = self.ip_address - - user_agent: None | str - user_agent = self.user_agent - - metadata: dict[str, Any] | None - if isinstance(self.metadata, AuditMetadataLoginMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataUsernameChangedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataEmailChangeRequestedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataEmailChangedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataApiTokenCreatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataApiTokenDeletedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataOAuthConnectedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataOAuthDisconnectedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAccountDeactivatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenCreatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenUpdatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenRotatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenDeletedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenUsedMetadata): - metadata = self.metadata.to_dict() - else: - metadata = self.metadata - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "userId": user_id, - "actorId": actor_id, - "action": action, - "reason": reason, - "ipAddress": ip_address, - "userAgent": user_agent, - "metadata": metadata, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 - from ..models.audit_metadata_automation_token_created_metadata import ( - AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_deleted_metadata import ( - AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_rotated_metadata import ( - AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_updated_metadata import ( - AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 - from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - user_id = UUID(d.pop("userId")) - - def _parse_actor_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - actor_id_type_1 = UUID(data) - - return actor_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - actor_id = _parse_actor_id(d.pop("actorId")) - - action = AuditAction(d.pop("action")) - - def _parse_reason(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - reason = _parse_reason(d.pop("reason")) - - def _parse_ip_address(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - ip_address = _parse_ip_address(d.pop("ipAddress")) - - def _parse_user_agent(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - user_agent = _parse_user_agent(d.pop("userAgent")) - - def _parse_metadata( - data: object, - ) -> ( - AuditMetadataAccountDeactivatedMetadata - | AuditMetadataApiTokenCreatedMetadata - | AuditMetadataApiTokenDeletedMetadata - | AuditMetadataAutomationTokenCreatedMetadata - | AuditMetadataAutomationTokenDeletedMetadata - | AuditMetadataAutomationTokenRotatedMetadata - | AuditMetadataAutomationTokenUpdatedMetadata - | AuditMetadataAutomationTokenUsedMetadata - | AuditMetadataEmailChangedMetadata - | AuditMetadataEmailChangeRequestedMetadata - | AuditMetadataLoginMetadata - | AuditMetadataOAuthConnectedMetadata - | AuditMetadataOAuthDisconnectedMetadata - | AuditMetadataUsernameChangedMetadata - | None - ): - if data is None: - return data - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_0 = AuditMetadataLoginMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_0 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_1 = AuditMetadataUsernameChangedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_2 = AuditMetadataEmailChangeRequestedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_2 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_3 = AuditMetadataEmailChangedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_3 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_4 = AuditMetadataApiTokenCreatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_4 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_5 = AuditMetadataApiTokenDeletedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_5 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_6 = AuditMetadataOAuthConnectedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_6 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_7 = AuditMetadataOAuthDisconnectedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_7 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_8 = AuditMetadataAccountDeactivatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_8 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_9 = AuditMetadataAutomationTokenCreatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_9 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_10 = AuditMetadataAutomationTokenUpdatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_10 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_11 = AuditMetadataAutomationTokenRotatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_11 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_12 = AuditMetadataAutomationTokenDeletedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_12 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_13 = AuditMetadataAutomationTokenUsedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_13 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast( - AuditMetadataAccountDeactivatedMetadata - | AuditMetadataApiTokenCreatedMetadata - | AuditMetadataApiTokenDeletedMetadata - | AuditMetadataAutomationTokenCreatedMetadata - | AuditMetadataAutomationTokenDeletedMetadata - | AuditMetadataAutomationTokenRotatedMetadata - | AuditMetadataAutomationTokenUpdatedMetadata - | AuditMetadataAutomationTokenUsedMetadata - | AuditMetadataEmailChangedMetadata - | AuditMetadataEmailChangeRequestedMetadata - | AuditMetadataLoginMetadata - | AuditMetadataOAuthConnectedMetadata - | AuditMetadataOAuthDisconnectedMetadata - | AuditMetadataUsernameChangedMetadata - | None, - data, - ) - - metadata = _parse_metadata(d.pop("metadata")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - audit_log_entry_response = cls( - id=id, - user_id=user_id, - actor_id=actor_id, - action=action, - reason=reason, - ip_address=ip_address, - user_agent=user_agent, - metadata=metadata, - created_at=created_at, - ) - - audit_log_entry_response.additional_properties = d - return audit_log_entry_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata.py deleted file mode 100644 index 0c04186..0000000 --- a/openshock/rest/models/audit_metadata_account_deactivated_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAccountDeactivatedMetadata") - - -@_attrs_define -class AuditMetadataAccountDeactivatedMetadata: - """ - Attributes: - delete_later (bool): - t (AuditMetadataAccountDeactivatedMetadataT | Unset): - """ - - delete_later: bool - t: AuditMetadataAccountDeactivatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - delete_later = self.delete_later - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "deleteLater": delete_later, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - delete_later = d.pop("deleteLater") - - _t = d.pop("t", UNSET) - t: AuditMetadataAccountDeactivatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAccountDeactivatedMetadataT(_t) - - audit_metadata_account_deactivated_metadata = cls( - delete_later=delete_later, - t=t, - ) - - audit_metadata_account_deactivated_metadata.additional_properties = d - return audit_metadata_account_deactivated_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py deleted file mode 100644 index f5a287d..0000000 --- a/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAccountDeactivatedMetadataT(StrEnum): - ACCOUNTDEACTIVATED = "accountDeactivated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata.py b/openshock/rest/models/audit_metadata_api_token_created_metadata.py deleted file mode 100644 index f813d7f..0000000 --- a/openshock/rest/models/audit_metadata_api_token_created_metadata.py +++ /dev/null @@ -1,98 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataApiTokenCreatedMetadata") - - -@_attrs_define -class AuditMetadataApiTokenCreatedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - permissions (list[str]): - t (AuditMetadataApiTokenCreatedMetadataT | Unset): - """ - - token_id: UUID - name: str - permissions: list[str] - t: AuditMetadataApiTokenCreatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - permissions = self.permissions - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "permissions": permissions, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - permissions = cast(list[str], d.pop("permissions")) - - _t = d.pop("t", UNSET) - t: AuditMetadataApiTokenCreatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataApiTokenCreatedMetadataT(_t) - - audit_metadata_api_token_created_metadata = cls( - token_id=token_id, - name=name, - permissions=permissions, - t=t, - ) - - audit_metadata_api_token_created_metadata.additional_properties = d - return audit_metadata_api_token_created_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py deleted file mode 100644 index 59024ee..0000000 --- a/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataApiTokenCreatedMetadataT(StrEnum): - APITOKENCREATED = "apiTokenCreated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py deleted file mode 100644 index 1087190..0000000 --- a/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py +++ /dev/null @@ -1,90 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataApiTokenDeletedMetadata") - - -@_attrs_define -class AuditMetadataApiTokenDeletedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - t (AuditMetadataApiTokenDeletedMetadataT | Unset): - """ - - token_id: UUID - name: str - t: AuditMetadataApiTokenDeletedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - _t = d.pop("t", UNSET) - t: AuditMetadataApiTokenDeletedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataApiTokenDeletedMetadataT(_t) - - audit_metadata_api_token_deleted_metadata = cls( - token_id=token_id, - name=name, - t=t, - ) - - audit_metadata_api_token_deleted_metadata.additional_properties = d - return audit_metadata_api_token_deleted_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py deleted file mode 100644 index de49448..0000000 --- a/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataApiTokenDeletedMetadataT(StrEnum): - APITOKENDELETED = "apiTokenDeleted" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata.py deleted file mode 100644 index 78c3add..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_created_metadata.py +++ /dev/null @@ -1,120 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenCreatedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenCreatedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - types (list[str]): - auto_cleanup_users (bool): - auto_cleanup_after (None | str): - t (AuditMetadataAutomationTokenCreatedMetadataT | Unset): - """ - - token_id: UUID - name: str - types: list[str] - auto_cleanup_users: bool - auto_cleanup_after: None | str - t: AuditMetadataAutomationTokenCreatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - types = self.types - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str - auto_cleanup_after = self.auto_cleanup_after - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "types": types, - "autoCleanupUsers": auto_cleanup_users, - "autoCleanupAfter": auto_cleanup_after, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - types = cast(list[str], d.pop("types")) - - auto_cleanup_users = d.pop("autoCleanupUsers") - - def _parse_auto_cleanup_after(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenCreatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenCreatedMetadataT(_t) - - audit_metadata_automation_token_created_metadata = cls( - token_id=token_id, - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - t=t, - ) - - audit_metadata_automation_token_created_metadata.additional_properties = d - return audit_metadata_automation_token_created_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py deleted file mode 100644 index 71728a5..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenCreatedMetadataT(StrEnum): - AUTOMATIONTOKENCREATED = "automationTokenCreated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py deleted file mode 100644 index 98e47b2..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py +++ /dev/null @@ -1,99 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenDeletedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenDeletedMetadata: - """The token was deleted together with the int AutomationTokenDeletedMetadata.DeletedAccountCount accounts it created. - - Attributes: - token_id (UUID): - name (str): - deleted_account_count (int): - t (AuditMetadataAutomationTokenDeletedMetadataT | Unset): - """ - - token_id: UUID - name: str - deleted_account_count: int - t: AuditMetadataAutomationTokenDeletedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - deleted_account_count = self.deleted_account_count - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "deletedAccountCount": deleted_account_count, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - deleted_account_count = d.pop("deletedAccountCount") - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenDeletedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenDeletedMetadataT(_t) - - audit_metadata_automation_token_deleted_metadata = cls( - token_id=token_id, - name=name, - deleted_account_count=deleted_account_count, - t=t, - ) - - audit_metadata_automation_token_deleted_metadata.additional_properties = d - return audit_metadata_automation_token_deleted_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py deleted file mode 100644 index 6e81913..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenDeletedMetadataT(StrEnum): - AUTOMATIONTOKENDELETED = "automationTokenDeleted" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py deleted file mode 100644 index 86b917e..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py +++ /dev/null @@ -1,90 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenRotatedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenRotatedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - t (AuditMetadataAutomationTokenRotatedMetadataT | Unset): - """ - - token_id: UUID - name: str - t: AuditMetadataAutomationTokenRotatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenRotatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenRotatedMetadataT(_t) - - audit_metadata_automation_token_rotated_metadata = cls( - token_id=token_id, - name=name, - t=t, - ) - - audit_metadata_automation_token_rotated_metadata.additional_properties = d - return audit_metadata_automation_token_rotated_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py deleted file mode 100644 index b9df839..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenRotatedMetadataT(StrEnum): - AUTOMATIONTOKENROTATED = "automationTokenRotated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py deleted file mode 100644 index 083f9d7..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py +++ /dev/null @@ -1,121 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenUpdatedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenUpdatedMetadata: - """The token's settings after the update. - - Attributes: - token_id (UUID): - name (str): - types (list[str]): - auto_cleanup_users (bool): - auto_cleanup_after (None | str): - t (AuditMetadataAutomationTokenUpdatedMetadataT | Unset): - """ - - token_id: UUID - name: str - types: list[str] - auto_cleanup_users: bool - auto_cleanup_after: None | str - t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - types = self.types - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str - auto_cleanup_after = self.auto_cleanup_after - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "types": types, - "autoCleanupUsers": auto_cleanup_users, - "autoCleanupAfter": auto_cleanup_after, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - types = cast(list[str], d.pop("types")) - - auto_cleanup_users = d.pop("autoCleanupUsers") - - def _parse_auto_cleanup_after(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenUpdatedMetadataT(_t) - - audit_metadata_automation_token_updated_metadata = cls( - token_id=token_id, - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - t=t, - ) - - audit_metadata_automation_token_updated_metadata.additional_properties = d - return audit_metadata_automation_token_updated_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py deleted file mode 100644 index e47bd5e..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenUpdatedMetadataT(StrEnum): - AUTOMATIONTOKENUPDATED = "automationTokenUpdated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata.py deleted file mode 100644 index d9bba52..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_used_metadata.py +++ /dev/null @@ -1,100 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenUsedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenUsedMetadata: - """An automation token was used on this account. string AutomationTokenUsedMetadata.Flow is a `AutomationTokenFlow` - name. - - Attributes: - token_id (UUID): - name (str): - flow (str): - t (AuditMetadataAutomationTokenUsedMetadataT | Unset): - """ - - token_id: UUID - name: str - flow: str - t: AuditMetadataAutomationTokenUsedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - flow = self.flow - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "flow": flow, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - flow = d.pop("flow") - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenUsedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenUsedMetadataT(_t) - - audit_metadata_automation_token_used_metadata = cls( - token_id=token_id, - name=name, - flow=flow, - t=t, - ) - - audit_metadata_automation_token_used_metadata.additional_properties = d - return audit_metadata_automation_token_used_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py deleted file mode 100644 index 591cb62..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenUsedMetadataT(StrEnum): - AUTOMATIONTOKENUSED = "automationTokenUsed" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata.py deleted file mode 100644 index c1e7b8a..0000000 --- a/openshock/rest/models/audit_metadata_email_change_requested_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataEmailChangeRequestedMetadata") - - -@_attrs_define -class AuditMetadataEmailChangeRequestedMetadata: - """ - Attributes: - new_email (str): - t (AuditMetadataEmailChangeRequestedMetadataT | Unset): - """ - - new_email: str - t: AuditMetadataEmailChangeRequestedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - new_email = self.new_email - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "newEmail": new_email, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - new_email = d.pop("newEmail") - - _t = d.pop("t", UNSET) - t: AuditMetadataEmailChangeRequestedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataEmailChangeRequestedMetadataT(_t) - - audit_metadata_email_change_requested_metadata = cls( - new_email=new_email, - t=t, - ) - - audit_metadata_email_change_requested_metadata.additional_properties = d - return audit_metadata_email_change_requested_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py deleted file mode 100644 index 5cf3cd0..0000000 --- a/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataEmailChangeRequestedMetadataT(StrEnum): - EMAILCHANGEREQUESTED = "emailChangeRequested" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata.py b/openshock/rest/models/audit_metadata_email_changed_metadata.py deleted file mode 100644 index 59f2ac4..0000000 --- a/openshock/rest/models/audit_metadata_email_changed_metadata.py +++ /dev/null @@ -1,89 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataEmailChangedMetadata") - - -@_attrs_define -class AuditMetadataEmailChangedMetadata: - """ - Attributes: - old (str): - new (str): - t (AuditMetadataEmailChangedMetadataT | Unset): - """ - - old: str - new: str - t: AuditMetadataEmailChangedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - old = self.old - - new = self.new - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "old": old, - "new": new, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - old = d.pop("old") - - new = d.pop("new") - - _t = d.pop("t", UNSET) - t: AuditMetadataEmailChangedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataEmailChangedMetadataT(_t) - - audit_metadata_email_changed_metadata = cls( - old=old, - new=new, - t=t, - ) - - audit_metadata_email_changed_metadata.additional_properties = d - return audit_metadata_email_changed_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata_t.py b/openshock/rest/models/audit_metadata_email_changed_metadata_t.py deleted file mode 100644 index 1bcee56..0000000 --- a/openshock/rest/models/audit_metadata_email_changed_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataEmailChangedMetadataT(StrEnum): - EMAILCHANGED = "emailChanged" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_login_metadata.py b/openshock/rest/models/audit_metadata_login_metadata.py deleted file mode 100644 index 56879d2..0000000 --- a/openshock/rest/models/audit_metadata_login_metadata.py +++ /dev/null @@ -1,82 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataLoginMetadata") - - -@_attrs_define -class AuditMetadataLoginMetadata: - """ - Attributes: - session_id (UUID): - t (AuditMetadataLoginMetadataT | Unset): - """ - - session_id: UUID - t: AuditMetadataLoginMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - session_id = str(self.session_id) - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "sessionId": session_id, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - session_id = UUID(d.pop("sessionId")) - - _t = d.pop("t", UNSET) - t: AuditMetadataLoginMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataLoginMetadataT(_t) - - audit_metadata_login_metadata = cls( - session_id=session_id, - t=t, - ) - - audit_metadata_login_metadata.additional_properties = d - return audit_metadata_login_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_login_metadata_t.py b/openshock/rest/models/audit_metadata_login_metadata_t.py deleted file mode 100644 index d98a11a..0000000 --- a/openshock/rest/models/audit_metadata_login_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataLoginMetadataT(StrEnum): - LOGIN = "login" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py deleted file mode 100644 index 96f4469..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataOAuthConnectedMetadata") - - -@_attrs_define -class AuditMetadataOAuthConnectedMetadata: - """ - Attributes: - provider (str): - t (AuditMetadataOAuthConnectedMetadataT | Unset): - """ - - provider: str - t: AuditMetadataOAuthConnectedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - provider = self.provider - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "provider": provider, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - provider = d.pop("provider") - - _t = d.pop("t", UNSET) - t: AuditMetadataOAuthConnectedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataOAuthConnectedMetadataT(_t) - - audit_metadata_o_auth_connected_metadata = cls( - provider=provider, - t=t, - ) - - audit_metadata_o_auth_connected_metadata.additional_properties = d - return audit_metadata_o_auth_connected_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py deleted file mode 100644 index 6d80bfc..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataOAuthConnectedMetadataT(StrEnum): - OAUTHCONNECTED = "oauthConnected" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py deleted file mode 100644 index b7ee896..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataOAuthDisconnectedMetadata") - - -@_attrs_define -class AuditMetadataOAuthDisconnectedMetadata: - """ - Attributes: - provider (str): - t (AuditMetadataOAuthDisconnectedMetadataT | Unset): - """ - - provider: str - t: AuditMetadataOAuthDisconnectedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - provider = self.provider - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "provider": provider, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - provider = d.pop("provider") - - _t = d.pop("t", UNSET) - t: AuditMetadataOAuthDisconnectedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataOAuthDisconnectedMetadataT(_t) - - audit_metadata_o_auth_disconnected_metadata = cls( - provider=provider, - t=t, - ) - - audit_metadata_o_auth_disconnected_metadata.additional_properties = d - return audit_metadata_o_auth_disconnected_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py deleted file mode 100644 index c528f73..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataOAuthDisconnectedMetadataT(StrEnum): - OAUTHDISCONNECTED = "oauthDisconnected" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata.py b/openshock/rest/models/audit_metadata_username_changed_metadata.py deleted file mode 100644 index a1ee8ea..0000000 --- a/openshock/rest/models/audit_metadata_username_changed_metadata.py +++ /dev/null @@ -1,89 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataUsernameChangedMetadata") - - -@_attrs_define -class AuditMetadataUsernameChangedMetadata: - """ - Attributes: - old (str): - new (str): - t (AuditMetadataUsernameChangedMetadataT | Unset): - """ - - old: str - new: str - t: AuditMetadataUsernameChangedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - old = self.old - - new = self.new - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "old": old, - "new": new, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - old = d.pop("old") - - new = d.pop("new") - - _t = d.pop("t", UNSET) - t: AuditMetadataUsernameChangedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataUsernameChangedMetadataT(_t) - - audit_metadata_username_changed_metadata = cls( - old=old, - new=new, - t=t, - ) - - audit_metadata_username_changed_metadata.additional_properties = d - return audit_metadata_username_changed_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata_t.py b/openshock/rest/models/audit_metadata_username_changed_metadata_t.py deleted file mode 100644 index 84465c1..0000000 --- a/openshock/rest/models/audit_metadata_username_changed_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataUsernameChangedMetadataT(StrEnum): - USERNAMECHANGED = "usernameChanged" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/automation_token_dto.py b/openshock/rest/models/automation_token_dto.py deleted file mode 100644 index 224cf7a..0000000 --- a/openshock/rest/models/automation_token_dto.py +++ /dev/null @@ -1,197 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AutomationTokenDto") - - -@_attrs_define -class AutomationTokenDto: - """ - Attributes: - id (UUID): - name (str): - types (list[AutomationTokenType]): - created_at (datetime.datetime): - last_used_at (datetime.datetime | None | Unset): - last_rotated_at (datetime.datetime | None | Unset): - use_count (int | Unset): - auto_cleanup_users (bool | Unset): - auto_cleanup_after (None | str | Unset): - """ - - id: UUID - name: str - types: list[AutomationTokenType] - created_at: datetime.datetime - last_used_at: datetime.datetime | None | Unset = UNSET - last_rotated_at: datetime.datetime | None | Unset = UNSET - use_count: int | Unset = UNSET - auto_cleanup_users: bool | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - types = [] - for types_item_data in self.types: - types_item = types_item_data.value - types.append(types_item) - - created_at = self.created_at.isoformat() - - last_used_at: None | str | Unset - if isinstance(self.last_used_at, Unset): - last_used_at = UNSET - elif isinstance(self.last_used_at, datetime.datetime): - last_used_at = self.last_used_at.isoformat() - else: - last_used_at = self.last_used_at - - last_rotated_at: None | str | Unset - if isinstance(self.last_rotated_at, Unset): - last_rotated_at = UNSET - elif isinstance(self.last_rotated_at, datetime.datetime): - last_rotated_at = self.last_rotated_at.isoformat() - else: - last_rotated_at = self.last_rotated_at - - use_count = self.use_count - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "types": types, - "createdAt": created_at, - } - ) - if last_used_at is not UNSET: - field_dict["lastUsedAt"] = last_used_at - if last_rotated_at is not UNSET: - field_dict["lastRotatedAt"] = last_rotated_at - if use_count is not UNSET: - field_dict["useCount"] = use_count - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - types = [] - _types = d.pop("types") - for types_item_data in _types: - types_item = AutomationTokenType(types_item_data) - - types.append(types_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_last_used_at(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_at_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - last_used_at = _parse_last_used_at(d.pop("lastUsedAt", UNSET)) - - def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) - - return last_rotated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) - - use_count = d.pop("useCount", UNSET) - - auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - automation_token_dto = cls( - id=id, - name=name, - types=types, - created_at=created_at, - last_used_at=last_used_at, - last_rotated_at=last_rotated_at, - use_count=use_count, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - automation_token_dto.additional_properties = d - return automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/automation_token_type.py b/openshock/rest/models/automation_token_type.py deleted file mode 100644 index b270e30..0000000 --- a/openshock/rest/models/automation_token_type.py +++ /dev/null @@ -1,11 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AutomationTokenType(StrEnum): - CONTROLSTATSREAD = "ControlStatsRead" - RATELIMIT = "RateLimit" - TURNSTILE = "Turnstile" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/change_email_request.py b/openshock/rest/models/change_email_request.py deleted file mode 100644 index 918e9c6..0000000 --- a/openshock/rest/models/change_email_request.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="ChangeEmailRequest") - - -@_attrs_define -class ChangeEmailRequest: - """ - Attributes: - current_password (str): - email (str): - """ - - current_password: str - email: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - current_password = self.current_password - - email = self.email - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "currentPassword": current_password, - "email": email, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - current_password = d.pop("currentPassword") - - email = d.pop("email") - - change_email_request = cls( - current_password=current_password, - email=email, - ) - - change_email_request.additional_properties = d - return change_email_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/change_password_request.py b/openshock/rest/models/change_password_request.py deleted file mode 100644 index 6337c0e..0000000 --- a/openshock/rest/models/change_password_request.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="ChangePasswordRequest") - - -@_attrs_define -class ChangePasswordRequest: - """ - Attributes: - current_password (str): - new_password (str): - """ - - current_password: str - new_password: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - current_password = self.current_password - - new_password = self.new_password - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "currentPassword": current_password, - "newPassword": new_password, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - current_password = d.pop("currentPassword") - - new_password = d.pop("newPassword") - - change_password_request = cls( - current_password=current_password, - new_password=new_password, - ) - - change_password_request.additional_properties = d - return change_password_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_add_item_request.py b/openshock/rest/models/configuration_add_item_request.py deleted file mode 100644 index a2650e7..0000000 --- a/openshock/rest/models/configuration_add_item_request.py +++ /dev/null @@ -1,91 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.configuration_value_type import ConfigurationValueType - -T = TypeVar("T", bound="ConfigurationAddItemRequest") - - -@_attrs_define -class ConfigurationAddItemRequest: - """Request DTO for adding a new configuration item. - - Attributes: - name (str): The unique name of the configuration item. - Must consist of uppercase letters and underscores only. - description (str): A human-readable description of the configuration item’s purpose. - type_ (ConfigurationValueType): - value (str): The initial value for the configuration item, serialized as a string. - Must conform to the format required by ConfigurationValueType ConfigurationAddItemRequest.Type. - """ - - name: str - description: str - type_: ConfigurationValueType - value: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - description = self.description - - type_ = self.type_.value - - value = self.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "description": description, - "type": type_, - "value": value, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - description = d.pop("description") - - type_ = ConfigurationValueType(d.pop("type")) - - value = d.pop("value") - - configuration_add_item_request = cls( - name=name, - description=description, - type_=type_, - value=value, - ) - - configuration_add_item_request.additional_properties = d - return configuration_add_item_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_item_dto.py b/openshock/rest/models/configuration_item_dto.py deleted file mode 100644 index 428129b..0000000 --- a/openshock/rest/models/configuration_item_dto.py +++ /dev/null @@ -1,106 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.configuration_value_type import ConfigurationValueType - -T = TypeVar("T", bound="ConfigurationItemDto") - - -@_attrs_define -class ConfigurationItemDto: - """Data transfer object representing a configuration item. - - Attributes: - name (str): The unique name of the configuration item. - description (str): A human-readable description of what this configuration item controls. - type_ (ConfigurationValueType): - value (str): The current value of the configuration item, serialized as a string. - updated_at (datetime.datetime): The timestamp when the configuration was last updated. - created_at (datetime.datetime): The timestamp when the configuration was originally created. - """ - - name: str - description: str - type_: ConfigurationValueType - value: str - updated_at: datetime.datetime - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - description = self.description - - type_ = self.type_.value - - value = self.value - - updated_at = self.updated_at.isoformat() - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "description": description, - "type": type_, - "value": value, - "updatedAt": updated_at, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - description = d.pop("description") - - type_ = ConfigurationValueType(d.pop("type")) - - value = d.pop("value") - - updated_at = datetime.datetime.fromisoformat(d.pop("updatedAt")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - configuration_item_dto = cls( - name=name, - description=description, - type_=type_, - value=value, - updated_at=updated_at, - created_at=created_at, - ) - - configuration_item_dto.additional_properties = d - return configuration_item_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_update_item_request.py b/openshock/rest/models/configuration_update_item_request.py deleted file mode 100644 index a2bb38b..0000000 --- a/openshock/rest/models/configuration_update_item_request.py +++ /dev/null @@ -1,110 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -T = TypeVar("T", bound="ConfigurationUpdateItemRequest") - - -@_attrs_define -class ConfigurationUpdateItemRequest: - """Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? ConfigurationUpdateItemRequest.Value (or both) - may be provided. - If both are null, no update action is performed. - - Attributes: - name (str): The name of the configuration item to update. - Must consist only of uppercase letters and underscores. - description (None | str | Unset): (Optional) New description for the configuration item. - value (None | str | Unset): (Optional) New value for the configuration item. - Must match the format expected by its existing ConfigurationValueType. - """ - - name: str - description: None | str | Unset = UNSET - value: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - description: None | str | Unset - if isinstance(self.description, Unset): - description = UNSET - else: - description = self.description - - value: None | str | Unset - if isinstance(self.value, Unset): - value = UNSET - else: - value = self.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - } - ) - if description is not UNSET: - field_dict["description"] = description - if value is not UNSET: - field_dict["value"] = value - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - def _parse_description(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - description = _parse_description(d.pop("description", UNSET)) - - def _parse_value(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - value = _parse_value(d.pop("value", UNSET)) - - configuration_update_item_request = cls( - name=name, - description=description, - value=value, - ) - - configuration_update_item_request.additional_properties = d - return configuration_update_item_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_value_type.py b/openshock/rest/models/configuration_value_type.py deleted file mode 100644 index b809802..0000000 --- a/openshock/rest/models/configuration_value_type.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class ConfigurationValueType(StrEnum): - BOOL = "Bool" - FLOAT = "Float" - INT = "Int" - JSON = "Json" - STRING = "String" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/create_automation_token_dto.py b/openshock/rest/models/create_automation_token_dto.py deleted file mode 100644 index 00e0bf8..0000000 --- a/openshock/rest/models/create_automation_token_dto.py +++ /dev/null @@ -1,112 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="CreateAutomationTokenDto") - - -@_attrs_define -class CreateAutomationTokenDto: - """ - Attributes: - name (str): - types (list[AutomationTokenType]): - auto_cleanup_users (bool | Unset): Whether the automated accounts this token creates are deleted once TimeSpan? - CreateAutomationTokenDto.AutoCleanupAfter has - passed since they were created. Off by default; accounts the token didn't create are never deleted. - auto_cleanup_after (None | str | Unset): - """ - - name: str - types: list[AutomationTokenType] - auto_cleanup_users: bool | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - types = [] - for types_item_data in self.types: - types_item = types_item_data.value - types.append(types_item) - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "types": types, - } - ) - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - types = [] - _types = d.pop("types") - for types_item_data in _types: - types_item = AutomationTokenType(types_item_data) - - types.append(types_item) - - auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - create_automation_token_dto = cls( - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - create_automation_token_dto.additional_properties = d - return create_automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/create_token_request_v2.py b/openshock/rest/models/create_token_request_v2.py deleted file mode 100644 index 7dfea1a..0000000 --- a/openshock/rest/models/create_token_request_v2.py +++ /dev/null @@ -1,127 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType -from ..types import UNSET, Unset - -if TYPE_CHECKING: - from ..models.shocker_control_settings import ShockerControlSettings - - -T = TypeVar("T", bound="CreateTokenRequestV2") - - -@_attrs_define -class CreateTokenRequestV2: - """ - Attributes: - name (str): - permissions (list[PermissionType]): - shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits - for intensity and duration. - valid_until (datetime.datetime | None | Unset): - """ - - name: str - permissions: list[PermissionType] - shocker_control: ShockerControlSettings - valid_until: datetime.datetime | None | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - shocker_control = self.shocker_control.to_dict() - - valid_until: None | str | Unset - if isinstance(self.valid_until, Unset): - valid_until = UNSET - elif isinstance(self.valid_until, datetime.datetime): - valid_until = self.valid_until.isoformat() - else: - valid_until = self.valid_until - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "permissions": permissions, - "shockerControl": shocker_control, - } - ) - if valid_until is not UNSET: - field_dict["validUntil"] = valid_until - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 - - d = dict(src_dict) - name = d.pop("name") - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) - - def _parse_valid_until(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - valid_until_type_1 = datetime.datetime.fromisoformat(data) - - return valid_until_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - valid_until = _parse_valid_until(d.pop("validUntil", UNSET)) - - create_token_request_v2 = cls( - name=name, - permissions=permissions, - shocker_control=shocker_control, - valid_until=valid_until, - ) - - create_token_request_v2.additional_properties = d - return create_token_request_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/created_automation_token_dto.py b/openshock/rest/models/created_automation_token_dto.py deleted file mode 100644 index 882a7e2..0000000 --- a/openshock/rest/models/created_automation_token_dto.py +++ /dev/null @@ -1,166 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="CreatedAutomationTokenDto") - - -@_attrs_define -class CreatedAutomationTokenDto: - """ - Attributes: - id (UUID): - name (str): - secret (str): - types (list[AutomationTokenType]): - created_at (datetime.datetime): - last_rotated_at (datetime.datetime | None | Unset): - auto_cleanup_users (bool | Unset): - auto_cleanup_after (None | str | Unset): - """ - - id: UUID - name: str - secret: str - types: list[AutomationTokenType] - created_at: datetime.datetime - last_rotated_at: datetime.datetime | None | Unset = UNSET - auto_cleanup_users: bool | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - secret = self.secret - - types = [] - for types_item_data in self.types: - types_item = types_item_data.value - types.append(types_item) - - created_at = self.created_at.isoformat() - - last_rotated_at: None | str | Unset - if isinstance(self.last_rotated_at, Unset): - last_rotated_at = UNSET - elif isinstance(self.last_rotated_at, datetime.datetime): - last_rotated_at = self.last_rotated_at.isoformat() - else: - last_rotated_at = self.last_rotated_at - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "secret": secret, - "types": types, - "createdAt": created_at, - } - ) - if last_rotated_at is not UNSET: - field_dict["lastRotatedAt"] = last_rotated_at - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - secret = d.pop("secret") - - types = [] - _types = d.pop("types") - for types_item_data in _types: - types_item = AutomationTokenType(types_item_data) - - types.append(types_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) - - return last_rotated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) - - auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - created_automation_token_dto = cls( - id=id, - name=name, - secret=secret, - types=types, - created_at=created_at, - last_rotated_at=last_rotated_at, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - created_automation_token_dto.additional_properties = d - return created_automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/edit_token_request_v2.py b/openshock/rest/models/edit_token_request_v2.py deleted file mode 100644 index 3cd7cfa..0000000 --- a/openshock/rest/models/edit_token_request_v2.py +++ /dev/null @@ -1,95 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType - -if TYPE_CHECKING: - from ..models.shocker_control_settings import ShockerControlSettings - - -T = TypeVar("T", bound="EditTokenRequestV2") - - -@_attrs_define -class EditTokenRequestV2: - """ - Attributes: - name (str): - permissions (list[PermissionType]): - shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits - for intensity and duration. - """ - - name: str - permissions: list[PermissionType] - shocker_control: ShockerControlSettings - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - shocker_control = self.shocker_control.to_dict() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "permissions": permissions, - "shockerControl": shocker_control, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 - - d = dict(src_dict) - name = d.pop("name") - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) - - edit_token_request_v2 = cls( - name=name, - permissions=permissions, - shocker_control=shocker_control, - ) - - edit_token_request_v2.additional_properties = d - return edit_token_request_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_request.py b/openshock/rest/models/email_outbox_bulk_request.py deleted file mode 100644 index fcf889f..0000000 --- a/openshock/rest/models/email_outbox_bulk_request.py +++ /dev/null @@ -1,72 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxBulkRequest") - - -@_attrs_define -class EmailOutboxBulkRequest: - """A set of email outbox message ids to apply a bulk requeue/cancel/delete to. - - Attributes: - ids (list[UUID]): - """ - - ids: list[UUID] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - ids = [] - for ids_item_data in self.ids: - ids_item = str(ids_item_data) - ids.append(ids_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "ids": ids, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - ids = [] - _ids = d.pop("ids") - for ids_item_data in _ids: - ids_item = UUID(ids_item_data) - - ids.append(ids_item) - - email_outbox_bulk_request = cls( - ids=ids, - ) - - email_outbox_bulk_request.additional_properties = d - return email_outbox_bulk_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_result_dto.py b/openshock/rest/models/email_outbox_bulk_result_dto.py deleted file mode 100644 index 2d7ad4f..0000000 --- a/openshock/rest/models/email_outbox_bulk_result_dto.py +++ /dev/null @@ -1,72 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxBulkResultDto") - - -@_attrs_define -class EmailOutboxBulkResultDto: - """Outcome of a bulk email outbox operation: how many ids were requested and how many rows were - actually affected (rows that were missing or in an ineligible state are silently not counted). - - Attributes: - requested (int): - affected (int): - """ - - requested: int - affected: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - requested = self.requested - - affected = self.affected - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "requested": requested, - "affected": affected, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - requested = d.pop("requested") - - affected = d.pop("affected") - - email_outbox_bulk_result_dto = cls( - requested=requested, - affected=affected, - ) - - email_outbox_bulk_result_dto.additional_properties = d - return email_outbox_bulk_result_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto.py b/openshock/rest/models/email_outbox_message_dto.py deleted file mode 100644 index 80d3e7c..0000000 --- a/openshock/rest/models/email_outbox_message_dto.py +++ /dev/null @@ -1,226 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.email_status import EmailStatus -from ..models.email_type import EmailType - -if TYPE_CHECKING: - from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload - - -T = TypeVar("T", bound="EmailOutboxMessageDto") - - -@_attrs_define -class EmailOutboxMessageDto: - """An EmailOutboxMessage as exposed to admins on the mail-queue page. Mirrors the row - verbatim - the outbox stores no rendered body and no usable secret, so every field is safe to show. - - Attributes: - id (UUID): - type_ (EmailType): The kind of email an outbox message represents. The outbox stores - only the intent to send one of these, never a rendered body or a usable secret, the - consumer maps the type to the matching template and (for token-bearing types) mints a fresh - secret at send time. - recipient (str): - recipient_name (None | str): - payload (EmailOutboxMessageDtoPayload): - coalesce_key (None | str): - status (EmailStatus): Delivery state of an email outbox message. - attempt_count (int): - next_attempt_at (datetime.datetime): - last_error (None | str): - created_at (datetime.datetime): - sent_at (datetime.datetime | None): - failed_at (datetime.datetime | None): - """ - - id: UUID - type_: EmailType - recipient: str - recipient_name: None | str - payload: EmailOutboxMessageDtoPayload - coalesce_key: None | str - status: EmailStatus - attempt_count: int - next_attempt_at: datetime.datetime - last_error: None | str - created_at: datetime.datetime - sent_at: datetime.datetime | None - failed_at: datetime.datetime | None - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - type_ = self.type_.value - - recipient = self.recipient - - recipient_name: None | str - recipient_name = self.recipient_name - - payload = self.payload.to_dict() - - coalesce_key: None | str - coalesce_key = self.coalesce_key - - status = self.status.value - - attempt_count = self.attempt_count - - next_attempt_at = self.next_attempt_at.isoformat() - - last_error: None | str - last_error = self.last_error - - created_at = self.created_at.isoformat() - - sent_at: None | str - if isinstance(self.sent_at, datetime.datetime): - sent_at = self.sent_at.isoformat() - else: - sent_at = self.sent_at - - failed_at: None | str - if isinstance(self.failed_at, datetime.datetime): - failed_at = self.failed_at.isoformat() - else: - failed_at = self.failed_at - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "type": type_, - "recipient": recipient, - "recipientName": recipient_name, - "payload": payload, - "coalesceKey": coalesce_key, - "status": status, - "attemptCount": attempt_count, - "nextAttemptAt": next_attempt_at, - "lastError": last_error, - "createdAt": created_at, - "sentAt": sent_at, - "failedAt": failed_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - type_ = EmailType(d.pop("type")) - - recipient = d.pop("recipient") - - def _parse_recipient_name(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - recipient_name = _parse_recipient_name(d.pop("recipientName")) - - payload = EmailOutboxMessageDtoPayload.from_dict(d.pop("payload")) - - def _parse_coalesce_key(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - coalesce_key = _parse_coalesce_key(d.pop("coalesceKey")) - - status = EmailStatus(d.pop("status")) - - attempt_count = d.pop("attemptCount") - - next_attempt_at = datetime.datetime.fromisoformat(d.pop("nextAttemptAt")) - - def _parse_last_error(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - last_error = _parse_last_error(d.pop("lastError")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_sent_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - sent_at_type_1 = datetime.datetime.fromisoformat(data) - - return sent_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - sent_at = _parse_sent_at(d.pop("sentAt")) - - def _parse_failed_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - failed_at_type_1 = datetime.datetime.fromisoformat(data) - - return failed_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - failed_at = _parse_failed_at(d.pop("failedAt")) - - email_outbox_message_dto = cls( - id=id, - type_=type_, - recipient=recipient, - recipient_name=recipient_name, - payload=payload, - coalesce_key=coalesce_key, - status=status, - attempt_count=attempt_count, - next_attempt_at=next_attempt_at, - last_error=last_error, - created_at=created_at, - sent_at=sent_at, - failed_at=failed_at, - ) - - email_outbox_message_dto.additional_properties = d - return email_outbox_message_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto_payload.py b/openshock/rest/models/email_outbox_message_dto_payload.py deleted file mode 100644 index 2db2ad1..0000000 --- a/openshock/rest/models/email_outbox_message_dto_payload.py +++ /dev/null @@ -1,46 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxMessageDtoPayload") - - -@_attrs_define -class EmailOutboxMessageDtoPayload: - additional_properties: dict[str, str] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - email_outbox_message_dto_payload = cls() - - email_outbox_message_dto_payload.additional_properties = d - return email_outbox_message_dto_payload - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> str: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: str) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_stats_dto.py b/openshock/rest/models/email_outbox_stats_dto.py deleted file mode 100644 index 1cd818c..0000000 --- a/openshock/rest/models/email_outbox_stats_dto.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxStatsDto") - - -@_attrs_define -class EmailOutboxStatsDto: - """Count of email outbox rows in each delivery state, for the admin mail-queue overview tiles. - - Attributes: - pending (int): - sending (int): - sent (int): - failed (int): - skipped (int): - total (int): - """ - - pending: int - sending: int - sent: int - failed: int - skipped: int - total: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - pending = self.pending - - sending = self.sending - - sent = self.sent - - failed = self.failed - - skipped = self.skipped - - total = self.total - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "pending": pending, - "sending": sending, - "sent": sent, - "failed": failed, - "skipped": skipped, - "total": total, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - pending = d.pop("pending") - - sending = d.pop("sending") - - sent = d.pop("sent") - - failed = d.pop("failed") - - skipped = d.pop("skipped") - - total = d.pop("total") - - email_outbox_stats_dto = cls( - pending=pending, - sending=sending, - sent=sent, - failed=failed, - skipped=skipped, - total=total, - ) - - email_outbox_stats_dto.additional_properties = d - return email_outbox_stats_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_provider_blacklist_dto.py b/openshock/rest/models/email_provider_blacklist_dto.py deleted file mode 100644 index 53a85f4..0000000 --- a/openshock/rest/models/email_provider_blacklist_dto.py +++ /dev/null @@ -1,80 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailProviderBlacklistDto") - - -@_attrs_define -class EmailProviderBlacklistDto: - """ - Attributes: - id (UUID): - domain (str): - created_at (datetime.datetime): - """ - - id: UUID - domain: str - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - domain = self.domain - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "domain": domain, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - domain = d.pop("domain") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - email_provider_blacklist_dto = cls( - id=id, - domain=domain, - created_at=created_at, - ) - - email_provider_blacklist_dto.additional_properties = d - return email_provider_blacklist_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_status.py b/openshock/rest/models/email_status.py deleted file mode 100644 index 12e74f7..0000000 --- a/openshock/rest/models/email_status.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class EmailStatus(StrEnum): - FAILED = "Failed" - PENDING = "Pending" - SENDING = "Sending" - SENT = "Sent" - SKIPPED = "Skipped" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/email_type.py b/openshock/rest/models/email_type.py deleted file mode 100644 index a778271..0000000 --- a/openshock/rest/models/email_type.py +++ /dev/null @@ -1,12 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class EmailType(StrEnum): - ACCOUNTACTIVATION = "AccountActivation" - EMAILCHANGENOTICE = "EmailChangeNotice" - EMAILVERIFICATION = "EmailVerification" - PASSWORDRESET = "PasswordReset" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py b/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py deleted file mode 100644 index 8aa0cb9..0000000 --- a/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py +++ /dev/null @@ -1,84 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_online_device_response import AdminOnlineDeviceResponse - - -T = TypeVar("T", bound="LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse") - - -@_attrs_define -class LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse: - """ - Attributes: - message (str): Default: ''. - data (list[AdminOnlineDeviceResponse]): - """ - - data: list[AdminOnlineDeviceResponse] - message: str = "" - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - message = self.message - - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "message": message, - "data": data, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_online_device_response import AdminOnlineDeviceResponse # noqa: PLC0415 - - d = dict(src_dict) - message = d.pop("message") - - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = AdminOnlineDeviceResponse.from_dict(data_item_data) - - data.append(data_item) - - legacy_data_response_of_array_of_admin_online_device_response = cls( - message=message, - data=data, - ) - - legacy_data_response_of_array_of_admin_online_device_response.additional_properties = d - return legacy_data_response_of_array_of_admin_online_device_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py b/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py deleted file mode 100644 index 757a667..0000000 --- a/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py +++ /dev/null @@ -1,84 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.ota_item import OtaItem - - -T = TypeVar("T", bound="LegacyDataResponseOfIReadOnlyCollectionOfOtaItem") - - -@_attrs_define -class LegacyDataResponseOfIReadOnlyCollectionOfOtaItem: - """ - Attributes: - message (str): Default: ''. - data (list[OtaItem]): - """ - - data: list[OtaItem] - message: str = "" - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - message = self.message - - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "message": message, - "data": data, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.ota_item import OtaItem # noqa: PLC0415 - - d = dict(src_dict) - message = d.pop("message") - - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = OtaItem.from_dict(data_item_data) - - data.append(data_item) - - legacy_data_response_of_i_read_only_collection_of_ota_item = cls( - message=message, - data=data, - ) - - legacy_data_response_of_i_read_only_collection_of_ota_item.additional_properties = d - return legacy_data_response_of_i_read_only_collection_of_ota_item - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/login_session_response.py b/openshock/rest/models/login_session_response.py deleted file mode 100644 index 47328f3..0000000 --- a/openshock/rest/models/login_session_response.py +++ /dev/null @@ -1,203 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -T = TypeVar("T", bound="LoginSessionResponse") - - -@_attrs_define -class LoginSessionResponse: - """ - Attributes: - id (UUID): - ip (str): An IPv4 or IPv6 address in its textual form. - user_agent (str): - created (datetime.datetime): - expires (datetime.datetime): - last_used (datetime.datetime | None): - asn_org (None | str | Unset): - is_vpn (bool | None | Unset): - country_code (None | str | Unset): - city (None | str | Unset): - """ - - id: UUID - ip: str - user_agent: str - created: datetime.datetime - expires: datetime.datetime - last_used: datetime.datetime | None - asn_org: None | str | Unset = UNSET - is_vpn: bool | None | Unset = UNSET - country_code: None | str | Unset = UNSET - city: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - ip = self.ip - - user_agent = self.user_agent - - created = self.created.isoformat() - - expires = self.expires.isoformat() - - last_used: None | str - if isinstance(self.last_used, datetime.datetime): - last_used = self.last_used.isoformat() - else: - last_used = self.last_used - - asn_org: None | str | Unset - if isinstance(self.asn_org, Unset): - asn_org = UNSET - else: - asn_org = self.asn_org - - is_vpn: bool | None | Unset - if isinstance(self.is_vpn, Unset): - is_vpn = UNSET - else: - is_vpn = self.is_vpn - - country_code: None | str | Unset - if isinstance(self.country_code, Unset): - country_code = UNSET - else: - country_code = self.country_code - - city: None | str | Unset - if isinstance(self.city, Unset): - city = UNSET - else: - city = self.city - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "ip": ip, - "userAgent": user_agent, - "created": created, - "expires": expires, - "lastUsed": last_used, - } - ) - if asn_org is not UNSET: - field_dict["asnOrg"] = asn_org - if is_vpn is not UNSET: - field_dict["isVpn"] = is_vpn - if country_code is not UNSET: - field_dict["countryCode"] = country_code - if city is not UNSET: - field_dict["city"] = city - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - ip = d.pop("ip") - - user_agent = d.pop("userAgent") - - created = datetime.datetime.fromisoformat(d.pop("created")) - - expires = datetime.datetime.fromisoformat(d.pop("expires")) - - def _parse_last_used(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - last_used = _parse_last_used(d.pop("lastUsed")) - - def _parse_asn_org(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - asn_org = _parse_asn_org(d.pop("asnOrg", UNSET)) - - def _parse_is_vpn(data: object) -> bool | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(bool | None | Unset, data) - - is_vpn = _parse_is_vpn(d.pop("isVpn", UNSET)) - - def _parse_country_code(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - country_code = _parse_country_code(d.pop("countryCode", UNSET)) - - def _parse_city(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - city = _parse_city(d.pop("city", UNSET)) - - login_session_response = cls( - id=id, - ip=ip, - user_agent=user_agent, - created=created, - expires=expires, - last_used=last_used, - asn_org=asn_org, - is_vpn=is_vpn, - country_code=country_code, - city=city, - ) - - login_session_response.additional_properties = d - return login_session_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/match_type_enum.py b/openshock/rest/models/match_type_enum.py deleted file mode 100644 index f734f77..0000000 --- a/openshock/rest/models/match_type_enum.py +++ /dev/null @@ -1,10 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class MatchTypeEnum(StrEnum): - CONTAINS = "Contains" - EXACT = "Exact" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/o_auth_connection_response.py b/openshock/rest/models/o_auth_connection_response.py deleted file mode 100644 index ce6a08a..0000000 --- a/openshock/rest/models/o_auth_connection_response.py +++ /dev/null @@ -1,93 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="OAuthConnectionResponse") - - -@_attrs_define -class OAuthConnectionResponse: - """ - Attributes: - provider_key (str): - external_id (str): - display_name (None | str): - linked_at (datetime.datetime): - """ - - provider_key: str - external_id: str - display_name: None | str - linked_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - provider_key = self.provider_key - - external_id = self.external_id - - display_name: None | str - display_name = self.display_name - - linked_at = self.linked_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "providerKey": provider_key, - "externalId": external_id, - "displayName": display_name, - "linkedAt": linked_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - provider_key = d.pop("providerKey") - - external_id = d.pop("externalId") - - def _parse_display_name(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - display_name = _parse_display_name(d.pop("displayName")) - - linked_at = datetime.datetime.fromisoformat(d.pop("linkedAt")) - - o_auth_connection_response = cls( - provider_key=provider_key, - external_id=external_id, - display_name=display_name, - linked_at=linked_at, - ) - - o_auth_connection_response.additional_properties = d - return o_auth_connection_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/ota_item.py b/openshock/rest/models/ota_item.py deleted file mode 100644 index 7c9e8fd..0000000 --- a/openshock/rest/models/ota_item.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.ota_update_status import OtaUpdateStatus - -T = TypeVar("T", bound="OtaItem") - - -@_attrs_define -class OtaItem: - """ - Attributes: - id (int): - started_at (datetime.datetime): - status (OtaUpdateStatus): - version (str): - message (None | str): - """ - - id: int - started_at: datetime.datetime - status: OtaUpdateStatus - version: str - message: None | str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = self.id - - started_at = self.started_at.isoformat() - - status = self.status.value - - version = self.version - - message: None | str - message = self.message - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "startedAt": started_at, - "status": status, - "version": version, - "message": message, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = d.pop("id") - - started_at = datetime.datetime.fromisoformat(d.pop("startedAt")) - - status = OtaUpdateStatus(d.pop("status")) - - version = d.pop("version") - - def _parse_message(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - message = _parse_message(d.pop("message")) - - ota_item = cls( - id=id, - started_at=started_at, - status=status, - version=version, - message=message, - ) - - ota_item.additional_properties = d - return ota_item - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/ota_update_status.py b/openshock/rest/models/ota_update_status.py deleted file mode 100644 index 6f8243f..0000000 --- a/openshock/rest/models/ota_update_status.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class OtaUpdateStatus(StrEnum): - ERROR = "Error" - FINISHED = "Finished" - RUNNING = "Running" - STARTED = "Started" - TIMEOUT = "Timeout" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/paged_result_of_audit_log_entry_response.py b/openshock/rest/models/paged_result_of_audit_log_entry_response.py deleted file mode 100644 index afb380c..0000000 --- a/openshock/rest/models/paged_result_of_audit_log_entry_response.py +++ /dev/null @@ -1,112 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -if TYPE_CHECKING: - from ..models.audit_log_entry_response import AuditLogEntryResponse - - -T = TypeVar("T", bound="PagedResultOfAuditLogEntryResponse") - - -@_attrs_define -class PagedResultOfAuditLogEntryResponse: - """Page of results for a paginated list endpoint. - - Attributes: - items (list[AuditLogEntryResponse]): Items on the current page. - page (int): 1-based current page index. - page_size (int): Page size used to produce this result. - total_count (int): Total number of items across all pages matching the query. - total_pages (int | Unset): Total number of pages. Always at least 1, even when `TotalCount` is zero. - """ - - items: list[AuditLogEntryResponse] - page: int - page_size: int - total_count: int - total_pages: int | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - items = [] - for items_item_data in self.items: - items_item = items_item_data.to_dict() - items.append(items_item) - - page = self.page - - page_size = self.page_size - - total_count = self.total_count - - total_pages = self.total_pages - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "items": items, - "page": page, - "pageSize": page_size, - "totalCount": total_count, - } - ) - if total_pages is not UNSET: - field_dict["totalPages"] = total_pages - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.audit_log_entry_response import AuditLogEntryResponse # noqa: PLC0415 - - d = dict(src_dict) - items = [] - _items = d.pop("items") - for items_item_data in _items: - items_item = AuditLogEntryResponse.from_dict(items_item_data) - - items.append(items_item) - - page = d.pop("page") - - page_size = d.pop("pageSize") - - total_count = d.pop("totalCount") - - total_pages = d.pop("totalPages", UNSET) - - paged_result_of_audit_log_entry_response = cls( - items=items, - page=page, - page_size=page_size, - total_count=total_count, - total_pages=total_pages, - ) - - paged_result_of_audit_log_entry_response.additional_properties = d - return paged_result_of_audit_log_entry_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_admin_users_view.py b/openshock/rest/models/paginated_of_admin_users_view.py deleted file mode 100644 index fa4499d..0000000 --- a/openshock/rest/models/paginated_of_admin_users_view.py +++ /dev/null @@ -1,100 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_users_view import AdminUsersView - - -T = TypeVar("T", bound="PaginatedOfAdminUsersView") - - -@_attrs_define -class PaginatedOfAdminUsersView: - """ - Attributes: - offset (int): - limit (int): - total (int): - data (list[AdminUsersView]): - """ - - offset: int - limit: int - total: int - data: list[AdminUsersView] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - offset = self.offset - - limit = self.limit - - total = self.total - - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "offset": offset, - "limit": limit, - "total": total, - "data": data, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_users_view import AdminUsersView # noqa: PLC0415 - - d = dict(src_dict) - offset = d.pop("offset") - - limit = d.pop("limit") - - total = d.pop("total") - - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = AdminUsersView.from_dict(data_item_data) - - data.append(data_item) - - paginated_of_admin_users_view = cls( - offset=offset, - limit=limit, - total=total, - data=data, - ) - - paginated_of_admin_users_view.additional_properties = d - return paginated_of_admin_users_view - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_email_outbox_message_dto.py b/openshock/rest/models/paginated_of_email_outbox_message_dto.py deleted file mode 100644 index dffe554..0000000 --- a/openshock/rest/models/paginated_of_email_outbox_message_dto.py +++ /dev/null @@ -1,100 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.email_outbox_message_dto import EmailOutboxMessageDto - - -T = TypeVar("T", bound="PaginatedOfEmailOutboxMessageDto") - - -@_attrs_define -class PaginatedOfEmailOutboxMessageDto: - """ - Attributes: - offset (int): - limit (int): - total (int): - data (list[EmailOutboxMessageDto]): - """ - - offset: int - limit: int - total: int - data: list[EmailOutboxMessageDto] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - offset = self.offset - - limit = self.limit - - total = self.total - - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "offset": offset, - "limit": limit, - "total": total, - "data": data, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.email_outbox_message_dto import EmailOutboxMessageDto # noqa: PLC0415 - - d = dict(src_dict) - offset = d.pop("offset") - - limit = d.pop("limit") - - total = d.pop("total") - - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = EmailOutboxMessageDto.from_dict(data_item_data) - - data.append(data_item) - - paginated_of_email_outbox_message_dto = cls( - offset=offset, - limit=limit, - total=total, - data=data, - ) - - paginated_of_email_outbox_message_dto.additional_properties = d - return paginated_of_email_outbox_message_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/password_hashing_algorithm.py b/openshock/rest/models/password_hashing_algorithm.py deleted file mode 100644 index 13a3409..0000000 --- a/openshock/rest/models/password_hashing_algorithm.py +++ /dev/null @@ -1,11 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class PasswordHashingAlgorithm(StrEnum): - BCRYPT = "BCrypt" - PBKDF2 = "PBKDF2" - UNKNOWN = "Unknown" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/patch_automation_token_dto.py b/openshock/rest/models/patch_automation_token_dto.py deleted file mode 100644 index ac287bc..0000000 --- a/openshock/rest/models/patch_automation_token_dto.py +++ /dev/null @@ -1,154 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="PatchAutomationTokenDto") - - -@_attrs_define -class PatchAutomationTokenDto: - """ - Attributes: - name (None | str | Unset): - types (list[AutomationTokenType] | None | Unset): - auto_cleanup_users (bool | None | Unset): - auto_cleanup_after (None | str | Unset): - """ - - name: None | str | Unset = UNSET - types: list[AutomationTokenType] | None | Unset = UNSET - auto_cleanup_users: bool | None | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name: None | str | Unset - if isinstance(self.name, Unset): - name = UNSET - else: - name = self.name - - types: list[str] | None | Unset - if isinstance(self.types, Unset): - types = UNSET - elif isinstance(self.types, list): - types = [] - for types_type_1_item_data in self.types: - types_type_1_item = types_type_1_item_data.value - types.append(types_type_1_item) - - else: - types = self.types - - auto_cleanup_users: bool | None | Unset - if isinstance(self.auto_cleanup_users, Unset): - auto_cleanup_users = UNSET - else: - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update({}) - if name is not UNSET: - field_dict["name"] = name - if types is not UNSET: - field_dict["types"] = types - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - - def _parse_name(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - name = _parse_name(d.pop("name", UNSET)) - - def _parse_types(data: object) -> list[AutomationTokenType] | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, list): - raise TypeError() - types_type_1 = [] - _types_type_1 = data - for types_type_1_item_data in _types_type_1: - types_type_1_item = AutomationTokenType(types_type_1_item_data) - - types_type_1.append(types_type_1_item) - - return types_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(list[AutomationTokenType] | None | Unset, data) - - types = _parse_types(d.pop("types", UNSET)) - - def _parse_auto_cleanup_users(data: object) -> bool | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(bool | None | Unset, data) - - auto_cleanup_users = _parse_auto_cleanup_users(d.pop("autoCleanupUsers", UNSET)) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - patch_automation_token_dto = cls( - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - patch_automation_token_dto.additional_properties = d - return patch_automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/report_tokens_request.py b/openshock/rest/models/report_tokens_request.py deleted file mode 100644 index 8c6cafb..0000000 --- a/openshock/rest/models/report_tokens_request.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="ReportTokensRequest") - - -@_attrs_define -class ReportTokensRequest: - """ - Attributes: - turnstile_response (str): - secrets (list[str]): - """ - - turnstile_response: str - secrets: list[str] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - turnstile_response = self.turnstile_response - - secrets = self.secrets - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "turnstileResponse": turnstile_response, - "secrets": secrets, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - turnstile_response = d.pop("turnstileResponse") - - secrets = cast(list[str], d.pop("secrets")) - - report_tokens_request = cls( - turnstile_response=turnstile_response, - secrets=secrets, - ) - - report_tokens_request.additional_properties = d - return report_tokens_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/send_test_email_dto.py b/openshock/rest/models/send_test_email_dto.py deleted file mode 100644 index e3fd2d6..0000000 --- a/openshock/rest/models/send_test_email_dto.py +++ /dev/null @@ -1,98 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.email_type import EmailType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="SendTestEmailDto") - - -@_attrs_define -class SendTestEmailDto: - """Request to enqueue a preview/test email of a chosen type to a chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no request row). - - Attributes: - type_ (EmailType): The kind of email an outbox message represents. The outbox stores - only the intent to send one of these, never a rendered body or a usable secret, the - consumer maps the type to the matching template and (for token-bearing types) mints a fresh - secret at send time. - recipient (str): Destination address for the test email. - recipient_name (None | str | Unset): Optional display name for the recipient. - """ - - type_: EmailType - recipient: str - recipient_name: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - type_ = self.type_.value - - recipient = self.recipient - - recipient_name: None | str | Unset - if isinstance(self.recipient_name, Unset): - recipient_name = UNSET - else: - recipient_name = self.recipient_name - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "type": type_, - "recipient": recipient, - } - ) - if recipient_name is not UNSET: - field_dict["recipientName"] = recipient_name - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - type_ = EmailType(d.pop("type")) - - recipient = d.pop("recipient") - - def _parse_recipient_name(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - recipient_name = _parse_recipient_name(d.pop("recipientName", UNSET)) - - send_test_email_dto = cls( - type_=type_, - recipient=recipient, - recipient_name=recipient_name, - ) - - send_test_email_dto.additional_properties = d - return send_test_email_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/set_token_paused_request.py b/openshock/rest/models/set_token_paused_request.py deleted file mode 100644 index 4a6507c..0000000 --- a/openshock/rest/models/set_token_paused_request.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SetTokenPausedRequest") - - -@_attrs_define -class SetTokenPausedRequest: - """ - Attributes: - paused (bool): When true, the token is paused and may not send shocker control messages. - """ - - paused: bool - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - paused = self.paused - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "paused": paused, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - paused = d.pop("paused") - - set_token_paused_request = cls( - paused=paused, - ) - - set_token_paused_request.additional_properties = d - return set_token_paused_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/set_user_email_request_body.py b/openshock/rest/models/set_user_email_request_body.py deleted file mode 100644 index 6d555e5..0000000 --- a/openshock/rest/models/set_user_email_request_body.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SetUserEmailRequestBody") - - -@_attrs_define -class SetUserEmailRequestBody: - """ - Attributes: - email (str): - """ - - email: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - email = self.email - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "email": email, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - email = d.pop("email") - - set_user_email_request_body = cls( - email=email, - ) - - set_user_email_request_body.additional_properties = d - return set_user_email_request_body - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/set_user_name_request_body.py b/openshock/rest/models/set_user_name_request_body.py deleted file mode 100644 index 178e806..0000000 --- a/openshock/rest/models/set_user_name_request_body.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SetUserNameRequestBody") - - -@_attrs_define -class SetUserNameRequestBody: - """ - Attributes: - name (str): - """ - - name: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - set_user_name_request_body = cls( - name=name, - ) - - set_user_name_request_body.additional_properties = d - return set_user_name_request_body - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/set_user_password_request_body.py b/openshock/rest/models/set_user_password_request_body.py deleted file mode 100644 index 2eba296..0000000 --- a/openshock/rest/models/set_user_password_request_body.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SetUserPasswordRequestBody") - - -@_attrs_define -class SetUserPasswordRequestBody: - """ - Attributes: - password (str): - """ - - password: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - password = self.password - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "password": password, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - password = d.pop("password") - - set_user_password_request_body = cls( - password=password, - ) - - set_user_password_request_body.additional_properties = d - return set_user_password_request_body - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/token_created_response_v2.py b/openshock/rest/models/token_created_response_v2.py deleted file mode 100644 index 0ff2f4b..0000000 --- a/openshock/rest/models/token_created_response_v2.py +++ /dev/null @@ -1,171 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType - -if TYPE_CHECKING: - from ..models.shocker_control_settings import ShockerControlSettings - - -T = TypeVar("T", bound="TokenCreatedResponseV2") - - -@_attrs_define -class TokenCreatedResponseV2: - """ - Attributes: - id (UUID): - name (str): - token (str): - created_at (datetime.datetime): - valid_until (datetime.datetime | None): - last_used (datetime.datetime | None): - permissions (list[PermissionType]): - shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits - for intensity and duration. - """ - - id: UUID - name: str - token: str - created_at: datetime.datetime - valid_until: datetime.datetime | None - last_used: datetime.datetime | None - permissions: list[PermissionType] - shocker_control: ShockerControlSettings - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - token = self.token - - created_at = self.created_at.isoformat() - - valid_until: None | str - if isinstance(self.valid_until, datetime.datetime): - valid_until = self.valid_until.isoformat() - else: - valid_until = self.valid_until - - last_used: None | str - if isinstance(self.last_used, datetime.datetime): - last_used = self.last_used.isoformat() - else: - last_used = self.last_used - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - shocker_control = self.shocker_control.to_dict() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "token": token, - "createdAt": created_at, - "validUntil": valid_until, - "lastUsed": last_used, - "permissions": permissions, - "shockerControl": shocker_control, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - token = d.pop("token") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_valid_until(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - valid_until_type_1 = datetime.datetime.fromisoformat(data) - - return valid_until_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - valid_until = _parse_valid_until(d.pop("validUntil")) - - def _parse_last_used(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - last_used = _parse_last_used(d.pop("lastUsed")) - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) - - token_created_response_v2 = cls( - id=id, - name=name, - token=token, - created_at=created_at, - valid_until=valid_until, - last_used=last_used, - permissions=permissions, - shocker_control=shocker_control, - ) - - token_created_response_v2.additional_properties = d - return token_created_response_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/token_paused_response.py b/openshock/rest/models/token_paused_response.py deleted file mode 100644 index dbce49a..0000000 --- a/openshock/rest/models/token_paused_response.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="TokenPausedResponse") - - -@_attrs_define -class TokenPausedResponse: - """ - Attributes: - paused (bool): The now-set paused state of the token. - """ - - paused: bool - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - paused = self.paused - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "paused": paused, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - paused = d.pop("paused") - - token_paused_response = cls( - paused=paused, - ) - - token_paused_response.additional_properties = d - return token_paused_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/user_name_blacklist_dto.py b/openshock/rest/models/user_name_blacklist_dto.py deleted file mode 100644 index 3f1a8e9..0000000 --- a/openshock/rest/models/user_name_blacklist_dto.py +++ /dev/null @@ -1,90 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.match_type_enum import MatchTypeEnum - -T = TypeVar("T", bound="UserNameBlacklistDto") - - -@_attrs_define -class UserNameBlacklistDto: - """ - Attributes: - id (UUID): - value (str): - match_type (MatchTypeEnum): - created_at (datetime.datetime): - """ - - id: UUID - value: str - match_type: MatchTypeEnum - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - value = self.value - - match_type = self.match_type.value - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "value": value, - "matchType": match_type, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - value = d.pop("value") - - match_type = MatchTypeEnum(d.pop("matchType")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - user_name_blacklist_dto = cls( - id=id, - value=value, - match_type=match_type, - created_at=created_at, - ) - - user_name_blacklist_dto.additional_properties = d - return user_name_blacklist_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/user_patch_dto.py b/openshock/rest/models/user_patch_dto.py deleted file mode 100644 index b4432b7..0000000 --- a/openshock/rest/models/user_patch_dto.py +++ /dev/null @@ -1,94 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -T = TypeVar("T", bound="UserPatchDto") - - -@_attrs_define -class UserPatchDto: - """ - Attributes: - name (None | str | Unset): - email (None | str | Unset): - """ - - name: None | str | Unset = UNSET - email: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name: None | str | Unset - if isinstance(self.name, Unset): - name = UNSET - else: - name = self.name - - email: None | str | Unset - if isinstance(self.email, Unset): - email = UNSET - else: - email = self.email - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update({}) - if name is not UNSET: - field_dict["name"] = name - if email is not UNSET: - field_dict["email"] = email - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - - def _parse_name(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - name = _parse_name(d.pop("name", UNSET)) - - def _parse_email(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - email = _parse_email(d.pop("email", UNSET)) - - user_patch_dto = cls( - name=name, - email=email, - ) - - user_patch_dto.additional_properties = d - return user_patch_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/webhook_dto.py b/openshock/rest/models/webhook_dto.py deleted file mode 100644 index ba0eb10..0000000 --- a/openshock/rest/models/webhook_dto.py +++ /dev/null @@ -1,88 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="WebhookDto") - - -@_attrs_define -class WebhookDto: - """ - Attributes: - id (UUID): - name (str): - url (str): - created_at (datetime.datetime): - """ - - id: UUID - name: str - url: str - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - url = self.url - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "url": url, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - url = d.pop("url") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - webhook_dto = cls( - id=id, - name=name, - url=url, - created_at=created_at, - ) - - webhook_dto.additional_properties = d - return webhook_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/scripts/generate.py b/scripts/generate.py index 87820ff..ab1dfdc 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -33,6 +33,58 @@ DEFAULT_SPEC_URL = "https://api.openshock.app/openapi.json" JSON = "application/json" +METHODS = {"get", "put", "post", "delete", "patch", "head", "options", "trace", "query"} + +# The SDK authenticates with API tokens (or a hub's device token). Operations nobody can +# call that way are left out of the generated client. +EXCLUDED_TAGS = {"Admin"} +SESSION_ONLY = "UserSessionCookie" + + +def excluded(operation: dict[str, Any]) -> bool: + """True for admin operations and for those that only accept a browser login session.""" + if EXCLUDED_TAGS & set(operation.get("tags") or []): + return True + schemes = {name for requirement in operation.get("security") or [] for name in requirement} + return schemes == {SESSION_ONLY} + + +def references(node: Any) -> set[str]: + """Names of the component schemas referenced anywhere below ``node``.""" + found: set[str] = set() + if isinstance(node, dict): + ref = node.get("$ref") + if isinstance(ref, str) and ref.startswith("#/components/schemas/"): + found.add(ref.rsplit("/", 1)[1]) + for value in node.values(): + found |= references(value) + elif isinstance(node, list): + for value in node: + found |= references(value) + return found + + +def drop_excluded(spec: dict[str, Any]) -> None: + paths = spec.get("paths", {}) + for path, item in list(paths.items()): + for method in [m for m, op in item.items() if m in METHODS and isinstance(op, dict) and excluded(op)]: + del item[method] + if not METHODS & item.keys(): + del paths[path] + + # Drop the models only the removed operations used. + schemas = spec.get("components", {}).get("schemas", {}) + keep: set[str] = set() + pending = references(paths) + while pending: + name = pending.pop() + if name not in keep and name in schemas: + keep.add(name) + pending |= references(schemas[name]) - keep + for name in [n for n in schemas if n not in keep]: + del schemas[name] + + HEADER = "# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand.\n" @@ -43,6 +95,8 @@ def prepare(spec: dict[str, Any]) -> dict[str, Any]: if str(spec.get("openapi", "")).startswith("3.2"): spec["openapi"] = "3.1.0" + drop_excluded(spec) + # ASP.NET lists every JSON flavour it accepts (application/json, text/json, # application/*+json). The generator would emit one branch per flavour and send the # last one as Content-Type, so keep plain JSON wherever it is offered. diff --git a/tests/test_generated.py b/tests/test_generated.py index d960601..ed2f1b3 100644 --- a/tests/test_generated.py +++ b/tests/test_generated.py @@ -10,10 +10,24 @@ import openshock.rest.api ROOT = Path(__file__).resolve().parent.parent -SPEC = json.loads((ROOT / "openapi" / "openapi.json").read_text(encoding="utf-8")) METHODS = {"get", "put", "post", "delete", "patch", "head", "options", "trace"} +def load_generate(): + spec = importlib.util.spec_from_file_location("generate", ROOT / "scripts" / "generate.py") + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + sys.modules["generate"] = module + spec.loader.exec_module(module) + return module + + +generate = load_generate() +RAW = json.loads((ROOT / "openapi" / "openapi.json").read_text(encoding="utf-8")) +#: The document as the generator sees it: without admin and session-only operations. +SPEC = generate.prepare(json.loads(json.dumps(RAW))) + + def operation_modules(): for tag in pkgutil.iter_modules(openshock.rest.api.__path__): package = importlib.import_module(f"openshock.rest.api.{tag.name}") @@ -24,7 +38,7 @@ def operation_modules(): def test_every_operation_has_a_module_with_sync_and_async_variants(): operations = [op for item in SPEC["paths"].values() for method, op in item.items() if method in METHODS] modules = list(operation_modules()) - assert len(modules) == len(operations) > 100 + assert len(modules) == len(operations) > 50 for module in modules: # Operations without a response body only get the *_detailed pair. for variant in ("sync_detailed", "asyncio_detailed"): @@ -39,12 +53,6 @@ def test_every_schema_has_a_model(): def test_spec_preparation(): - spec = importlib.util.spec_from_file_location("generate", ROOT / "scripts" / "generate.py") - assert spec and spec.loader - generate = importlib.util.module_from_spec(spec) - sys.modules["generate"] = generate - spec.loader.exec_module(generate) - document = { "openapi": "3.2.0", "paths": { @@ -68,3 +76,55 @@ def test_spec_preparation(): assert post["requestBody"]["content"] == {"application/json": {"a": 1}} assert post["responses"]["200"]["content"] == {"application/json": {"b": 2}} assert post["responses"]["201"]["content"] == {"text/plain": {"c": 3}} + + +def test_admin_and_session_only_operations_are_not_generated(): + remaining = [op for item in SPEC["paths"].values() for method, op in item.items() if method in METHODS] + assert not any("Admin" in op.get("tags", []) for op in remaining) + assert not any(op.get("security") == [{"UserSessionCookie": []}] for op in remaining) + assert not any(path.startswith("/1/admin") for path in SPEC["paths"]) + # Everything an API token or a hub token can call is still there. + for path, item in RAW["paths"].items(): + for method, op in item.items(): + if method not in METHODS or "Admin" in op.get("tags", []): + continue + schemes = {name for requirement in op.get("security") or [] for name in requirement} + if schemes != {"UserSessionCookie"}: + assert method in SPEC["paths"][path], f"{method} {path}" + + import openshock.rest.api as api + + names = {module.name for module in pkgutil.iter_modules(api.__path__)} + assert "admin" not in names and "sessions" not in names + assert {"shockers", "hub_management", "hub_endpoints", "meta"} <= names + + +def test_excluding_operations_drops_their_models(): + document = { + "paths": { + "/keep": { + "get": { + "responses": { + "200": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/A"}}}} + } + } + }, + "/admin": { + "get": { + "tags": ["Admin"], + "responses": { + "200": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/C"}}}} + }, + } + }, + "/mixed": { + "get": {"security": [{"UserSessionCookie": []}], "responses": {}}, + "post": {"security": [{"ApiToken": []}, {"UserSessionCookie": []}], "responses": {}}, + }, + }, + "components": {"schemas": {"A": {"properties": {"b": {"$ref": "#/components/schemas/B"}}}, "B": {}, "C": {}}}, + } + generate.prepare(document) + assert set(document["paths"]) == {"/keep", "/mixed"} + assert set(document["paths"]["/mixed"]) == {"post"} + assert set(document["components"]["schemas"]) == {"A", "B"} From eb1540ed06810a86b787733dd0ff603708b92cc0 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 16:23:30 +0100 Subject: [PATCH 6/9] Revert "feat!: leave admin and session-only endpoints out of the generated client" This reverts commit 47d5d4d5d7873a5472eec75d7baf2a604341fcd9. --- README.md | 19 +- .../authenticated_account_change_email.py | 189 ++++++++ .../authenticated_account_change_password.py | 170 +++++++ .../authenticated_account_change_username.py | 175 +++++++ .../authenticated_account_deactivate.py | 133 ++++++ .../authenticated_account_get_audit_log.py | 226 +++++++++ ...ticated_account_list_o_auth_connections.py | 134 ++++++ ...icated_account_remove_o_auth_connection.py | 158 +++++++ openshock/rest/api/admin/__init__.py | 2 + .../admin_add_email_provider_blacklist.py | 102 +++++ .../api/admin/admin_add_username_blacklist.py | 102 +++++ openshock/rest/api/admin/admin_add_webhook.py | 167 +++++++ .../admin/admin_bulk_cancel_email_outbox.py | 177 +++++++ .../admin/admin_bulk_delete_email_outbox.py | 173 +++++++ .../admin/admin_bulk_requeue_email_outbox.py | 177 +++++++ .../api/admin/admin_cancel_email_outbox.py | 172 +++++++ .../rest/api/admin/admin_configuration_add.py | 174 +++++++ .../api/admin/admin_configuration_delete.py | 169 +++++++ .../api/admin/admin_configuration_list.py | 138 ++++++ .../api/admin/admin_configuration_update.py | 191 ++++++++ .../admin/admin_create_automation_token.py | 161 +++++++ .../rest/api/admin/admin_deactivate_user.py | 127 +++++ .../rest/api/admin/admin_delete_api_token.py | 103 +++++ .../admin/admin_delete_automation_token.py | 168 +++++++ .../api/admin/admin_delete_email_outbox.py | 167 +++++++ openshock/rest/api/admin/admin_delete_user.py | 118 +++++ .../api/admin/admin_get_admin_audit_log.py | 263 +++++++++++ .../rest/api/admin/admin_get_email_outbox.py | 218 +++++++++ .../api/admin/admin_get_email_outbox_stats.py | 133 ++++++ .../api/admin/admin_get_online_devices.py | 135 ++++++ .../api/admin/admin_get_online_gateways.py | 138 ++++++ .../rest/api/admin/admin_get_user_by_id.py | 167 +++++++ openshock/rest/api/admin/admin_get_users.py | 210 +++++++++ .../api/admin/admin_list_automation_tokens.py | 134 ++++++ .../admin_list_email_provider_blacklist.py | 162 +++++++ .../admin/admin_list_username_blacklist.py | 162 +++++++ .../rest/api/admin/admin_list_webhooks.py | 138 ++++++ openshock/rest/api/admin/admin_modify_user.py | 121 +++++ .../api/admin/admin_patch_automation_token.py | 184 ++++++++ .../rest/api/admin/admin_reactivate_user.py | 118 +++++ .../admin_remove_email_provider_blacklist.py | 155 +++++++ .../admin/admin_remove_username_blacklist.py | 155 +++++++ .../rest/api/admin/admin_remove_webhook.py | 163 +++++++ .../api/admin/admin_requeue_email_outbox.py | 172 +++++++ .../admin/admin_rotate_automation_token.py | 163 +++++++ .../rest/api/admin/admin_send_test_email.py | 191 ++++++++ .../rest/api/admin/admin_set_user_email.py | 184 ++++++++ .../rest/api/admin/admin_set_user_name.py | 192 ++++++++ .../rest/api/admin/admin_set_user_password.py | 192 ++++++++ .../api/api_tokens/tokens_create_token_v2.py | 161 +++++++ .../api/api_tokens/tokens_edit_token_v2.py | 182 ++++++++ .../api_tokens/tokens_get_token_by_id_v2.py | 163 +++++++ .../api/api_tokens/tokens_list_tokens_v2.py | 132 ++++++ .../api/api_tokens/tokens_report_tokens.py | 104 +++++ .../api/api_tokens/tokens_set_token_paused.py | 184 ++++++++ .../devices_ota_get_ota_update_history.py | 165 +++++++ openshock/rest/api/sessions/__init__.py | 2 + .../api/sessions/sessions_delete_session.py | 157 +++++++ .../api/sessions/sessions_get_self_session.py | 127 +++++ .../api/sessions/sessions_list_sessions.py | 130 ++++++ openshock/rest/api/shocker_shares/__init__.py | 2 + .../shares_delete_share_code.py | 163 +++++++ .../shocker_shares/shares_link_share_code.py | 172 +++++++ openshock/rest/models/__init__.py | 180 ++++++++ .../add_email_provider_blacklist_dto.py | 62 +++ .../rest/models/add_username_blacklist_dto.py | 72 +++ openshock/rest/models/add_webhook_dto.py | 70 +++ .../models/admin_online_device_response.py | 216 +++++++++ .../models/admin_online_gateway_response.py | 146 ++++++ openshock/rest/models/admin_user_view.py | 324 +++++++++++++ .../rest/models/admin_user_view_api_token.py | 156 +++++++ .../models/admin_user_view_email_change.py | 105 +++++ openshock/rest/models/admin_user_view_hub.py | 102 +++++ .../models/admin_user_view_name_change.py | 79 ++++ .../models/admin_user_view_password_reset.py | 97 ++++ .../rest/models/admin_user_view_shocker.py | 80 ++++ ...admin_user_view_user_activation_request.py | 71 +++ .../admin_user_view_user_deactivation.py | 102 +++++ .../rest/models/admin_user_view_user_ref.py | 71 +++ openshock/rest/models/admin_users_view.py | 304 ++++++++++++ openshock/rest/models/audit_action.py | 26 ++ .../rest/models/audit_log_entry_response.py | 432 ++++++++++++++++++ ...t_metadata_account_deactivated_metadata.py | 81 ++++ ...metadata_account_deactivated_metadata_t.py | 9 + ...dit_metadata_api_token_created_metadata.py | 98 ++++ ...t_metadata_api_token_created_metadata_t.py | 9 + ...dit_metadata_api_token_deleted_metadata.py | 90 ++++ ...t_metadata_api_token_deleted_metadata_t.py | 9 + ...adata_automation_token_created_metadata.py | 120 +++++ ...ata_automation_token_created_metadata_t.py | 9 + ...adata_automation_token_deleted_metadata.py | 99 ++++ ...ata_automation_token_deleted_metadata_t.py | 9 + ...adata_automation_token_rotated_metadata.py | 90 ++++ ...ata_automation_token_rotated_metadata_t.py | 9 + ...adata_automation_token_updated_metadata.py | 121 +++++ ...ata_automation_token_updated_metadata_t.py | 9 + ...metadata_automation_token_used_metadata.py | 100 ++++ ...tadata_automation_token_used_metadata_t.py | 9 + ...etadata_email_change_requested_metadata.py | 81 ++++ ...adata_email_change_requested_metadata_t.py | 9 + .../audit_metadata_email_changed_metadata.py | 89 ++++ ...audit_metadata_email_changed_metadata_t.py | 9 + .../models/audit_metadata_login_metadata.py | 82 ++++ .../models/audit_metadata_login_metadata_t.py | 9 + ...udit_metadata_o_auth_connected_metadata.py | 81 ++++ ...it_metadata_o_auth_connected_metadata_t.py | 9 + ...t_metadata_o_auth_disconnected_metadata.py | 81 ++++ ...metadata_o_auth_disconnected_metadata_t.py | 9 + ...udit_metadata_username_changed_metadata.py | 89 ++++ ...it_metadata_username_changed_metadata_t.py | 9 + openshock/rest/models/automation_token_dto.py | 197 ++++++++ .../rest/models/automation_token_type.py | 11 + openshock/rest/models/change_email_request.py | 70 +++ .../rest/models/change_password_request.py | 70 +++ .../models/configuration_add_item_request.py | 91 ++++ .../rest/models/configuration_item_dto.py | 106 +++++ .../configuration_update_item_request.py | 110 +++++ .../rest/models/configuration_value_type.py | 13 + .../models/create_automation_token_dto.py | 112 +++++ .../rest/models/create_token_request_v2.py | 127 +++++ .../models/created_automation_token_dto.py | 166 +++++++ .../rest/models/edit_token_request_v2.py | 95 ++++ .../rest/models/email_outbox_bulk_request.py | 72 +++ .../models/email_outbox_bulk_result_dto.py | 72 +++ .../rest/models/email_outbox_message_dto.py | 226 +++++++++ .../email_outbox_message_dto_payload.py | 46 ++ .../rest/models/email_outbox_stats_dto.py | 103 +++++ .../models/email_provider_blacklist_dto.py | 80 ++++ openshock/rest/models/email_status.py | 13 + openshock/rest/models/email_type.py | 12 + ...f_array_of_admin_online_device_response.py | 84 ++++ ...e_of_i_read_only_collection_of_ota_item.py | 84 ++++ .../rest/models/login_session_response.py | 203 ++++++++ openshock/rest/models/match_type_enum.py | 10 + .../rest/models/o_auth_connection_response.py | 93 ++++ openshock/rest/models/ota_item.py | 103 +++++ openshock/rest/models/ota_update_status.py | 13 + ...aged_result_of_audit_log_entry_response.py | 112 +++++ .../models/paginated_of_admin_users_view.py | 100 ++++ .../paginated_of_email_outbox_message_dto.py | 100 ++++ .../rest/models/password_hashing_algorithm.py | 11 + .../rest/models/patch_automation_token_dto.py | 154 +++++++ .../rest/models/report_tokens_request.py | 70 +++ openshock/rest/models/send_test_email_dto.py | 98 ++++ .../rest/models/set_token_paused_request.py | 62 +++ .../models/set_user_email_request_body.py | 62 +++ .../rest/models/set_user_name_request_body.py | 62 +++ .../models/set_user_password_request_body.py | 62 +++ .../rest/models/token_created_response_v2.py | 171 +++++++ .../rest/models/token_paused_response.py | 62 +++ .../rest/models/user_name_blacklist_dto.py | 90 ++++ openshock/rest/models/user_patch_dto.py | 94 ++++ openshock/rest/models/webhook_dto.py | 88 ++++ scripts/generate.py | 54 --- tests/test_generated.py | 76 +-- 155 files changed, 17385 insertions(+), 134 deletions(-) create mode 100644 openshock/rest/api/account/authenticated_account_change_email.py create mode 100644 openshock/rest/api/account/authenticated_account_change_password.py create mode 100644 openshock/rest/api/account/authenticated_account_change_username.py create mode 100644 openshock/rest/api/account/authenticated_account_deactivate.py create mode 100644 openshock/rest/api/account/authenticated_account_get_audit_log.py create mode 100644 openshock/rest/api/account/authenticated_account_list_o_auth_connections.py create mode 100644 openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py create mode 100644 openshock/rest/api/admin/__init__.py create mode 100644 openshock/rest/api/admin/admin_add_email_provider_blacklist.py create mode 100644 openshock/rest/api/admin/admin_add_username_blacklist.py create mode 100644 openshock/rest/api/admin/admin_add_webhook.py create mode 100644 openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_bulk_delete_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_cancel_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_configuration_add.py create mode 100644 openshock/rest/api/admin/admin_configuration_delete.py create mode 100644 openshock/rest/api/admin/admin_configuration_list.py create mode 100644 openshock/rest/api/admin/admin_configuration_update.py create mode 100644 openshock/rest/api/admin/admin_create_automation_token.py create mode 100644 openshock/rest/api/admin/admin_deactivate_user.py create mode 100644 openshock/rest/api/admin/admin_delete_api_token.py create mode 100644 openshock/rest/api/admin/admin_delete_automation_token.py create mode 100644 openshock/rest/api/admin/admin_delete_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_delete_user.py create mode 100644 openshock/rest/api/admin/admin_get_admin_audit_log.py create mode 100644 openshock/rest/api/admin/admin_get_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_get_email_outbox_stats.py create mode 100644 openshock/rest/api/admin/admin_get_online_devices.py create mode 100644 openshock/rest/api/admin/admin_get_online_gateways.py create mode 100644 openshock/rest/api/admin/admin_get_user_by_id.py create mode 100644 openshock/rest/api/admin/admin_get_users.py create mode 100644 openshock/rest/api/admin/admin_list_automation_tokens.py create mode 100644 openshock/rest/api/admin/admin_list_email_provider_blacklist.py create mode 100644 openshock/rest/api/admin/admin_list_username_blacklist.py create mode 100644 openshock/rest/api/admin/admin_list_webhooks.py create mode 100644 openshock/rest/api/admin/admin_modify_user.py create mode 100644 openshock/rest/api/admin/admin_patch_automation_token.py create mode 100644 openshock/rest/api/admin/admin_reactivate_user.py create mode 100644 openshock/rest/api/admin/admin_remove_email_provider_blacklist.py create mode 100644 openshock/rest/api/admin/admin_remove_username_blacklist.py create mode 100644 openshock/rest/api/admin/admin_remove_webhook.py create mode 100644 openshock/rest/api/admin/admin_requeue_email_outbox.py create mode 100644 openshock/rest/api/admin/admin_rotate_automation_token.py create mode 100644 openshock/rest/api/admin/admin_send_test_email.py create mode 100644 openshock/rest/api/admin/admin_set_user_email.py create mode 100644 openshock/rest/api/admin/admin_set_user_name.py create mode 100644 openshock/rest/api/admin/admin_set_user_password.py create mode 100644 openshock/rest/api/api_tokens/tokens_create_token_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_edit_token_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_list_tokens_v2.py create mode 100644 openshock/rest/api/api_tokens/tokens_report_tokens.py create mode 100644 openshock/rest/api/api_tokens/tokens_set_token_paused.py create mode 100644 openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py create mode 100644 openshock/rest/api/sessions/__init__.py create mode 100644 openshock/rest/api/sessions/sessions_delete_session.py create mode 100644 openshock/rest/api/sessions/sessions_get_self_session.py create mode 100644 openshock/rest/api/sessions/sessions_list_sessions.py create mode 100644 openshock/rest/api/shocker_shares/__init__.py create mode 100644 openshock/rest/api/shocker_shares/shares_delete_share_code.py create mode 100644 openshock/rest/api/shocker_shares/shares_link_share_code.py create mode 100644 openshock/rest/models/add_email_provider_blacklist_dto.py create mode 100644 openshock/rest/models/add_username_blacklist_dto.py create mode 100644 openshock/rest/models/add_webhook_dto.py create mode 100644 openshock/rest/models/admin_online_device_response.py create mode 100644 openshock/rest/models/admin_online_gateway_response.py create mode 100644 openshock/rest/models/admin_user_view.py create mode 100644 openshock/rest/models/admin_user_view_api_token.py create mode 100644 openshock/rest/models/admin_user_view_email_change.py create mode 100644 openshock/rest/models/admin_user_view_hub.py create mode 100644 openshock/rest/models/admin_user_view_name_change.py create mode 100644 openshock/rest/models/admin_user_view_password_reset.py create mode 100644 openshock/rest/models/admin_user_view_shocker.py create mode 100644 openshock/rest/models/admin_user_view_user_activation_request.py create mode 100644 openshock/rest/models/admin_user_view_user_deactivation.py create mode 100644 openshock/rest/models/admin_user_view_user_ref.py create mode 100644 openshock/rest/models/admin_users_view.py create mode 100644 openshock/rest/models/audit_action.py create mode 100644 openshock/rest/models/audit_log_entry_response.py create mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata.py create mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata.py create mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata.py create mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata.py create mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata.py create mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata.py create mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_login_metadata.py create mode 100644 openshock/rest/models/audit_metadata_login_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py create mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py create mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata.py create mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata_t.py create mode 100644 openshock/rest/models/automation_token_dto.py create mode 100644 openshock/rest/models/automation_token_type.py create mode 100644 openshock/rest/models/change_email_request.py create mode 100644 openshock/rest/models/change_password_request.py create mode 100644 openshock/rest/models/configuration_add_item_request.py create mode 100644 openshock/rest/models/configuration_item_dto.py create mode 100644 openshock/rest/models/configuration_update_item_request.py create mode 100644 openshock/rest/models/configuration_value_type.py create mode 100644 openshock/rest/models/create_automation_token_dto.py create mode 100644 openshock/rest/models/create_token_request_v2.py create mode 100644 openshock/rest/models/created_automation_token_dto.py create mode 100644 openshock/rest/models/edit_token_request_v2.py create mode 100644 openshock/rest/models/email_outbox_bulk_request.py create mode 100644 openshock/rest/models/email_outbox_bulk_result_dto.py create mode 100644 openshock/rest/models/email_outbox_message_dto.py create mode 100644 openshock/rest/models/email_outbox_message_dto_payload.py create mode 100644 openshock/rest/models/email_outbox_stats_dto.py create mode 100644 openshock/rest/models/email_provider_blacklist_dto.py create mode 100644 openshock/rest/models/email_status.py create mode 100644 openshock/rest/models/email_type.py create mode 100644 openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py create mode 100644 openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py create mode 100644 openshock/rest/models/login_session_response.py create mode 100644 openshock/rest/models/match_type_enum.py create mode 100644 openshock/rest/models/o_auth_connection_response.py create mode 100644 openshock/rest/models/ota_item.py create mode 100644 openshock/rest/models/ota_update_status.py create mode 100644 openshock/rest/models/paged_result_of_audit_log_entry_response.py create mode 100644 openshock/rest/models/paginated_of_admin_users_view.py create mode 100644 openshock/rest/models/paginated_of_email_outbox_message_dto.py create mode 100644 openshock/rest/models/password_hashing_algorithm.py create mode 100644 openshock/rest/models/patch_automation_token_dto.py create mode 100644 openshock/rest/models/report_tokens_request.py create mode 100644 openshock/rest/models/send_test_email_dto.py create mode 100644 openshock/rest/models/set_token_paused_request.py create mode 100644 openshock/rest/models/set_user_email_request_body.py create mode 100644 openshock/rest/models/set_user_name_request_body.py create mode 100644 openshock/rest/models/set_user_password_request_body.py create mode 100644 openshock/rest/models/token_created_response_v2.py create mode 100644 openshock/rest/models/token_paused_response.py create mode 100644 openshock/rest/models/user_name_blacklist_dto.py create mode 100644 openshock/rest/models/user_patch_dto.py create mode 100644 openshock/rest/models/webhook_dto.py diff --git a/README.md b/README.md index 7e80f02..35863ce 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ The official OpenShock Python SDK to integrate with an OpenShock backend easily. -- **REST API** — every endpoint an API token can call, generated from the backend's OpenAPI document, sync and async +- **REST API** — every endpoint and model, generated from the backend's OpenAPI document, sync and async - **Realtime events** — SignalR user hub: hub online state, executed commands, firmware updates - **Live control** — stream intensity to shockers in real time - Typed models and enums, typed errors, automatic reconnects, Python 3.11+ @@ -73,11 +73,7 @@ OpenShock team tell integrations apart. `openshock.rest` is generated from the backend's OpenAPI document with [openapi-python-client](https://github.com/openapi-generators/openapi-python-client). Nothing -in it is written by hand. - -It covers everything you can call with an API token or a hub's device token, plus the -endpoints that need no authentication. Admin endpoints and endpoints that only accept a -browser login session (managing API tokens and login sessions, account settings) are left out. +in it is written by hand, so it always covers the whole API. - **Operations** live in `openshock.rest.api.`, one module per endpoint. The module name is the endpoint's operation ID in snake case. @@ -89,13 +85,13 @@ browser login session (managing API tokens and login sessions, account settings) |-------------------------------|--------| | `shockers` | Shocker CRUD, control, pause, logs, share codes | | `hub_management` | Hubs: list, create, edit, pair code, gateway lookup, OTA history | -| `user_shocker_shares` | User-to-user shares and invites | +| `user_shocker_shares`, `shocker_shares` | User-to-user shares and invites | | `public_shocker_shares` | Public share links | -| `api_tokens` | The token you are using: inspect it, delete a token | -| `users`, `account` | Profile, and the unauthenticated account flows (sign-up, password reset) | +| `api_tokens` | API tokens | +| `users`, `account`, `sessions` | Profile, account settings, login sessions | | `meta` | Backend version and public stats | | `hub_endpoints` | What a hub device itself calls (see below) | -| `integrations` | Integrations | +| `integrations`, `admin` | Integrations and admin endpoints | Each operation module offers the same functions: @@ -309,8 +305,7 @@ python scripts/generate.py # regenerate from the committed snapshot python scripts/generate.py --check # what CI runs; fails if openshock/rest is out of date ``` -The script drops admin and session-only operations (and the models only they use) from the -document before generating. The generator and formatter versions are pinned in the `codegen` extra because they decide +The generator and formatter versions are pinned in the `codegen` extra because they decide the output. The script fails rather than emit a partial client if the generator skips anything. Hand-written code is limited to what the OpenAPI document cannot describe: the preconfigured diff --git a/openshock/rest/api/account/authenticated_account_change_email.py b/openshock/rest/api/account/authenticated_account_change_email.py new file mode 100644 index 0000000..61c9030 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_change_email.py @@ -0,0 +1,189 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.change_email_request import ChangeEmailRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ChangeEmailRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/email-change", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = OpenShockProblem.from_dict(response.json()) + + return response_401 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if response.status_code == 429: + response_429 = OpenShockProblem.from_dict(response.json()) + + return response_429 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Response[Any | OpenShockProblem]: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Any | OpenShockProblem | None: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Response[Any | OpenShockProblem]: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ChangeEmailRequest, +) -> Any | OpenShockProblem | None: + """Initiate an email change for the current user. A verification link is sent to the new + address; the change is not applied until that link is opened. + + Args: + body (ChangeEmailRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_password.py b/openshock/rest/api/account/authenticated_account_change_password.py new file mode 100644 index 0000000..278a24f --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_change_password.py @@ -0,0 +1,170 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.change_password_request import ChangePasswordRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ChangePasswordRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/password", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Response[Any | OpenShockProblem]: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Any | OpenShockProblem | None: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Response[Any | OpenShockProblem]: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ChangePasswordRequest, +) -> Any | OpenShockProblem | None: + """Change the password of the current user + + Args: + body (ChangePasswordRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_username.py b/openshock/rest/api/account/authenticated_account_change_username.py new file mode 100644 index 0000000..4f5f5c2 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_change_username.py @@ -0,0 +1,175 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.change_username_request import ChangeUsernameRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ChangeUsernameRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/account/username", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Response[Any | OpenShockProblem]: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Any | OpenShockProblem | None: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Response[Any | OpenShockProblem]: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ChangeUsernameRequest, +) -> Any | OpenShockProblem | None: + """Change the username of the current user + + Args: + body (ChangeUsernameRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_deactivate.py b/openshock/rest/api/account/authenticated_account_deactivate.py new file mode 100644 index 0000000..1c590a1 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_deactivate.py @@ -0,0 +1,133 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/account", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 204: + response_204 = cast(Any, None) + return response_204 + + if response.status_code == 403: + response_403 = OpenShockProblem.from_dict(response.json()) + + return response_403 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deactivate currently logged in account + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_get_audit_log.py b/openshock/rest/api/account/authenticated_account_get_audit_log.py new file mode 100644 index 0000000..36ca1f4 --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_get_audit_log.py @@ -0,0 +1,226 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse +from ...models.sort_direction import SortDirection +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["page"] = page + + params["pageSize"] = page_size + + params["search"] = search + + params["sort"] = sort + + json_sort_dir: str | Unset = UNSET + if not isinstance(sort_dir, Unset): + json_sort_dir = sort_dir.value + + params["sortDir"] = json_sort_dir + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/account/audit-log", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> PagedResultOfAuditLogEntryResponse | None: + if response.status_code == 200: + response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[PagedResultOfAuditLogEntryResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return sync_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get the audit log for the current user's account. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return ( + await asyncio_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py b/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py new file mode 100644 index 0000000..4bed30e --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py @@ -0,0 +1,134 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.o_auth_connection_response import OAuthConnectionResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/account/connections", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[OAuthConnectionResponse] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = OAuthConnectionResponse.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[OAuthConnectionResponse]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[OAuthConnectionResponse]]: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[OAuthConnectionResponse]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[OAuthConnectionResponse] | None: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[OAuthConnectionResponse] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[OAuthConnectionResponse]]: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[OAuthConnectionResponse]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[OAuthConnectionResponse] | None: + """List OAuth connections linked to the current user. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[OAuthConnectionResponse] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py b/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py new file mode 100644 index 0000000..d91c1ca --- /dev/null +++ b/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py @@ -0,0 +1,158 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + provider: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/account/connections/{provider}".format( + provider=quote(str(provider), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 204: + response_204 = cast(Any, None) + return response_204 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + provider: str, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + provider=provider, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + provider: str, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + provider=provider, + client=client, + ).parsed + + +async def asyncio_detailed( + provider: str, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + provider=provider, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + provider: str, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Remove an existing OAuth connection for the current user. + + Args: + provider (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + provider=provider, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/__init__.py b/openshock/rest/api/admin/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/admin/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/admin/admin_add_email_provider_blacklist.py b/openshock/rest/api/admin/admin_add_email_provider_blacklist.py new file mode 100644 index 0000000..2dcec86 --- /dev/null +++ b/openshock/rest/api/admin/admin_add_email_provider_blacklist.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto +from ...types import Response + + +def _get_kwargs( + *, + body: AddEmailProviderBlacklistDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/blacklist/emailProviders", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: AddEmailProviderBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddEmailProviderBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: AddEmailProviderBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddEmailProviderBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_username_blacklist.py b/openshock/rest/api/admin/admin_add_username_blacklist.py new file mode 100644 index 0000000..c5fbddb --- /dev/null +++ b/openshock/rest/api/admin/admin_add_username_blacklist.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.add_username_blacklist_dto import AddUsernameBlacklistDto +from ...types import Response + + +def _get_kwargs( + *, + body: AddUsernameBlacklistDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/blacklist/usernames", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: AddUsernameBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddUsernameBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: AddUsernameBlacklistDto, +) -> Response[Any]: + """ + Args: + body (AddUsernameBlacklistDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_webhook.py b/openshock/rest/api/admin/admin_add_webhook.py new file mode 100644 index 0000000..833d05d --- /dev/null +++ b/openshock/rest/api/admin/admin_add_webhook.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.add_webhook_dto import AddWebhookDto +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + *, + body: AddWebhookDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/webhooks", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = ProblemDetails.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Response[Any | ProblemDetails]: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Any | ProblemDetails | None: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Response[Any | ProblemDetails]: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: AddWebhookDto, +) -> Any | ProblemDetails | None: + """Creates a webhook + + Args: + body (AddWebhookDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py b/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py new file mode 100644 index 0000000..a4c511e --- /dev/null +++ b/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py @@ -0,0 +1,177 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest +from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from ...types import Response + + +def _get_kwargs( + *, + body: EmailOutboxBulkRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/bulk/cancel", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxBulkResultDto | None: + if response.status_code == 200: + response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxBulkResultDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are + not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were + actually cancelled. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py b/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py new file mode 100644 index 0000000..775933d --- /dev/null +++ b/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py @@ -0,0 +1,173 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest +from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from ...types import Response + + +def _get_kwargs( + *, + body: EmailOutboxBulkRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/bulk/delete", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxBulkResultDto | None: + if response.status_code == 200: + response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxBulkResultDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many + rows were actually deleted. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py b/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py new file mode 100644 index 0000000..5e3f3ed --- /dev/null +++ b/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py @@ -0,0 +1,177 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest +from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from ...types import Response + + +def _get_kwargs( + *, + body: EmailOutboxBulkRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/bulk/requeue", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxBulkResultDto | None: + if response.status_code == 200: + response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxBulkResultDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Response[Any | EmailOutboxBulkResultDto]: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxBulkResultDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: EmailOutboxBulkRequest, +) -> Any | EmailOutboxBulkResultDto | None: + """Requeues many email outbox messages at once. Each id is treated exactly like the single-message + requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing + ids are skipped. Returns how many rows were actually requeued. + + Args: + body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk + requeue/cancel/delete to. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxBulkResultDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_cancel_email_outbox.py b/openshock/rest/api/admin/admin_cancel_email_outbox.py new file mode 100644 index 0000000..6257ab1 --- /dev/null +++ b/openshock/rest/api/admin/admin_cancel_email_outbox.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/{id}/cancel".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = ProblemDetails.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only + pending messages can be cancelled; a message already being sent or in a terminal state cannot. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_add.py b/openshock/rest/api/admin/admin_configuration_add.py new file mode 100644 index 0000000..4347d91 --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_add.py @@ -0,0 +1,174 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.configuration_add_item_request import ConfigurationAddItemRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ConfigurationAddItemRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/config", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Response[Any | OpenShockProblem]: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Any | OpenShockProblem | None: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Response[Any | OpenShockProblem]: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ConfigurationAddItemRequest, +) -> Any | OpenShockProblem | None: + """Adds a new configuration + + Args: + body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_delete.py b/openshock/rest/api/admin/admin_configuration_delete.py new file mode 100644 index 0000000..7161385 --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_delete.py @@ -0,0 +1,169 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + name: str, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/config/{name}".format( + name=quote(str(name), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + name: str, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + name=name, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + name: str, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + name=name, + client=client, + ).parsed + + +async def asyncio_detailed( + name: str, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + name=name, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + name: str, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """Deletes a configuration + + Args: + name (str): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + name=name, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_list.py b/openshock/rest/api/admin/admin_configuration_list.py new file mode 100644 index 0000000..39dc4fd --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_list.py @@ -0,0 +1,138 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.configuration_item_dto import ConfigurationItemDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/config", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | list[ConfigurationItemDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = ConfigurationItemDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | list[ConfigurationItemDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[ConfigurationItemDto]]: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[ConfigurationItemDto]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | list[ConfigurationItemDto] | None: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[ConfigurationItemDto] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[ConfigurationItemDto]]: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[ConfigurationItemDto]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | list[ConfigurationItemDto] | None: + """Gets all configuration items + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[ConfigurationItemDto] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_update.py b/openshock/rest/api/admin/admin_configuration_update.py new file mode 100644 index 0000000..93f5294 --- /dev/null +++ b/openshock/rest/api/admin/admin_configuration_update.py @@ -0,0 +1,191 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.configuration_update_item_request import ConfigurationUpdateItemRequest +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + *, + body: ConfigurationUpdateItemRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/config", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Response[Any | OpenShockProblem]: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Any | OpenShockProblem | None: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Response[Any | OpenShockProblem]: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: ConfigurationUpdateItemRequest, +) -> Any | OpenShockProblem | None: + """Updates an existing configuration + + Args: + body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? + ConfigurationUpdateItemRequest.Value (or both) may be provided. + If both are null, no update action is performed. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_create_automation_token.py b/openshock/rest/api/admin/admin_create_automation_token.py new file mode 100644 index 0000000..8ebddfe --- /dev/null +++ b/openshock/rest/api/admin/admin_create_automation_token.py @@ -0,0 +1,161 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.create_automation_token_dto import CreateAutomationTokenDto +from ...models.created_automation_token_dto import CreatedAutomationTokenDto +from ...types import Response + + +def _get_kwargs( + *, + body: CreateAutomationTokenDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/automationTokens", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> CreatedAutomationTokenDto | None: + if response.status_code == 200: + response_200 = CreatedAutomationTokenDto.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[CreatedAutomationTokenDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> Response[CreatedAutomationTokenDto]: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> CreatedAutomationTokenDto | None: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> Response[CreatedAutomationTokenDto]: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: CreateAutomationTokenDto, +) -> CreatedAutomationTokenDto | None: + """Creates an automation token. The secret is only returned once, in this response + + Args: + body (CreateAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_deactivate_user.py b/openshock/rest/api/admin/admin_deactivate_user.py new file mode 100644 index 0000000..fb92e0d --- /dev/null +++ b/openshock/rest/api/admin/admin_deactivate_user.py @@ -0,0 +1,127 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + user_id: UUID, + *, + delete_later: bool | Unset = UNSET, + reason: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["deleteLater"] = delete_later + + params["reason"] = reason + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/deactivate".format( + user_id=quote(str(user_id), safe=""), + ), + "params": params, + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + delete_later: bool | Unset = UNSET, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deactivates a user + + Args: + user_id (UUID): + delete_later (bool | Unset): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + delete_later=delete_later, + reason=reason, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + delete_later: bool | Unset = UNSET, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deactivates a user + + Args: + user_id (UUID): + delete_later (bool | Unset): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + delete_later=delete_later, + reason=reason, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_api_token.py b/openshock/rest/api/admin/admin_delete_api_token.py new file mode 100644 index 0000000..aa2c018 --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_api_token.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import Response + + +def _get_kwargs( + token_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/apitokens/{token_id}".format( + token_id=quote(str(token_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any]: + """Deletes an API token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any]: + """Deletes an API token + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_automation_token.py b/openshock/rest/api/admin/admin_delete_automation_token.py new file mode 100644 index 0000000..0bc899c --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_automation_token.py @@ -0,0 +1,168 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/automationTokens/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = ProblemDetails.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Deletes an automation token together with every account it created. Refused while any of those + accounts holds a privileged role + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_delete_email_outbox.py b/openshock/rest/api/admin/admin_delete_email_outbox.py new file mode 100644 index 0000000..6a9034d --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_email_outbox.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/email/outbox/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds + the row gone and does nothing, so a delete never corrupts an in-flight send. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_delete_user.py b/openshock/rest/api/admin/admin_delete_user.py new file mode 100644 index 0000000..4de0110 --- /dev/null +++ b/openshock/rest/api/admin/admin_delete_user.py @@ -0,0 +1,118 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + user_id: UUID, + *, + reason: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["reason"] = reason + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/users/{user_id}".format( + user_id=quote(str(user_id), safe=""), + ), + "params": params, + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deletes a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Deletes a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_get_admin_audit_log.py b/openshock/rest/api/admin/admin_get_admin_audit_log.py new file mode 100644 index 0000000..55d480b --- /dev/null +++ b/openshock/rest/api/admin/admin_get_admin_audit_log.py @@ -0,0 +1,263 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse +from ...models.sort_direction import SortDirection +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["page"] = page + + params["pageSize"] = page_size + + params["search"] = search + + params["sort"] = sort + + json_sort_dir: str | Unset = UNSET + if not isinstance(sort_dir, Unset): + json_sort_dir = sort_dir.value + + params["sortDir"] = json_sort_dir + + json_user_id: str | Unset = UNSET + if not isinstance(user_id, Unset): + json_user_id = str(user_id) + params["userId"] = json_user_id + + json_actor_id: str | Unset = UNSET + if not isinstance(actor_id, Unset): + json_actor_id = str(actor_id) + params["actorId"] = json_actor_id + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/audit-log", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> PagedResultOfAuditLogEntryResponse | None: + if response.status_code == 200: + response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[PagedResultOfAuditLogEntryResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return sync_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> Response[PagedResultOfAuditLogEntryResponse]: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PagedResultOfAuditLogEntryResponse] + """ + + kwargs = _get_kwargs( + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + page: int | Unset = UNSET, + page_size: int | Unset = UNSET, + search: str | Unset = UNSET, + sort: str | Unset = UNSET, + sort_dir: SortDirection | Unset = UNSET, + user_id: UUID | Unset = UNSET, + actor_id: UUID | Unset = UNSET, +) -> PagedResultOfAuditLogEntryResponse | None: + """Get audit log entries across all users. Optionally filter by subject user or actor. + + Args: + page (int | Unset): + page_size (int | Unset): + search (str | Unset): + sort (str | Unset): + sort_dir (SortDirection | Unset): Sort direction for list endpoints. + user_id (UUID | Unset): + actor_id (UUID | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PagedResultOfAuditLogEntryResponse + """ + + return ( + await asyncio_detailed( + client=client, + page=page, + page_size=page_size, + search=search, + sort=sort, + sort_dir=sort_dir, + user_id=user_id, + actor_id=actor_id, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox.py b/openshock/rest/api/admin/admin_get_email_outbox.py new file mode 100644 index 0000000..af7ea09 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_email_outbox.py @@ -0,0 +1,218 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["$filter"] = filter_ + + params["$orderby"] = orderby + + params["$offset"] = offset + + params["$limit"] = limit + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/email/outbox", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | PaginatedOfEmailOutboxMessageDto | None: + if response.status_code == 200: + response_200 = PaginatedOfEmailOutboxMessageDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfEmailOutboxMessageDto] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfEmailOutboxMessageDto | None: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfEmailOutboxMessageDto + """ + + return sync_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfEmailOutboxMessageDto] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfEmailOutboxMessageDto | None: + """Lists email outbox messages, paginated. Supports the same OData-style + `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, + `recipient ilike '%@example.com'`). Defaults to newest first. + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfEmailOutboxMessageDto + """ + + return ( + await asyncio_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox_stats.py b/openshock/rest/api/admin/admin_get_email_outbox_stats.py new file mode 100644 index 0000000..1e97d6d --- /dev/null +++ b/openshock/rest/api/admin/admin_get_email_outbox_stats.py @@ -0,0 +1,133 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_stats_dto import EmailOutboxStatsDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/email/outbox/stats", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxStatsDto | None: + if response.status_code == 200: + response_200 = EmailOutboxStatsDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxStatsDto]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | EmailOutboxStatsDto]: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxStatsDto] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | EmailOutboxStatsDto | None: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxStatsDto + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | EmailOutboxStatsDto]: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxStatsDto] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | EmailOutboxStatsDto | None: + """Returns the number of email outbox messages in each delivery state. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxStatsDto + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_devices.py b/openshock/rest/api/admin/admin_get_online_devices.py new file mode 100644 index 0000000..038a002 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_online_devices.py @@ -0,0 +1,135 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_array_of_admin_online_device_response import ( + LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, +) +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/monitoring/onlineDevices", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: + """Gets all online devices + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_gateways.py b/openshock/rest/api/admin/admin_get_online_gateways.py new file mode 100644 index 0000000..8e655a1 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_online_gateways.py @@ -0,0 +1,138 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.admin_online_gateway_response import AdminOnlineGatewayResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/monitoring/gateways", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | list[AdminOnlineGatewayResponse] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = AdminOnlineGatewayResponse.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | list[AdminOnlineGatewayResponse]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[AdminOnlineGatewayResponse]]: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[AdminOnlineGatewayResponse]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | list[AdminOnlineGatewayResponse] | None: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[AdminOnlineGatewayResponse] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[AdminOnlineGatewayResponse]]: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[AdminOnlineGatewayResponse]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | list[AdminOnlineGatewayResponse] | None: + """Gets all online gateways + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[AdminOnlineGatewayResponse] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_user_by_id.py b/openshock/rest/api/admin/admin_get_user_by_id.py new file mode 100644 index 0000000..0cdfef5 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_user_by_id.py @@ -0,0 +1,167 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.admin_user_view import AdminUserView +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + user_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/users/{user_id}".format( + user_id=quote(str(user_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> AdminUserView | Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = AdminUserView.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[AdminUserView | Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[AdminUserView | Any | ProblemDetails]: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AdminUserView | Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> AdminUserView | Any | ProblemDetails | None: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AdminUserView | Any | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[AdminUserView | Any | ProblemDetails]: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AdminUserView | Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, +) -> AdminUserView | Any | ProblemDetails | None: + """Gets a user by id + + Args: + user_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AdminUserView | Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_get_users.py b/openshock/rest/api/admin/admin_get_users.py new file mode 100644 index 0000000..87e1045 --- /dev/null +++ b/openshock/rest/api/admin/admin_get_users.py @@ -0,0 +1,210 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.paginated_of_admin_users_view import PaginatedOfAdminUsersView +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["$filter"] = filter_ + + params["$orderby"] = orderby + + params["$offset"] = offset + + params["$limit"] = limit + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/users", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | PaginatedOfAdminUsersView | None: + if response.status_code == 200: + response_200 = PaginatedOfAdminUsersView.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | PaginatedOfAdminUsersView]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfAdminUsersView]: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfAdminUsersView] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfAdminUsersView | None: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfAdminUsersView + """ + + return sync_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Response[Any | PaginatedOfAdminUsersView]: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | PaginatedOfAdminUsersView] + """ + + kwargs = _get_kwargs( + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + filter_: str | Unset = "", + orderby: str | Unset = "", + offset: int | Unset = 0, + limit: int | Unset = 100, +) -> Any | PaginatedOfAdminUsersView | None: + """Gets all users, paginated + + Args: + filter_ (str | Unset): Default: ''. + orderby (str | Unset): Default: ''. + offset (int | Unset): Default: 0. + limit (int | Unset): Default: 100. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | PaginatedOfAdminUsersView + """ + + return ( + await asyncio_detailed( + client=client, + filter_=filter_, + orderby=orderby, + offset=offset, + limit=limit, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_automation_tokens.py b/openshock/rest/api/admin/admin_list_automation_tokens.py new file mode 100644 index 0000000..23171a0 --- /dev/null +++ b/openshock/rest/api/admin/admin_list_automation_tokens.py @@ -0,0 +1,134 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.automation_token_dto import AutomationTokenDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/automationTokens", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[AutomationTokenDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = AutomationTokenDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[AutomationTokenDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[AutomationTokenDto]]: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[AutomationTokenDto]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[AutomationTokenDto] | None: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[AutomationTokenDto] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[AutomationTokenDto]]: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[AutomationTokenDto]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[AutomationTokenDto] | None: + """Lists all automation tokens + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[AutomationTokenDto] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_email_provider_blacklist.py b/openshock/rest/api/admin/admin_list_email_provider_blacklist.py new file mode 100644 index 0000000..f6011ba --- /dev/null +++ b/openshock/rest/api/admin/admin_list_email_provider_blacklist.py @@ -0,0 +1,162 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_provider_blacklist_dto import EmailProviderBlacklistDto +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + match: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["match"] = match + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/blacklist/emailProviders", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[EmailProviderBlacklistDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = EmailProviderBlacklistDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[EmailProviderBlacklistDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[EmailProviderBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[EmailProviderBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[EmailProviderBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[EmailProviderBlacklistDto] + """ + + return sync_detailed( + client=client, + match=match, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[EmailProviderBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[EmailProviderBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[EmailProviderBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[EmailProviderBlacklistDto] + """ + + return ( + await asyncio_detailed( + client=client, + match=match, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_username_blacklist.py b/openshock/rest/api/admin/admin_list_username_blacklist.py new file mode 100644 index 0000000..c1f1b45 --- /dev/null +++ b/openshock/rest/api/admin/admin_list_username_blacklist.py @@ -0,0 +1,162 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.user_name_blacklist_dto import UserNameBlacklistDto +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + match: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["match"] = match + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/blacklist/usernames", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[UserNameBlacklistDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = UserNameBlacklistDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[UserNameBlacklistDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[UserNameBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[UserNameBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[UserNameBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[UserNameBlacklistDto] + """ + + return sync_detailed( + client=client, + match=match, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> Response[list[UserNameBlacklistDto]]: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[UserNameBlacklistDto]] + """ + + kwargs = _get_kwargs( + match=match, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + match: str | Unset = UNSET, +) -> list[UserNameBlacklistDto] | None: + """ + Args: + match (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[UserNameBlacklistDto] + """ + + return ( + await asyncio_detailed( + client=client, + match=match, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_list_webhooks.py b/openshock/rest/api/admin/admin_list_webhooks.py new file mode 100644 index 0000000..87efc54 --- /dev/null +++ b/openshock/rest/api/admin/admin_list_webhooks.py @@ -0,0 +1,138 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.webhook_dto import WebhookDto +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/admin/webhooks", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | list[WebhookDto] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = WebhookDto.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | list[WebhookDto]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[WebhookDto]]: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[WebhookDto]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> Any | list[WebhookDto] | None: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[WebhookDto] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[Any | list[WebhookDto]]: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | list[WebhookDto]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> Any | list[WebhookDto] | None: + """List webhooks + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | list[WebhookDto] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_modify_user.py b/openshock/rest/api/admin/admin_modify_user.py new file mode 100644 index 0000000..fa09ec9 --- /dev/null +++ b/openshock/rest/api/admin/admin_modify_user.py @@ -0,0 +1,121 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.user_patch_dto import UserPatchDto +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: UserPatchDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/admin/users/{user_id}".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if response.status_code == 404: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: UserPatchDto, +) -> Response[Any]: + """Edits a user + + Args: + user_id (UUID): + body (UserPatchDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: UserPatchDto, +) -> Response[Any]: + """Edits a user + + Args: + user_id (UUID): + body (UserPatchDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_patch_automation_token.py b/openshock/rest/api/admin/admin_patch_automation_token.py new file mode 100644 index 0000000..53798c1 --- /dev/null +++ b/openshock/rest/api/admin/admin_patch_automation_token.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.automation_token_dto import AutomationTokenDto +from ...models.patch_automation_token_dto import PatchAutomationTokenDto +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, + *, + body: PatchAutomationTokenDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/1/admin/automationTokens/{id}".format( + id=quote(str(id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> AutomationTokenDto | ProblemDetails | None: + if response.status_code == 200: + response_200 = AutomationTokenDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[AutomationTokenDto | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> Response[AutomationTokenDto | ProblemDetails]: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> AutomationTokenDto | ProblemDetails | None: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AutomationTokenDto | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> Response[AutomationTokenDto | ProblemDetails]: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, + body: PatchAutomationTokenDto, +) -> AutomationTokenDto | ProblemDetails | None: + """Updates an automation token + + Args: + id (UUID): + body (PatchAutomationTokenDto): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AutomationTokenDto | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_reactivate_user.py b/openshock/rest/api/admin/admin_reactivate_user.py new file mode 100644 index 0000000..8a950b1 --- /dev/null +++ b/openshock/rest/api/admin/admin_reactivate_user.py @@ -0,0 +1,118 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + user_id: UUID, + *, + reason: str | Unset = UNSET, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["reason"] = reason + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/reactivate".format( + user_id=quote(str(user_id), safe=""), + ), + "params": params, + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if response.status_code == 401: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Reactivates a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + reason: str | Unset = UNSET, +) -> Response[Any]: + """Reactivates a user + + Args: + user_id (UUID): + reason (str | Unset): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + user_id=user_id, + reason=reason, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py b/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py new file mode 100644 index 0000000..e38dd29 --- /dev/null +++ b/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py @@ -0,0 +1,155 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/blacklist/emailProviders/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_remove_username_blacklist.py b/openshock/rest/api/admin/admin_remove_username_blacklist.py new file mode 100644 index 0000000..c019ba9 --- /dev/null +++ b/openshock/rest/api/admin/admin_remove_username_blacklist.py @@ -0,0 +1,155 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/blacklist/usernames/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """ + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_remove_webhook.py b/openshock/rest/api/admin/admin_remove_webhook.py new file mode 100644 index 0000000..3248192 --- /dev/null +++ b/openshock/rest/api/admin/admin_remove_webhook.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/admin/webhooks/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Removes a webhook + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_requeue_email_outbox.py b/openshock/rest/api/admin/admin_requeue_email_outbox.py new file mode 100644 index 0000000..4922023 --- /dev/null +++ b/openshock/rest/api/admin/admin_requeue_email_outbox.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/outbox/{id}/requeue".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = ProblemDetails.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | ProblemDetails]: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> Any | ProblemDetails | None: + """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, + with a fresh attempt budget, and nudges the delivery consumer to send it immediately. + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_rotate_automation_token.py b/openshock/rest/api/admin/admin_rotate_automation_token.py new file mode 100644 index 0000000..38a1b67 --- /dev/null +++ b/openshock/rest/api/admin/admin_rotate_automation_token.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.created_automation_token_dto import CreatedAutomationTokenDto +from ...models.problem_details import ProblemDetails +from ...types import Response + + +def _get_kwargs( + id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/automationTokens/{id}/rotate".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> CreatedAutomationTokenDto | ProblemDetails | None: + if response.status_code == 200: + response_200 = CreatedAutomationTokenDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[CreatedAutomationTokenDto | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[CreatedAutomationTokenDto | ProblemDetails]: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: UUID, + *, + client: AuthenticatedClient, +) -> CreatedAutomationTokenDto | ProblemDetails | None: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto | ProblemDetails + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: UUID, + *, + client: AuthenticatedClient, +) -> Response[CreatedAutomationTokenDto | ProblemDetails]: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[CreatedAutomationTokenDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: UUID, + *, + client: AuthenticatedClient, +) -> CreatedAutomationTokenDto | ProblemDetails | None: + """Rotates the secret of an automation token. The new secret is only returned once, in this response + + Args: + id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + CreatedAutomationTokenDto | ProblemDetails + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_send_test_email.py b/openshock/rest/api/admin/admin_send_test_email.py new file mode 100644 index 0000000..90bf759 --- /dev/null +++ b/openshock/rest/api/admin/admin_send_test_email.py @@ -0,0 +1,191 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.email_outbox_message_dto import EmailOutboxMessageDto +from ...models.problem_details import ProblemDetails +from ...models.send_test_email_dto import SendTestEmailDto +from ...types import Response + + +def _get_kwargs( + *, + body: SendTestEmailDto, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/admin/email/test", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | EmailOutboxMessageDto | ProblemDetails | None: + if response.status_code == 200: + response_200 = EmailOutboxMessageDto.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = ProblemDetails.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxMessageDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Any | EmailOutboxMessageDto | ProblemDetails | None: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxMessageDto | ProblemDetails + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | EmailOutboxMessageDto | ProblemDetails] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: SendTestEmailDto, +) -> Any | EmailOutboxMessageDto | ProblemDetails | None: + """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the + normal durable delivery pipeline - visible in the outbox listing - but is rendered with + placeholder data and a dummy link, so it touches no request row and mints no token. + + Args: + body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a + chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no + request row). + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | EmailOutboxMessageDto | ProblemDetails + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_email.py b/openshock/rest/api/admin/admin_set_user_email.py new file mode 100644 index 0000000..a8fee2d --- /dev/null +++ b/openshock/rest/api/admin/admin_set_user_email.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.problem_details import ProblemDetails +from ...models.set_user_email_request_body import SetUserEmailRequestBody +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: SetUserEmailRequestBody, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/email".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Response[Any | ProblemDetails]: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Any | ProblemDetails | None: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Response[Any | ProblemDetails]: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserEmailRequestBody, +) -> Any | ProblemDetails | None: + """Sets a users email to the supplied value + + Args: + user_id (UUID): + body (SetUserEmailRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_name.py b/openshock/rest/api/admin/admin_set_user_name.py new file mode 100644 index 0000000..fc6ff10 --- /dev/null +++ b/openshock/rest/api/admin/admin_set_user_name.py @@ -0,0 +1,192 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.problem_details import ProblemDetails +from ...models.set_user_name_request_body import SetUserNameRequestBody +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: SetUserNameRequestBody, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/name".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserNameRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users name to the supplied value + + Args: + user_id (UUID): + body (SetUserNameRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_password.py b/openshock/rest/api/admin/admin_set_user_password.py new file mode 100644 index 0000000..60ab728 --- /dev/null +++ b/openshock/rest/api/admin/admin_set_user_password.py @@ -0,0 +1,192 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.problem_details import ProblemDetails +from ...models.set_user_password_request_body import SetUserPasswordRequestBody +from ...types import Response + + +def _get_kwargs( + user_id: UUID, + *, + body: SetUserPasswordRequestBody, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "put", + "url": "/1/admin/users/{user_id}/password".format( + user_id=quote(str(user_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | ProblemDetails | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 401: + response_401 = cast(Any, None) + return response_401 + + if response.status_code == 404: + response_404 = ProblemDetails.from_dict(response.json()) + + return response_404 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem | ProblemDetails]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return sync_detailed( + user_id=user_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Response[Any | OpenShockProblem | ProblemDetails]: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem | ProblemDetails] + """ + + kwargs = _get_kwargs( + user_id=user_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + user_id: UUID, + *, + client: AuthenticatedClient, + body: SetUserPasswordRequestBody, +) -> Any | OpenShockProblem | ProblemDetails | None: + """Sets a users password to the supplied value + + Args: + user_id (UUID): + body (SetUserPasswordRequestBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem | ProblemDetails + """ + + return ( + await asyncio_detailed( + user_id=user_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_create_token_v2.py b/openshock/rest/api/api_tokens/tokens_create_token_v2.py new file mode 100644 index 0000000..3c43d0b --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_create_token_v2.py @@ -0,0 +1,161 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.create_token_request_v2 import CreateTokenRequestV2 +from ...models.token_created_response_v2 import TokenCreatedResponseV2 +from ...types import Response + + +def _get_kwargs( + *, + body: CreateTokenRequestV2, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/2/tokens", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> TokenCreatedResponseV2 | None: + if response.status_code == 200: + response_200 = TokenCreatedResponseV2.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[TokenCreatedResponseV2]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> Response[TokenCreatedResponseV2]: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[TokenCreatedResponseV2] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> TokenCreatedResponseV2 | None: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + TokenCreatedResponseV2 + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> Response[TokenCreatedResponseV2]: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[TokenCreatedResponseV2] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, + body: CreateTokenRequestV2, +) -> TokenCreatedResponseV2 | None: + """Create a new token + + Args: + body (CreateTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + TokenCreatedResponseV2 + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_edit_token_v2.py b/openshock/rest/api/api_tokens/tokens_edit_token_v2.py new file mode 100644 index 0000000..6c71df2 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_edit_token_v2.py @@ -0,0 +1,182 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.edit_token_request_v2 import EditTokenRequestV2 +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + token_id: UUID, + *, + body: EditTokenRequestV2, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/2/tokens/{token_id}".format( + token_id=quote(str(token_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Response[Any | OpenShockProblem]: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Any | OpenShockProblem | None: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + token_id=token_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Response[Any | OpenShockProblem]: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + token_id: UUID, + *, + client: AuthenticatedClient, + body: EditTokenRequestV2, +) -> Any | OpenShockProblem | None: + """Edit a token + + Args: + token_id (UUID): + body (EditTokenRequestV2): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + token_id=token_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py b/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py new file mode 100644 index 0000000..651c565 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.token_response_v2 import TokenResponseV2 +from ...types import Response + + +def _get_kwargs( + token_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/tokens/{token_id}".format( + token_id=quote(str(token_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> OpenShockProblem | TokenResponseV2 | None: + if response.status_code == 200: + response_200 = TokenResponseV2.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[OpenShockProblem | TokenResponseV2]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[OpenShockProblem | TokenResponseV2]: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenResponseV2] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> OpenShockProblem | TokenResponseV2 | None: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenResponseV2 + """ + + return sync_detailed( + token_id=token_id, + client=client, + ).parsed + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[OpenShockProblem | TokenResponseV2]: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenResponseV2] + """ + + kwargs = _get_kwargs( + token_id=token_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + token_id: UUID, + *, + client: AuthenticatedClient, +) -> OpenShockProblem | TokenResponseV2 | None: + """Get a token by id + + Args: + token_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenResponseV2 + """ + + return ( + await asyncio_detailed( + token_id=token_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py b/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py new file mode 100644 index 0000000..f0a4125 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py @@ -0,0 +1,132 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.token_response_v2 import TokenResponseV2 +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/2/tokens", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> list[TokenResponseV2] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = TokenResponseV2.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[TokenResponseV2]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[TokenResponseV2]]: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[TokenResponseV2]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[TokenResponseV2] | None: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[TokenResponseV2] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[TokenResponseV2]]: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[TokenResponseV2]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[TokenResponseV2] | None: + """List all tokens for the current user + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[TokenResponseV2] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_report_tokens.py b/openshock/rest/api/api_tokens/tokens_report_tokens.py new file mode 100644 index 0000000..b505c71 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_report_tokens.py @@ -0,0 +1,104 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.report_tokens_request import ReportTokensRequest +from ...types import Response + + +def _get_kwargs( + *, + body: ReportTokensRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/tokens/report", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: + if response.status_code == 200: + return None + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, + body: ReportTokensRequest, +) -> Response[Any]: + """Endpoint to delete potentially compromised api tokens + + Args: + body (ReportTokensRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, + body: ReportTokensRequest, +) -> Response[Any]: + """Endpoint to delete potentially compromised api tokens + + Args: + body (ReportTokensRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any] + """ + + kwargs = _get_kwargs( + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) diff --git a/openshock/rest/api/api_tokens/tokens_set_token_paused.py b/openshock/rest/api/api_tokens/tokens_set_token_paused.py new file mode 100644 index 0000000..feefc15 --- /dev/null +++ b/openshock/rest/api/api_tokens/tokens_set_token_paused.py @@ -0,0 +1,184 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...models.set_token_paused_request import SetTokenPausedRequest +from ...models.token_paused_response import TokenPausedResponse +from ...types import Response + + +def _get_kwargs( + token_id: UUID, + *, + body: SetTokenPausedRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "patch", + "url": "/2/tokens/{token_id}/paused".format( + token_id=quote(str(token_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> OpenShockProblem | TokenPausedResponse | None: + if response.status_code == 200: + response_200 = TokenPausedResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[OpenShockProblem | TokenPausedResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> Response[OpenShockProblem | TokenPausedResponse]: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenPausedResponse] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> OpenShockProblem | TokenPausedResponse | None: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenPausedResponse + """ + + return sync_detailed( + token_id=token_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> Response[OpenShockProblem | TokenPausedResponse]: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[OpenShockProblem | TokenPausedResponse] + """ + + kwargs = _get_kwargs( + token_id=token_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + token_id: UUID, + *, + client: AuthenticatedClient, + body: SetTokenPausedRequest, +) -> OpenShockProblem | TokenPausedResponse | None: + """Set whether a token is paused. A paused token may not send shocker control messages. + + Args: + token_id (UUID): + body (SetTokenPausedRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + OpenShockProblem | TokenPausedResponse + """ + + return ( + await asyncio_detailed( + token_id=token_id, + client=client, + body=body, + ) + ).parsed diff --git a/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py b/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py new file mode 100644 index 0000000..ce2caf2 --- /dev/null +++ b/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py @@ -0,0 +1,165 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_data_response_of_i_read_only_collection_of_ota_item import ( + LegacyDataResponseOfIReadOnlyCollectionOfOtaItem, +) +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + device_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/devices/{device_id}/ota".format( + device_id=quote(str(device_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyDataResponseOfIReadOnlyCollectionOfOtaItem.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem + """ + + return sync_detailed( + device_id=device_id, + client=client, + ).parsed + + +async def asyncio_detailed( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] + """ + + kwargs = _get_kwargs( + device_id=device_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + device_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: + """Gets the OTA update history for a device + + Args: + device_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem + """ + + return ( + await asyncio_detailed( + device_id=device_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/sessions/__init__.py b/openshock/rest/api/sessions/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/sessions/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/sessions/sessions_delete_session.py b/openshock/rest/api/sessions/sessions_delete_session.py new file mode 100644 index 0000000..f5f1179 --- /dev/null +++ b/openshock/rest/api/sessions/sessions_delete_session.py @@ -0,0 +1,157 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + session_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/sessions/{session_id}".format( + session_id=quote(str(session_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | OpenShockProblem | None: + if response.status_code == 200: + response_200 = cast(Any, None) + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + session_id=session_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return sync_detailed( + session_id=session_id, + client=client, + ).parsed + + +async def asyncio_detailed( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | OpenShockProblem]: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | OpenShockProblem] + """ + + kwargs = _get_kwargs( + session_id=session_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + session_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | OpenShockProblem | None: + """ + Args: + session_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | OpenShockProblem + """ + + return ( + await asyncio_detailed( + session_id=session_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/sessions/sessions_get_self_session.py b/openshock/rest/api/sessions/sessions_get_self_session.py new file mode 100644 index 0000000..70302aa --- /dev/null +++ b/openshock/rest/api/sessions/sessions_get_self_session.py @@ -0,0 +1,127 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.login_session_response import LoginSessionResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/sessions/self", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> LoginSessionResponse | None: + if response.status_code == 200: + response_200 = LoginSessionResponse.from_dict(response.json()) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LoginSessionResponse]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[LoginSessionResponse]: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LoginSessionResponse] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> LoginSessionResponse | None: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LoginSessionResponse + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[LoginSessionResponse]: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LoginSessionResponse] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> LoginSessionResponse | None: + """Gets information about the current token used to access this endpoint + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LoginSessionResponse + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/sessions/sessions_list_sessions.py b/openshock/rest/api/sessions/sessions_list_sessions.py new file mode 100644 index 0000000..48a8244 --- /dev/null +++ b/openshock/rest/api/sessions/sessions_list_sessions.py @@ -0,0 +1,130 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.login_session_response import LoginSessionResponse +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/1/sessions", + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> list[LoginSessionResponse] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = LoginSessionResponse.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[list[LoginSessionResponse]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[LoginSessionResponse]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[LoginSessionResponse]] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient, +) -> list[LoginSessionResponse] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[LoginSessionResponse] + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient, +) -> Response[list[LoginSessionResponse]]: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[list[LoginSessionResponse]] + """ + + kwargs = _get_kwargs() + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient, +) -> list[LoginSessionResponse] | None: + """ + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + list[LoginSessionResponse] + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shocker_shares/__init__.py b/openshock/rest/api/shocker_shares/__init__.py new file mode 100644 index 0000000..181fdd9 --- /dev/null +++ b/openshock/rest/api/shocker_shares/__init__.py @@ -0,0 +1,2 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/shocker_shares/shares_delete_share_code.py b/openshock/rest/api/shocker_shares/shares_delete_share_code.py new file mode 100644 index 0000000..4f89f58 --- /dev/null +++ b/openshock/rest/api/shocker_shares/shares_delete_share_code.py @@ -0,0 +1,163 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + share_code_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/1/shares/code/{share_code_id}".format( + share_code_id=quote(str(share_code_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + share_code_id=share_code_id, + client=client, + ).parsed + + +async def asyncio_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[LegacyEmptyResponse | OpenShockProblem]: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> LegacyEmptyResponse | OpenShockProblem | None: + """Delete a share code + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + share_code_id=share_code_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/api/shocker_shares/shares_link_share_code.py b/openshock/rest/api/shocker_shares/shares_link_share_code.py new file mode 100644 index 0000000..a6463ae --- /dev/null +++ b/openshock/rest/api/shocker_shares/shares_link_share_code.py @@ -0,0 +1,172 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote +from uuid import UUID + +import httpx2 + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.open_shock_problem import OpenShockProblem +from ...types import Response + + +def _get_kwargs( + share_code_id: UUID, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/1/shares/code/{share_code_id}".format( + share_code_id=quote(str(share_code_id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + if response.status_code == 200: + response_200 = LegacyEmptyResponse.from_dict(response.json()) + + return response_200 + + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) + + return response_404 + + if response.status_code == 500: + response_500 = cast(Any, None) + return response_500 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx2.Response +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyEmptyResponse | OpenShockProblem + """ + + return sync_detailed( + share_code_id=share_code_id, + client=client, + ).parsed + + +async def asyncio_detailed( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | LegacyEmptyResponse | OpenShockProblem] + """ + + kwargs = _get_kwargs( + share_code_id=share_code_id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + share_code_id: UUID, + *, + client: AuthenticatedClient, +) -> Any | LegacyEmptyResponse | OpenShockProblem | None: + """Link a share code to your account + + Args: + share_code_id (UUID): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx2.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | LegacyEmptyResponse | OpenShockProblem + """ + + return ( + await asyncio_detailed( + share_code_id=share_code_id, + client=client, + ) + ).parsed diff --git a/openshock/rest/models/__init__.py b/openshock/rest/models/__init__.py index 6f13201..ab386b7 100644 --- a/openshock/rest/models/__init__.py +++ b/openshock/rest/models/__init__.py @@ -1,10 +1,64 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. """Contains all the data models used in inputs/outputs""" +from .add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto +from .add_username_blacklist_dto import AddUsernameBlacklistDto +from .add_webhook_dto import AddWebhookDto +from .admin_online_device_response import AdminOnlineDeviceResponse +from .admin_online_gateway_response import AdminOnlineGatewayResponse +from .admin_user_view import AdminUserView +from .admin_user_view_api_token import AdminUserViewApiToken +from .admin_user_view_email_change import AdminUserViewEmailChange +from .admin_user_view_hub import AdminUserViewHub +from .admin_user_view_name_change import AdminUserViewNameChange +from .admin_user_view_password_reset import AdminUserViewPasswordReset +from .admin_user_view_shocker import AdminUserViewShocker +from .admin_user_view_user_activation_request import AdminUserViewUserActivationRequest +from .admin_user_view_user_deactivation import AdminUserViewUserDeactivation +from .admin_user_view_user_ref import AdminUserViewUserRef +from .admin_users_view import AdminUsersView +from .audit_action import AuditAction +from .audit_log_entry_response import AuditLogEntryResponse +from .audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata +from .audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT +from .audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata +from .audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT +from .audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata +from .audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT +from .audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata +from .audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT +from .audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata +from .audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT +from .audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata +from .audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT +from .audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata +from .audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT +from .audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata +from .audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT +from .audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata +from .audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT +from .audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata +from .audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT +from .audit_metadata_login_metadata import AuditMetadataLoginMetadata +from .audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT +from .audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata +from .audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT +from .audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata +from .audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT +from .audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata +from .audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT +from .automation_token_dto import AutomationTokenDto +from .automation_token_type import AutomationTokenType from .backend_info_response import BackendInfoResponse from .basic_user_info import BasicUserInfo from .bulk_user_share_shockers_update_request import BulkUserShareShockersUpdateRequest +from .change_email_request import ChangeEmailRequest +from .change_password_request import ChangePasswordRequest from .change_username_request import ChangeUsernameRequest +from .configuration_add_item_request import ConfigurationAddItemRequest +from .configuration_item_dto import ConfigurationItemDto +from .configuration_update_item_request import ConfigurationUpdateItemRequest +from .configuration_value_type import ConfigurationValueType from .control import Control from .control_limit_mode import ControlLimitMode from .control_log_sender_light import ControlLogSenderLight @@ -14,19 +68,34 @@ from .control_stat_totals import ControlStatTotals from .control_stats_response import ControlStatsResponse from .control_type import ControlType +from .create_automation_token_dto import CreateAutomationTokenDto from .create_share_request import CreateShareRequest +from .create_token_request_v2 import CreateTokenRequestV2 +from .created_automation_token_dto import CreatedAutomationTokenDto from .daily_control_stats import DailyControlStats from .device_response import DeviceResponse from .device_self_response import DeviceSelfResponse from .device_with_shockers_response import DeviceWithShockersResponse from .device_with_token_response import DeviceWithTokenResponse from .duration_limit_settings import DurationLimitSettings +from .edit_token_request_v2 import EditTokenRequestV2 +from .email_outbox_bulk_request import EmailOutboxBulkRequest +from .email_outbox_bulk_result_dto import EmailOutboxBulkResultDto +from .email_outbox_message_dto import EmailOutboxMessageDto +from .email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload +from .email_outbox_stats_dto import EmailOutboxStatsDto +from .email_provider_blacklist_dto import EmailProviderBlacklistDto +from .email_status import EmailStatus +from .email_type import EmailType from .given_control_stats import GivenControlStats from .hub_create_request import HubCreateRequest from .hub_edit_request import HubEditRequest from .intensity_limit_settings import IntensityLimitSettings from .lcg_node_response_v2 import LcgNodeResponseV2 from .lcg_response_v2 import LcgResponseV2 +from .legacy_data_response_of_array_of_admin_online_device_response import ( + LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, +) from .legacy_data_response_of_array_of_device_response import LegacyDataResponseOfArrayOfDeviceResponse from .legacy_data_response_of_array_of_device_with_shockers_response import ( LegacyDataResponseOfArrayOfDeviceWithShockersResponse, @@ -43,6 +112,7 @@ from .legacy_data_response_of_device_self_response import LegacyDataResponseOfDeviceSelfResponse from .legacy_data_response_of_device_with_token_response import LegacyDataResponseOfDeviceWithTokenResponse from .legacy_data_response_of_guid import LegacyDataResponseOfGuid +from .legacy_data_response_of_i_read_only_collection_of_ota_item import LegacyDataResponseOfIReadOnlyCollectionOfOtaItem from .legacy_data_response_of_legacy_user_self_response import LegacyDataResponseOfLegacyUserSelfResponse from .legacy_data_response_of_pause_reason import LegacyDataResponseOfPauseReason from .legacy_data_response_of_public_share_response import LegacyDataResponseOfPublicShareResponse @@ -54,16 +124,26 @@ from .legacy_user_self_response import LegacyUserSelfResponse from .log_entry import LogEntry from .log_entry_with_hub import LogEntryWithHub +from .login_session_response import LoginSessionResponse from .login_v2 import LoginV2 from .login_v2_ok_response import LoginV2OkResponse +from .match_type_enum import MatchTypeEnum from .minimal_shocker import MinimalShocker from .new_shocker import NewShocker +from .o_auth_connection_response import OAuthConnectionResponse from .open_shock_problem import OpenShockProblem +from .ota_item import OtaItem +from .ota_update_status import OtaUpdateStatus from .own_public_share_response import OwnPublicShareResponse from .owner_shocker_response import OwnerShockerResponse +from .paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse from .paged_result_of_log_entry_with_hub import PagedResultOfLogEntryWithHub +from .paginated_of_admin_users_view import PaginatedOfAdminUsersView +from .paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto +from .password_hashing_algorithm import PasswordHashingAlgorithm from .password_reset_process_data import PasswordResetProcessData from .password_reset_request_v2 import PasswordResetRequestV2 +from .patch_automation_token_dto import PatchAutomationTokenDto from .pause_request import PauseRequest from .pause_user_share_shockers_request import PauseUserShareShockersRequest from .pause_user_share_shockers_response import PauseUserShareShockersResponse @@ -77,7 +157,13 @@ from .public_share_shocker import PublicShareShocker from .received_control_stats import ReceivedControlStats from .remove_user_shares_response import RemoveUserSharesResponse +from .report_tokens_request import ReportTokensRequest from .role_type import RoleType +from .send_test_email_dto import SendTestEmailDto +from .set_token_paused_request import SetTokenPausedRequest +from .set_user_email_request_body import SetUserEmailRequestBody +from .set_user_name_request_body import SetUserNameRequestBody +from .set_user_password_request_body import SetUserPasswordRequestBody from .share_code_info import ShareCodeInfo from .share_info import ShareInfo from .share_invite_base_details import ShareInviteBaseDetails @@ -96,9 +182,13 @@ from .sign_up_v2 import SignUpV2 from .sort_direction import SortDirection from .stats_response import StatsResponse +from .token_created_response_v2 import TokenCreatedResponseV2 +from .token_paused_response import TokenPausedResponse from .token_response_v2 import TokenResponseV2 from .user_control_stat_totals import UserControlStatTotals from .user_control_stats import UserControlStats +from .user_name_blacklist_dto import UserNameBlacklistDto +from .user_patch_dto import UserPatchDto from .user_self_response import UserSelfResponse from .user_share_info import UserShareInfo from .username_availability import UsernameAvailability @@ -107,12 +197,67 @@ from .username_error_type import UsernameErrorType from .v2_user_shares import V2UserShares from .v2_user_shares_list_item import V2UserSharesListItem +from .webhook_dto import WebhookDto __all__ = ( + "AddEmailProviderBlacklistDto", + "AddUsernameBlacklistDto", + "AddWebhookDto", + "AdminOnlineDeviceResponse", + "AdminOnlineGatewayResponse", + "AdminUsersView", + "AdminUserView", + "AdminUserViewApiToken", + "AdminUserViewEmailChange", + "AdminUserViewHub", + "AdminUserViewNameChange", + "AdminUserViewPasswordReset", + "AdminUserViewShocker", + "AdminUserViewUserActivationRequest", + "AdminUserViewUserDeactivation", + "AdminUserViewUserRef", + "AuditAction", + "AuditLogEntryResponse", + "AuditMetadataAccountDeactivatedMetadata", + "AuditMetadataAccountDeactivatedMetadataT", + "AuditMetadataApiTokenCreatedMetadata", + "AuditMetadataApiTokenCreatedMetadataT", + "AuditMetadataApiTokenDeletedMetadata", + "AuditMetadataApiTokenDeletedMetadataT", + "AuditMetadataAutomationTokenCreatedMetadata", + "AuditMetadataAutomationTokenCreatedMetadataT", + "AuditMetadataAutomationTokenDeletedMetadata", + "AuditMetadataAutomationTokenDeletedMetadataT", + "AuditMetadataAutomationTokenRotatedMetadata", + "AuditMetadataAutomationTokenRotatedMetadataT", + "AuditMetadataAutomationTokenUpdatedMetadata", + "AuditMetadataAutomationTokenUpdatedMetadataT", + "AuditMetadataAutomationTokenUsedMetadata", + "AuditMetadataAutomationTokenUsedMetadataT", + "AuditMetadataEmailChangedMetadata", + "AuditMetadataEmailChangedMetadataT", + "AuditMetadataEmailChangeRequestedMetadata", + "AuditMetadataEmailChangeRequestedMetadataT", + "AuditMetadataLoginMetadata", + "AuditMetadataLoginMetadataT", + "AuditMetadataOAuthConnectedMetadata", + "AuditMetadataOAuthConnectedMetadataT", + "AuditMetadataOAuthDisconnectedMetadata", + "AuditMetadataOAuthDisconnectedMetadataT", + "AuditMetadataUsernameChangedMetadata", + "AuditMetadataUsernameChangedMetadataT", + "AutomationTokenDto", + "AutomationTokenType", "BackendInfoResponse", "BasicUserInfo", "BulkUserShareShockersUpdateRequest", + "ChangeEmailRequest", + "ChangePasswordRequest", "ChangeUsernameRequest", + "ConfigurationAddItemRequest", + "ConfigurationItemDto", + "ConfigurationUpdateItemRequest", + "ConfigurationValueType", "Control", "ControlLimitMode", "ControlLogSenderLight", @@ -122,19 +267,32 @@ "ControlStatsResponse", "ControlStatTotals", "ControlType", + "CreateAutomationTokenDto", + "CreatedAutomationTokenDto", "CreateShareRequest", + "CreateTokenRequestV2", "DailyControlStats", "DeviceResponse", "DeviceSelfResponse", "DeviceWithShockersResponse", "DeviceWithTokenResponse", "DurationLimitSettings", + "EditTokenRequestV2", + "EmailOutboxBulkRequest", + "EmailOutboxBulkResultDto", + "EmailOutboxMessageDto", + "EmailOutboxMessageDtoPayload", + "EmailOutboxStatsDto", + "EmailProviderBlacklistDto", + "EmailStatus", + "EmailType", "GivenControlStats", "HubCreateRequest", "HubEditRequest", "IntensityLimitSettings", "LcgNodeResponseV2", "LcgResponseV2", + "LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse", "LegacyDataResponseOfArrayOfDeviceResponse", "LegacyDataResponseOfArrayOfDeviceWithShockersResponse", "LegacyDataResponseOfArrayOfLogEntry", @@ -148,6 +306,7 @@ "LegacyDataResponseOfDeviceSelfResponse", "LegacyDataResponseOfDeviceWithTokenResponse", "LegacyDataResponseOfGuid", + "LegacyDataResponseOfIReadOnlyCollectionOfOtaItem", "LegacyDataResponseOfLegacyUserSelfResponse", "LegacyDataResponseOfPauseReason", "LegacyDataResponseOfPublicShareResponse", @@ -158,16 +317,26 @@ "LegacyUserSelfResponse", "LogEntry", "LogEntryWithHub", + "LoginSessionResponse", "LoginV2", "LoginV2OkResponse", + "MatchTypeEnum", "MinimalShocker", "NewShocker", + "OAuthConnectionResponse", "OpenShockProblem", + "OtaItem", + "OtaUpdateStatus", "OwnerShockerResponse", "OwnPublicShareResponse", + "PagedResultOfAuditLogEntryResponse", "PagedResultOfLogEntryWithHub", + "PaginatedOfAdminUsersView", + "PaginatedOfEmailOutboxMessageDto", + "PasswordHashingAlgorithm", "PasswordResetProcessData", "PasswordResetRequestV2", + "PatchAutomationTokenDto", "PauseRequest", "PauseUserShareShockersRequest", "PauseUserShareShockersResponse", @@ -181,7 +350,13 @@ "PublicShareShocker", "ReceivedControlStats", "RemoveUserSharesResponse", + "ReportTokensRequest", "RoleType", + "SendTestEmailDto", + "SetTokenPausedRequest", + "SetUserEmailRequestBody", + "SetUserNameRequestBody", + "SetUserPasswordRequestBody", "ShareCodeInfo", "SharedDevice", "SharedShocker", @@ -200,15 +375,20 @@ "SignUpV2", "SortDirection", "StatsResponse", + "TokenCreatedResponseV2", + "TokenPausedResponse", "TokenResponseV2", "UserControlStats", "UserControlStatTotals", "UsernameAvailability", + "UserNameBlacklistDto", "UsernameCheckResponse", "UsernameError", "UsernameErrorType", + "UserPatchDto", "UserSelfResponse", "UserShareInfo", "V2UserShares", "V2UserSharesListItem", + "WebhookDto", ) diff --git a/openshock/rest/models/add_email_provider_blacklist_dto.py b/openshock/rest/models/add_email_provider_blacklist_dto.py new file mode 100644 index 0000000..fb17ea7 --- /dev/null +++ b/openshock/rest/models/add_email_provider_blacklist_dto.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AddEmailProviderBlacklistDto") + + +@_attrs_define +class AddEmailProviderBlacklistDto: + """ + Attributes: + domains (list[str]): + """ + + domains: list[str] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + domains = self.domains + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "domains": domains, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + domains = cast(list[str], d.pop("domains")) + + add_email_provider_blacklist_dto = cls( + domains=domains, + ) + + add_email_provider_blacklist_dto.additional_properties = d + return add_email_provider_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/add_username_blacklist_dto.py b/openshock/rest/models/add_username_blacklist_dto.py new file mode 100644 index 0000000..e962cb9 --- /dev/null +++ b/openshock/rest/models/add_username_blacklist_dto.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.match_type_enum import MatchTypeEnum + +T = TypeVar("T", bound="AddUsernameBlacklistDto") + + +@_attrs_define +class AddUsernameBlacklistDto: + """ + Attributes: + value (str): + match_type (MatchTypeEnum): + """ + + value: str + match_type: MatchTypeEnum + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + value = self.value + + match_type = self.match_type.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "value": value, + "matchType": match_type, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + value = d.pop("value") + + match_type = MatchTypeEnum(d.pop("matchType")) + + add_username_blacklist_dto = cls( + value=value, + match_type=match_type, + ) + + add_username_blacklist_dto.additional_properties = d + return add_username_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/add_webhook_dto.py b/openshock/rest/models/add_webhook_dto.py new file mode 100644 index 0000000..de3ff55 --- /dev/null +++ b/openshock/rest/models/add_webhook_dto.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AddWebhookDto") + + +@_attrs_define +class AddWebhookDto: + """ + Attributes: + name (str): + url (str): + """ + + name: str + url: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + url = self.url + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "url": url, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + url = d.pop("url") + + add_webhook_dto = cls( + name=name, + url=url, + ) + + add_webhook_dto.additional_properties = d + return add_webhook_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_device_response.py b/openshock/rest/models/admin_online_device_response.py new file mode 100644 index 0000000..5a60cd5 --- /dev/null +++ b/openshock/rest/models/admin_online_device_response.py @@ -0,0 +1,216 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.basic_user_info import BasicUserInfo + + +T = TypeVar("T", bound="AdminOnlineDeviceResponse") + + +@_attrs_define +class AdminOnlineDeviceResponse: + """ + Attributes: + id (UUID): + name (str): + owner (BasicUserInfo): + firmware_version (str): + gateway (str): + connected_at (datetime.datetime): + user_agent (None | str): + booted_at (datetime.datetime): + latency_ms (int | None): + rssi (int | None): + country (None | str): + ip (None | str): An IPv4 or IPv6 address in its textual form. + asn (int | None): + asn_org (None | str): + """ + + id: UUID + name: str + owner: BasicUserInfo + firmware_version: str + gateway: str + connected_at: datetime.datetime + user_agent: None | str + booted_at: datetime.datetime + latency_ms: int | None + rssi: int | None + country: None | str + ip: None | str + asn: int | None + asn_org: None | str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + owner = self.owner.to_dict() + + firmware_version = self.firmware_version + + gateway = self.gateway + + connected_at = self.connected_at.isoformat() + + user_agent: None | str + user_agent = self.user_agent + + booted_at = self.booted_at.isoformat() + + latency_ms: int | None + latency_ms = self.latency_ms + + rssi: int | None + rssi = self.rssi + + country: None | str + country = self.country + + ip: None | str + ip = self.ip + + asn: int | None + asn = self.asn + + asn_org: None | str + asn_org = self.asn_org + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "owner": owner, + "firmwareVersion": firmware_version, + "gateway": gateway, + "connectedAt": connected_at, + "userAgent": user_agent, + "bootedAt": booted_at, + "latencyMs": latency_ms, + "rssi": rssi, + "country": country, + "ip": ip, + "asn": asn, + "asnOrg": asn_org, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + owner = BasicUserInfo.from_dict(d.pop("owner")) + + firmware_version = d.pop("firmwareVersion") + + gateway = d.pop("gateway") + + connected_at = datetime.datetime.fromisoformat(d.pop("connectedAt")) + + def _parse_user_agent(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + user_agent = _parse_user_agent(d.pop("userAgent")) + + booted_at = datetime.datetime.fromisoformat(d.pop("bootedAt")) + + def _parse_latency_ms(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + latency_ms = _parse_latency_ms(d.pop("latencyMs")) + + def _parse_rssi(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + rssi = _parse_rssi(d.pop("rssi")) + + def _parse_country(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + country = _parse_country(d.pop("country")) + + def _parse_ip(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + ip = _parse_ip(d.pop("ip")) + + def _parse_asn(data: object) -> int | None: + if data is None: + return data + return cast(int | None, data) + + asn = _parse_asn(d.pop("asn")) + + def _parse_asn_org(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + asn_org = _parse_asn_org(d.pop("asnOrg")) + + admin_online_device_response = cls( + id=id, + name=name, + owner=owner, + firmware_version=firmware_version, + gateway=gateway, + connected_at=connected_at, + user_agent=user_agent, + booted_at=booted_at, + latency_ms=latency_ms, + rssi=rssi, + country=country, + ip=ip, + asn=asn, + asn_org=asn_org, + ) + + admin_online_device_response.additional_properties = d + return admin_online_device_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_gateway_response.py b/openshock/rest/models/admin_online_gateway_response.py new file mode 100644 index 0000000..e4452ad --- /dev/null +++ b/openshock/rest/models/admin_online_gateway_response.py @@ -0,0 +1,146 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminOnlineGatewayResponse") + + +@_attrs_define +class AdminOnlineGatewayResponse: + """ + Attributes: + id (str): + host (str): + port (int): + path_prefix (str): + country (str): + latitude (float | None): + longitude (float | None): + load (int): Load the gateway advertises for hub assignment, in percent + environment (str): + connected_hubs (int): + """ + + id: str + host: str + port: int + path_prefix: str + country: str + latitude: float | None + longitude: float | None + load: int + environment: str + connected_hubs: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = self.id + + host = self.host + + port = self.port + + path_prefix = self.path_prefix + + country = self.country + + latitude: float | None + latitude = self.latitude + + longitude: float | None + longitude = self.longitude + + load = self.load + + environment = self.environment + + connected_hubs = self.connected_hubs + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "host": host, + "port": port, + "pathPrefix": path_prefix, + "country": country, + "latitude": latitude, + "longitude": longitude, + "load": load, + "environment": environment, + "connectedHubs": connected_hubs, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = d.pop("id") + + host = d.pop("host") + + port = d.pop("port") + + path_prefix = d.pop("pathPrefix") + + country = d.pop("country") + + def _parse_latitude(data: object) -> float | None: + if data is None: + return data + return cast(float | None, data) + + latitude = _parse_latitude(d.pop("latitude")) + + def _parse_longitude(data: object) -> float | None: + if data is None: + return data + return cast(float | None, data) + + longitude = _parse_longitude(d.pop("longitude")) + + load = d.pop("load") + + environment = d.pop("environment") + + connected_hubs = d.pop("connectedHubs") + + admin_online_gateway_response = cls( + id=id, + host=host, + port=port, + path_prefix=path_prefix, + country=country, + latitude=latitude, + longitude=longitude, + load=load, + environment=environment, + connected_hubs=connected_hubs, + ) + + admin_online_gateway_response.additional_properties = d + return admin_online_gateway_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view.py b/openshock/rest/models/admin_user_view.py new file mode 100644 index 0000000..f173c58 --- /dev/null +++ b/openshock/rest/models/admin_user_view.py @@ -0,0 +1,324 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.password_hashing_algorithm import PasswordHashingAlgorithm +from ..models.role_type import RoleType + +if TYPE_CHECKING: + from ..models.admin_user_view_api_token import AdminUserViewApiToken + from ..models.admin_user_view_email_change import AdminUserViewEmailChange + from ..models.admin_user_view_hub import AdminUserViewHub + from ..models.admin_user_view_name_change import AdminUserViewNameChange + from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset + from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest + from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation + + +T = TypeVar("T", bound="AdminUserView") + + +@_attrs_define +class AdminUserView: + """ + Attributes: + id (UUID): + name (str): + email (str): + password_hash_type (PasswordHashingAlgorithm): + roles (list[RoleType]): + created_at (datetime.datetime): + activated_at (datetime.datetime | None): + created_by_automation_token_id (None | UUID): + activation_request (AdminUserViewUserActivationRequest | None): + deactivation (AdminUserViewUserDeactivation | None): + hubs (list[AdminUserViewHub]): + api_tokens (list[AdminUserViewApiToken]): + users_name_changes (list[AdminUserViewNameChange]): + users_email_changes (list[AdminUserViewEmailChange]): + password_resets (list[AdminUserViewPasswordReset]): + shocker_control_logs_count (int): + """ + + id: UUID + name: str + email: str + password_hash_type: PasswordHashingAlgorithm + roles: list[RoleType] + created_at: datetime.datetime + activated_at: datetime.datetime | None + created_by_automation_token_id: None | UUID + activation_request: AdminUserViewUserActivationRequest | None + deactivation: AdminUserViewUserDeactivation | None + hubs: list[AdminUserViewHub] + api_tokens: list[AdminUserViewApiToken] + users_name_changes: list[AdminUserViewNameChange] + users_email_changes: list[AdminUserViewEmailChange] + password_resets: list[AdminUserViewPasswordReset] + shocker_control_logs_count: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 + from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 + + id = str(self.id) + + name = self.name + + email = self.email + + password_hash_type = self.password_hash_type.value + + roles = [] + for roles_item_data in self.roles: + roles_item = roles_item_data.value + roles.append(roles_item) + + created_at = self.created_at.isoformat() + + activated_at: None | str + if isinstance(self.activated_at, datetime.datetime): + activated_at = self.activated_at.isoformat() + else: + activated_at = self.activated_at + + created_by_automation_token_id: None | str + if isinstance(self.created_by_automation_token_id, UUID): + created_by_automation_token_id = str(self.created_by_automation_token_id) + else: + created_by_automation_token_id = self.created_by_automation_token_id + + activation_request: dict[str, Any] | None + if isinstance(self.activation_request, AdminUserViewUserActivationRequest): + activation_request = self.activation_request.to_dict() + else: + activation_request = self.activation_request + + deactivation: dict[str, Any] | None + if isinstance(self.deactivation, AdminUserViewUserDeactivation): + deactivation = self.deactivation.to_dict() + else: + deactivation = self.deactivation + + hubs = [] + for hubs_item_data in self.hubs: + hubs_item = hubs_item_data.to_dict() + hubs.append(hubs_item) + + api_tokens = [] + for api_tokens_item_data in self.api_tokens: + api_tokens_item = api_tokens_item_data.to_dict() + api_tokens.append(api_tokens_item) + + users_name_changes = [] + for users_name_changes_item_data in self.users_name_changes: + users_name_changes_item = users_name_changes_item_data.to_dict() + users_name_changes.append(users_name_changes_item) + + users_email_changes = [] + for users_email_changes_item_data in self.users_email_changes: + users_email_changes_item = users_email_changes_item_data.to_dict() + users_email_changes.append(users_email_changes_item) + + password_resets = [] + for password_resets_item_data in self.password_resets: + password_resets_item = password_resets_item_data.to_dict() + password_resets.append(password_resets_item) + + shocker_control_logs_count = self.shocker_control_logs_count + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "email": email, + "passwordHashType": password_hash_type, + "roles": roles, + "createdAt": created_at, + "activatedAt": activated_at, + "createdByAutomationTokenId": created_by_automation_token_id, + "activationRequest": activation_request, + "deactivation": deactivation, + "hubs": hubs, + "apiTokens": api_tokens, + "usersNameChanges": users_name_changes, + "usersEmailChanges": users_email_changes, + "passwordResets": password_resets, + "shockerControlLogsCount": shocker_control_logs_count, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_user_view_api_token import AdminUserViewApiToken # noqa: PLC0415 + from ..models.admin_user_view_email_change import AdminUserViewEmailChange # noqa: PLC0415 + from ..models.admin_user_view_hub import AdminUserViewHub # noqa: PLC0415 + from ..models.admin_user_view_name_change import AdminUserViewNameChange # noqa: PLC0415 + from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset # noqa: PLC0415 + from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 + from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + email = d.pop("email") + + password_hash_type = PasswordHashingAlgorithm(d.pop("passwordHashType")) + + roles = [] + _roles = d.pop("roles") + for roles_item_data in _roles: + roles_item = RoleType(roles_item_data) + + roles.append(roles_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_activated_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + activated_at_type_1 = datetime.datetime.fromisoformat(data) + + return activated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + activated_at = _parse_activated_at(d.pop("activatedAt")) + + def _parse_created_by_automation_token_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + created_by_automation_token_id_type_1 = UUID(data) + + return created_by_automation_token_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) + + def _parse_activation_request(data: object) -> AdminUserViewUserActivationRequest | None: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + activation_request_type_1 = AdminUserViewUserActivationRequest.from_dict(data) + + return activation_request_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(AdminUserViewUserActivationRequest | None, data) + + activation_request = _parse_activation_request(d.pop("activationRequest")) + + def _parse_deactivation(data: object) -> AdminUserViewUserDeactivation | None: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + deactivation_type_1 = AdminUserViewUserDeactivation.from_dict(data) + + return deactivation_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(AdminUserViewUserDeactivation | None, data) + + deactivation = _parse_deactivation(d.pop("deactivation")) + + hubs = [] + _hubs = d.pop("hubs") + for hubs_item_data in _hubs: + hubs_item = AdminUserViewHub.from_dict(hubs_item_data) + + hubs.append(hubs_item) + + api_tokens = [] + _api_tokens = d.pop("apiTokens") + for api_tokens_item_data in _api_tokens: + api_tokens_item = AdminUserViewApiToken.from_dict(api_tokens_item_data) + + api_tokens.append(api_tokens_item) + + users_name_changes = [] + _users_name_changes = d.pop("usersNameChanges") + for users_name_changes_item_data in _users_name_changes: + users_name_changes_item = AdminUserViewNameChange.from_dict(users_name_changes_item_data) + + users_name_changes.append(users_name_changes_item) + + users_email_changes = [] + _users_email_changes = d.pop("usersEmailChanges") + for users_email_changes_item_data in _users_email_changes: + users_email_changes_item = AdminUserViewEmailChange.from_dict(users_email_changes_item_data) + + users_email_changes.append(users_email_changes_item) + + password_resets = [] + _password_resets = d.pop("passwordResets") + for password_resets_item_data in _password_resets: + password_resets_item = AdminUserViewPasswordReset.from_dict(password_resets_item_data) + + password_resets.append(password_resets_item) + + shocker_control_logs_count = d.pop("shockerControlLogsCount") + + admin_user_view = cls( + id=id, + name=name, + email=email, + password_hash_type=password_hash_type, + roles=roles, + created_at=created_at, + activated_at=activated_at, + created_by_automation_token_id=created_by_automation_token_id, + activation_request=activation_request, + deactivation=deactivation, + hubs=hubs, + api_tokens=api_tokens, + users_name_changes=users_name_changes, + users_email_changes=users_email_changes, + password_resets=password_resets, + shocker_control_logs_count=shocker_control_logs_count, + ) + + admin_user_view.additional_properties = d + return admin_user_view + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_api_token.py b/openshock/rest/models/admin_user_view_api_token.py new file mode 100644 index 0000000..ca254d6 --- /dev/null +++ b/openshock/rest/models/admin_user_view_api_token.py @@ -0,0 +1,156 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType + +T = TypeVar("T", bound="AdminUserViewApiToken") + + +@_attrs_define +class AdminUserViewApiToken: + """ + Attributes: + id (UUID): + name (str): + permissions (list[PermissionType]): + valid_until (datetime.datetime | None): + last_used (datetime.datetime | None): + created_at (datetime.datetime): + created_by_ip (str): An IPv4 or IPv6 address in its textual form. + """ + + id: UUID + name: str + permissions: list[PermissionType] + valid_until: datetime.datetime | None + last_used: datetime.datetime | None + created_at: datetime.datetime + created_by_ip: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + valid_until: None | str + if isinstance(self.valid_until, datetime.datetime): + valid_until = self.valid_until.isoformat() + else: + valid_until = self.valid_until + + last_used: None | str + if isinstance(self.last_used, datetime.datetime): + last_used = self.last_used.isoformat() + else: + last_used = self.last_used + + created_at = self.created_at.isoformat() + + created_by_ip = self.created_by_ip + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "permissions": permissions, + "validUntil": valid_until, + "lastUsed": last_used, + "createdAt": created_at, + "createdByIp": created_by_ip, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + def _parse_valid_until(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + valid_until_type_1 = datetime.datetime.fromisoformat(data) + + return valid_until_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + valid_until = _parse_valid_until(d.pop("validUntil")) + + def _parse_last_used(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + last_used = _parse_last_used(d.pop("lastUsed")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + created_by_ip = d.pop("createdByIp") + + admin_user_view_api_token = cls( + id=id, + name=name, + permissions=permissions, + valid_until=valid_until, + last_used=last_used, + created_at=created_at, + created_by_ip=created_by_ip, + ) + + admin_user_view_api_token.additional_properties = d + return admin_user_view_api_token + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_email_change.py b/openshock/rest/models/admin_user_view_email_change.py new file mode 100644 index 0000000..a43a754 --- /dev/null +++ b/openshock/rest/models/admin_user_view_email_change.py @@ -0,0 +1,105 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewEmailChange") + + +@_attrs_define +class AdminUserViewEmailChange: + """ + Attributes: + id (UUID): + email (str): + created_at (datetime.datetime): + used_at (datetime.datetime | None): + """ + + id: UUID + email: str + created_at: datetime.datetime + used_at: datetime.datetime | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + email = self.email + + created_at = self.created_at.isoformat() + + used_at: None | str + if isinstance(self.used_at, datetime.datetime): + used_at = self.used_at.isoformat() + else: + used_at = self.used_at + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "email": email, + "createdAt": created_at, + "usedAt": used_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + email = d.pop("email") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_used_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + used_at_type_1 = datetime.datetime.fromisoformat(data) + + return used_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + used_at = _parse_used_at(d.pop("usedAt")) + + admin_user_view_email_change = cls( + id=id, + email=email, + created_at=created_at, + used_at=used_at, + ) + + admin_user_view_email_change.additional_properties = d + return admin_user_view_email_change + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_hub.py b/openshock/rest/models/admin_user_view_hub.py new file mode 100644 index 0000000..e7620b7 --- /dev/null +++ b/openshock/rest/models/admin_user_view_hub.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_user_view_shocker import AdminUserViewShocker + + +T = TypeVar("T", bound="AdminUserViewHub") + + +@_attrs_define +class AdminUserViewHub: + """ + Attributes: + id (UUID): + name (str): + created_at (datetime.datetime): + shockers (list[AdminUserViewShocker]): + """ + + id: UUID + name: str + created_at: datetime.datetime + shockers: list[AdminUserViewShocker] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_at = self.created_at.isoformat() + + shockers = [] + for shockers_item_data in self.shockers: + shockers_item = shockers_item_data.to_dict() + shockers.append(shockers_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdAt": created_at, + "shockers": shockers, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_user_view_shocker import AdminUserViewShocker # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + shockers = [] + _shockers = d.pop("shockers") + for shockers_item_data in _shockers: + shockers_item = AdminUserViewShocker.from_dict(shockers_item_data) + + shockers.append(shockers_item) + + admin_user_view_hub = cls( + id=id, + name=name, + created_at=created_at, + shockers=shockers, + ) + + admin_user_view_hub.additional_properties = d + return admin_user_view_hub + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_name_change.py b/openshock/rest/models/admin_user_view_name_change.py new file mode 100644 index 0000000..00eb2fb --- /dev/null +++ b/openshock/rest/models/admin_user_view_name_change.py @@ -0,0 +1,79 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewNameChange") + + +@_attrs_define +class AdminUserViewNameChange: + """ + Attributes: + id (int): + old_name (str): + created_at (datetime.datetime): + """ + + id: int + old_name: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = self.id + + old_name = self.old_name + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "oldName": old_name, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = d.pop("id") + + old_name = d.pop("oldName") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + admin_user_view_name_change = cls( + id=id, + old_name=old_name, + created_at=created_at, + ) + + admin_user_view_name_change.additional_properties = d + return admin_user_view_name_change + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_password_reset.py b/openshock/rest/models/admin_user_view_password_reset.py new file mode 100644 index 0000000..4f0cc60 --- /dev/null +++ b/openshock/rest/models/admin_user_view_password_reset.py @@ -0,0 +1,97 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewPasswordReset") + + +@_attrs_define +class AdminUserViewPasswordReset: + """ + Attributes: + id (UUID): + created_at (datetime.datetime): + used_at (datetime.datetime | None): + """ + + id: UUID + created_at: datetime.datetime + used_at: datetime.datetime | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + created_at = self.created_at.isoformat() + + used_at: None | str + if isinstance(self.used_at, datetime.datetime): + used_at = self.used_at.isoformat() + else: + used_at = self.used_at + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "createdAt": created_at, + "usedAt": used_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_used_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + used_at_type_1 = datetime.datetime.fromisoformat(data) + + return used_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + used_at = _parse_used_at(d.pop("usedAt")) + + admin_user_view_password_reset = cls( + id=id, + created_at=created_at, + used_at=used_at, + ) + + admin_user_view_password_reset.additional_properties = d + return admin_user_view_password_reset + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_shocker.py b/openshock/rest/models/admin_user_view_shocker.py new file mode 100644 index 0000000..996decd --- /dev/null +++ b/openshock/rest/models/admin_user_view_shocker.py @@ -0,0 +1,80 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewShocker") + + +@_attrs_define +class AdminUserViewShocker: + """ + Attributes: + id (UUID): + name (str): + created_at (datetime.datetime): + """ + + id: UUID + name: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + admin_user_view_shocker = cls( + id=id, + name=name, + created_at=created_at, + ) + + admin_user_view_shocker.additional_properties = d + return admin_user_view_shocker + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_activation_request.py b/openshock/rest/models/admin_user_view_user_activation_request.py new file mode 100644 index 0000000..89a85c8 --- /dev/null +++ b/openshock/rest/models/admin_user_view_user_activation_request.py @@ -0,0 +1,71 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewUserActivationRequest") + + +@_attrs_define +class AdminUserViewUserActivationRequest: + """ + Attributes: + email_send_attempts (int): + created_at (datetime.datetime): + """ + + email_send_attempts: int + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + email_send_attempts = self.email_send_attempts + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "emailSendAttempts": email_send_attempts, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + email_send_attempts = d.pop("emailSendAttempts") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + admin_user_view_user_activation_request = cls( + email_send_attempts=email_send_attempts, + created_at=created_at, + ) + + admin_user_view_user_activation_request.additional_properties = d + return admin_user_view_user_activation_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_deactivation.py b/openshock/rest/models/admin_user_view_user_deactivation.py new file mode 100644 index 0000000..a73d1b5 --- /dev/null +++ b/openshock/rest/models/admin_user_view_user_deactivation.py @@ -0,0 +1,102 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_user_view_user_ref import AdminUserViewUserRef + + +T = TypeVar("T", bound="AdminUserViewUserDeactivation") + + +@_attrs_define +class AdminUserViewUserDeactivation: + """ + Attributes: + deactivated_by (AdminUserViewUserRef): + scheduled_deletion_time (datetime.datetime | None): + deactivated_at (datetime.datetime): + """ + + deactivated_by: AdminUserViewUserRef + scheduled_deletion_time: datetime.datetime | None + deactivated_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + deactivated_by = self.deactivated_by.to_dict() + + scheduled_deletion_time: None | str + if isinstance(self.scheduled_deletion_time, datetime.datetime): + scheduled_deletion_time = self.scheduled_deletion_time.isoformat() + else: + scheduled_deletion_time = self.scheduled_deletion_time + + deactivated_at = self.deactivated_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "deactivatedBy": deactivated_by, + "scheduledDeletionTime": scheduled_deletion_time, + "deactivatedAt": deactivated_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_user_view_user_ref import AdminUserViewUserRef # noqa: PLC0415 + + d = dict(src_dict) + deactivated_by = AdminUserViewUserRef.from_dict(d.pop("deactivatedBy")) + + def _parse_scheduled_deletion_time(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + scheduled_deletion_time_type_1 = datetime.datetime.fromisoformat(data) + + return scheduled_deletion_time_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + scheduled_deletion_time = _parse_scheduled_deletion_time(d.pop("scheduledDeletionTime")) + + deactivated_at = datetime.datetime.fromisoformat(d.pop("deactivatedAt")) + + admin_user_view_user_deactivation = cls( + deactivated_by=deactivated_by, + scheduled_deletion_time=scheduled_deletion_time, + deactivated_at=deactivated_at, + ) + + admin_user_view_user_deactivation.additional_properties = d + return admin_user_view_user_deactivation + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_ref.py b/openshock/rest/models/admin_user_view_user_ref.py new file mode 100644 index 0000000..0faa90f --- /dev/null +++ b/openshock/rest/models/admin_user_view_user_ref.py @@ -0,0 +1,71 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="AdminUserViewUserRef") + + +@_attrs_define +class AdminUserViewUserRef: + """ + Attributes: + id (UUID): + name (str): + """ + + id: UUID + name: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + admin_user_view_user_ref = cls( + id=id, + name=name, + ) + + admin_user_view_user_ref.additional_properties = d + return admin_user_view_user_ref + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/admin_users_view.py b/openshock/rest/models/admin_users_view.py new file mode 100644 index 0000000..2dc3109 --- /dev/null +++ b/openshock/rest/models/admin_users_view.py @@ -0,0 +1,304 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.password_hashing_algorithm import PasswordHashingAlgorithm +from ..models.role_type import RoleType + +T = TypeVar("T", bound="AdminUsersView") + + +@_attrs_define +class AdminUsersView: + """ + Attributes: + id (UUID): + name (str): + email (str): + password_hash_type (None | PasswordHashingAlgorithm): + roles (list[RoleType]): + created_at (datetime.datetime): + activated_at (datetime.datetime | None): + created_by_automation_token_id (None | UUID): + deactivated_at (datetime.datetime | None): + deactivated_by_user_id (None | UUID): + api_token_count (int): + password_reset_count (int): + shocker_user_share_count (int): + shocker_public_share_count (int): + email_change_request_count (int): + name_change_request_count (int): + device_count (int): + shocker_count (int): + shocker_control_log_count (int): + """ + + id: UUID + name: str + email: str + password_hash_type: None | PasswordHashingAlgorithm + roles: list[RoleType] + created_at: datetime.datetime + activated_at: datetime.datetime | None + created_by_automation_token_id: None | UUID + deactivated_at: datetime.datetime | None + deactivated_by_user_id: None | UUID + api_token_count: int + password_reset_count: int + shocker_user_share_count: int + shocker_public_share_count: int + email_change_request_count: int + name_change_request_count: int + device_count: int + shocker_count: int + shocker_control_log_count: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + email = self.email + + password_hash_type: None | str + if isinstance(self.password_hash_type, PasswordHashingAlgorithm): + password_hash_type = self.password_hash_type.value + else: + password_hash_type = self.password_hash_type + + roles = [] + for roles_item_data in self.roles: + roles_item = roles_item_data.value + roles.append(roles_item) + + created_at = self.created_at.isoformat() + + activated_at: None | str + if isinstance(self.activated_at, datetime.datetime): + activated_at = self.activated_at.isoformat() + else: + activated_at = self.activated_at + + created_by_automation_token_id: None | str + if isinstance(self.created_by_automation_token_id, UUID): + created_by_automation_token_id = str(self.created_by_automation_token_id) + else: + created_by_automation_token_id = self.created_by_automation_token_id + + deactivated_at: None | str + if isinstance(self.deactivated_at, datetime.datetime): + deactivated_at = self.deactivated_at.isoformat() + else: + deactivated_at = self.deactivated_at + + deactivated_by_user_id: None | str + if isinstance(self.deactivated_by_user_id, UUID): + deactivated_by_user_id = str(self.deactivated_by_user_id) + else: + deactivated_by_user_id = self.deactivated_by_user_id + + api_token_count = self.api_token_count + + password_reset_count = self.password_reset_count + + shocker_user_share_count = self.shocker_user_share_count + + shocker_public_share_count = self.shocker_public_share_count + + email_change_request_count = self.email_change_request_count + + name_change_request_count = self.name_change_request_count + + device_count = self.device_count + + shocker_count = self.shocker_count + + shocker_control_log_count = self.shocker_control_log_count + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "email": email, + "passwordHashType": password_hash_type, + "roles": roles, + "createdAt": created_at, + "activatedAt": activated_at, + "createdByAutomationTokenId": created_by_automation_token_id, + "deactivatedAt": deactivated_at, + "deactivatedByUserId": deactivated_by_user_id, + "apiTokenCount": api_token_count, + "passwordResetCount": password_reset_count, + "shockerUserShareCount": shocker_user_share_count, + "shockerPublicShareCount": shocker_public_share_count, + "emailChangeRequestCount": email_change_request_count, + "nameChangeRequestCount": name_change_request_count, + "deviceCount": device_count, + "shockerCount": shocker_count, + "shockerControlLogCount": shocker_control_log_count, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + email = d.pop("email") + + def _parse_password_hash_type(data: object) -> None | PasswordHashingAlgorithm: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + password_hash_type_type_1 = PasswordHashingAlgorithm(data) + + return password_hash_type_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | PasswordHashingAlgorithm, data) + + password_hash_type = _parse_password_hash_type(d.pop("passwordHashType")) + + roles = [] + _roles = d.pop("roles") + for roles_item_data in _roles: + roles_item = RoleType(roles_item_data) + + roles.append(roles_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_activated_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + activated_at_type_1 = datetime.datetime.fromisoformat(data) + + return activated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + activated_at = _parse_activated_at(d.pop("activatedAt")) + + def _parse_created_by_automation_token_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + created_by_automation_token_id_type_1 = UUID(data) + + return created_by_automation_token_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) + + def _parse_deactivated_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + deactivated_at_type_1 = datetime.datetime.fromisoformat(data) + + return deactivated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + deactivated_at = _parse_deactivated_at(d.pop("deactivatedAt")) + + def _parse_deactivated_by_user_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + deactivated_by_user_id_type_1 = UUID(data) + + return deactivated_by_user_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + deactivated_by_user_id = _parse_deactivated_by_user_id(d.pop("deactivatedByUserId")) + + api_token_count = d.pop("apiTokenCount") + + password_reset_count = d.pop("passwordResetCount") + + shocker_user_share_count = d.pop("shockerUserShareCount") + + shocker_public_share_count = d.pop("shockerPublicShareCount") + + email_change_request_count = d.pop("emailChangeRequestCount") + + name_change_request_count = d.pop("nameChangeRequestCount") + + device_count = d.pop("deviceCount") + + shocker_count = d.pop("shockerCount") + + shocker_control_log_count = d.pop("shockerControlLogCount") + + admin_users_view = cls( + id=id, + name=name, + email=email, + password_hash_type=password_hash_type, + roles=roles, + created_at=created_at, + activated_at=activated_at, + created_by_automation_token_id=created_by_automation_token_id, + deactivated_at=deactivated_at, + deactivated_by_user_id=deactivated_by_user_id, + api_token_count=api_token_count, + password_reset_count=password_reset_count, + shocker_user_share_count=shocker_user_share_count, + shocker_public_share_count=shocker_public_share_count, + email_change_request_count=email_change_request_count, + name_change_request_count=name_change_request_count, + device_count=device_count, + shocker_count=shocker_count, + shocker_control_log_count=shocker_control_log_count, + ) + + admin_users_view.additional_properties = d + return admin_users_view + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_action.py b/openshock/rest/models/audit_action.py new file mode 100644 index 0000000..e7bcff5 --- /dev/null +++ b/openshock/rest/models/audit_action.py @@ -0,0 +1,26 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditAction(StrEnum): + ACCOUNTDEACTIVATED = "AccountDeactivated" + ACCOUNTDELETED = "AccountDeleted" + ACCOUNTREACTIVATED = "AccountReactivated" + APITOKENCREATED = "ApiTokenCreated" + APITOKENDELETED = "ApiTokenDeleted" + AUTOMATIONTOKENCREATED = "AutomationTokenCreated" + AUTOMATIONTOKENDELETED = "AutomationTokenDeleted" + AUTOMATIONTOKENROTATED = "AutomationTokenRotated" + AUTOMATIONTOKENUPDATED = "AutomationTokenUpdated" + AUTOMATIONTOKENUSED = "AutomationTokenUsed" + EMAILCHANGED = "EmailChanged" + EMAILCHANGEREQUESTED = "EmailChangeRequested" + LOGIN = "Login" + LOGOUT = "Logout" + OAUTHCONNECTED = "OAuthConnected" + OAUTHDISCONNECTED = "OAuthDisconnected" + PASSWORDCHANGED = "PasswordChanged" + USERNAMECHANGED = "UsernameChanged" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_log_entry_response.py b/openshock/rest/models/audit_log_entry_response.py new file mode 100644 index 0000000..382f07a --- /dev/null +++ b/openshock/rest/models/audit_log_entry_response.py @@ -0,0 +1,432 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_action import AuditAction + +if TYPE_CHECKING: + from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata + from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata + from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata + from ..models.audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata + from ..models.audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata + from ..models.audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata + from ..models.audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata + from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata + from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata + from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata + from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata + from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata + from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata + from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata + + +T = TypeVar("T", bound="AuditLogEntryResponse") + + +@_attrs_define +class AuditLogEntryResponse: + """ + Attributes: + id (UUID): + user_id (UUID): + actor_id (None | UUID): + action (AuditAction): + reason (None | str): + ip_address (None | str): An IPv4 or IPv6 address in its textual form. + user_agent (None | str): + metadata (AuditMetadataAccountDeactivatedMetadata | AuditMetadataApiTokenCreatedMetadata | + AuditMetadataApiTokenDeletedMetadata | AuditMetadataAutomationTokenCreatedMetadata | + AuditMetadataAutomationTokenDeletedMetadata | AuditMetadataAutomationTokenRotatedMetadata | + AuditMetadataAutomationTokenUpdatedMetadata | AuditMetadataAutomationTokenUsedMetadata | + AuditMetadataEmailChangedMetadata | AuditMetadataEmailChangeRequestedMetadata | AuditMetadataLoginMetadata | + AuditMetadataOAuthConnectedMetadata | AuditMetadataOAuthDisconnectedMetadata | + AuditMetadataUsernameChangedMetadata | None): + created_at (datetime.datetime): + """ + + id: UUID + user_id: UUID + actor_id: None | UUID + action: AuditAction + reason: None | str + ip_address: None | str + user_agent: None | str + metadata: ( + AuditMetadataAccountDeactivatedMetadata + | AuditMetadataApiTokenCreatedMetadata + | AuditMetadataApiTokenDeletedMetadata + | AuditMetadataAutomationTokenCreatedMetadata + | AuditMetadataAutomationTokenDeletedMetadata + | AuditMetadataAutomationTokenRotatedMetadata + | AuditMetadataAutomationTokenUpdatedMetadata + | AuditMetadataAutomationTokenUsedMetadata + | AuditMetadataEmailChangedMetadata + | AuditMetadataEmailChangeRequestedMetadata + | AuditMetadataLoginMetadata + | AuditMetadataOAuthConnectedMetadata + | AuditMetadataOAuthDisconnectedMetadata + | AuditMetadataUsernameChangedMetadata + | None + ) + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 + from ..models.audit_metadata_automation_token_created_metadata import ( + AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_deleted_metadata import ( + AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_rotated_metadata import ( + AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_updated_metadata import ( + AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 + from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 + + id = str(self.id) + + user_id = str(self.user_id) + + actor_id: None | str + if isinstance(self.actor_id, UUID): + actor_id = str(self.actor_id) + else: + actor_id = self.actor_id + + action = self.action.value + + reason: None | str + reason = self.reason + + ip_address: None | str + ip_address = self.ip_address + + user_agent: None | str + user_agent = self.user_agent + + metadata: dict[str, Any] | None + if isinstance(self.metadata, AuditMetadataLoginMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataUsernameChangedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataEmailChangeRequestedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataEmailChangedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataApiTokenCreatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataApiTokenDeletedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataOAuthConnectedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataOAuthDisconnectedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAccountDeactivatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenCreatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenUpdatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenRotatedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenDeletedMetadata): + metadata = self.metadata.to_dict() + elif isinstance(self.metadata, AuditMetadataAutomationTokenUsedMetadata): + metadata = self.metadata.to_dict() + else: + metadata = self.metadata + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "userId": user_id, + "actorId": actor_id, + "action": action, + "reason": reason, + "ipAddress": ip_address, + "userAgent": user_agent, + "metadata": metadata, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 + from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 + from ..models.audit_metadata_automation_token_created_metadata import ( + AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_deleted_metadata import ( + AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_rotated_metadata import ( + AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_updated_metadata import ( + AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 + ) + from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 + from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 + from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 + from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + user_id = UUID(d.pop("userId")) + + def _parse_actor_id(data: object) -> None | UUID: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + actor_id_type_1 = UUID(data) + + return actor_id_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | UUID, data) + + actor_id = _parse_actor_id(d.pop("actorId")) + + action = AuditAction(d.pop("action")) + + def _parse_reason(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + reason = _parse_reason(d.pop("reason")) + + def _parse_ip_address(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + ip_address = _parse_ip_address(d.pop("ipAddress")) + + def _parse_user_agent(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + user_agent = _parse_user_agent(d.pop("userAgent")) + + def _parse_metadata( + data: object, + ) -> ( + AuditMetadataAccountDeactivatedMetadata + | AuditMetadataApiTokenCreatedMetadata + | AuditMetadataApiTokenDeletedMetadata + | AuditMetadataAutomationTokenCreatedMetadata + | AuditMetadataAutomationTokenDeletedMetadata + | AuditMetadataAutomationTokenRotatedMetadata + | AuditMetadataAutomationTokenUpdatedMetadata + | AuditMetadataAutomationTokenUsedMetadata + | AuditMetadataEmailChangedMetadata + | AuditMetadataEmailChangeRequestedMetadata + | AuditMetadataLoginMetadata + | AuditMetadataOAuthConnectedMetadata + | AuditMetadataOAuthDisconnectedMetadata + | AuditMetadataUsernameChangedMetadata + | None + ): + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_0 = AuditMetadataLoginMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_0 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_1 = AuditMetadataUsernameChangedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_2 = AuditMetadataEmailChangeRequestedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_2 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_3 = AuditMetadataEmailChangedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_3 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_4 = AuditMetadataApiTokenCreatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_4 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_5 = AuditMetadataApiTokenDeletedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_5 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_6 = AuditMetadataOAuthConnectedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_6 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_7 = AuditMetadataOAuthDisconnectedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_7 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_8 = AuditMetadataAccountDeactivatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_8 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_9 = AuditMetadataAutomationTokenCreatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_9 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_10 = AuditMetadataAutomationTokenUpdatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_10 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_11 = AuditMetadataAutomationTokenRotatedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_11 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_12 = AuditMetadataAutomationTokenDeletedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_12 + except (TypeError, ValueError, AttributeError, KeyError): + pass + try: + if not isinstance(data, dict): + raise TypeError() + componentsschemas_audit_metadata_type_13 = AuditMetadataAutomationTokenUsedMetadata.from_dict(data) + + return componentsschemas_audit_metadata_type_13 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast( + AuditMetadataAccountDeactivatedMetadata + | AuditMetadataApiTokenCreatedMetadata + | AuditMetadataApiTokenDeletedMetadata + | AuditMetadataAutomationTokenCreatedMetadata + | AuditMetadataAutomationTokenDeletedMetadata + | AuditMetadataAutomationTokenRotatedMetadata + | AuditMetadataAutomationTokenUpdatedMetadata + | AuditMetadataAutomationTokenUsedMetadata + | AuditMetadataEmailChangedMetadata + | AuditMetadataEmailChangeRequestedMetadata + | AuditMetadataLoginMetadata + | AuditMetadataOAuthConnectedMetadata + | AuditMetadataOAuthDisconnectedMetadata + | AuditMetadataUsernameChangedMetadata + | None, + data, + ) + + metadata = _parse_metadata(d.pop("metadata")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + audit_log_entry_response = cls( + id=id, + user_id=user_id, + actor_id=actor_id, + action=action, + reason=reason, + ip_address=ip_address, + user_agent=user_agent, + metadata=metadata, + created_at=created_at, + ) + + audit_log_entry_response.additional_properties = d + return audit_log_entry_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata.py new file mode 100644 index 0000000..0c04186 --- /dev/null +++ b/openshock/rest/models/audit_metadata_account_deactivated_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAccountDeactivatedMetadata") + + +@_attrs_define +class AuditMetadataAccountDeactivatedMetadata: + """ + Attributes: + delete_later (bool): + t (AuditMetadataAccountDeactivatedMetadataT | Unset): + """ + + delete_later: bool + t: AuditMetadataAccountDeactivatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + delete_later = self.delete_later + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "deleteLater": delete_later, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + delete_later = d.pop("deleteLater") + + _t = d.pop("t", UNSET) + t: AuditMetadataAccountDeactivatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAccountDeactivatedMetadataT(_t) + + audit_metadata_account_deactivated_metadata = cls( + delete_later=delete_later, + t=t, + ) + + audit_metadata_account_deactivated_metadata.additional_properties = d + return audit_metadata_account_deactivated_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py new file mode 100644 index 0000000..f5a287d --- /dev/null +++ b/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAccountDeactivatedMetadataT(StrEnum): + ACCOUNTDEACTIVATED = "accountDeactivated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata.py b/openshock/rest/models/audit_metadata_api_token_created_metadata.py new file mode 100644 index 0000000..f813d7f --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_created_metadata.py @@ -0,0 +1,98 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataApiTokenCreatedMetadata") + + +@_attrs_define +class AuditMetadataApiTokenCreatedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + permissions (list[str]): + t (AuditMetadataApiTokenCreatedMetadataT | Unset): + """ + + token_id: UUID + name: str + permissions: list[str] + t: AuditMetadataApiTokenCreatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + permissions = self.permissions + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "permissions": permissions, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + permissions = cast(list[str], d.pop("permissions")) + + _t = d.pop("t", UNSET) + t: AuditMetadataApiTokenCreatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataApiTokenCreatedMetadataT(_t) + + audit_metadata_api_token_created_metadata = cls( + token_id=token_id, + name=name, + permissions=permissions, + t=t, + ) + + audit_metadata_api_token_created_metadata.additional_properties = d + return audit_metadata_api_token_created_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py new file mode 100644 index 0000000..59024ee --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataApiTokenCreatedMetadataT(StrEnum): + APITOKENCREATED = "apiTokenCreated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py new file mode 100644 index 0000000..1087190 --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py @@ -0,0 +1,90 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataApiTokenDeletedMetadata") + + +@_attrs_define +class AuditMetadataApiTokenDeletedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + t (AuditMetadataApiTokenDeletedMetadataT | Unset): + """ + + token_id: UUID + name: str + t: AuditMetadataApiTokenDeletedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + _t = d.pop("t", UNSET) + t: AuditMetadataApiTokenDeletedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataApiTokenDeletedMetadataT(_t) + + audit_metadata_api_token_deleted_metadata = cls( + token_id=token_id, + name=name, + t=t, + ) + + audit_metadata_api_token_deleted_metadata.additional_properties = d + return audit_metadata_api_token_deleted_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py new file mode 100644 index 0000000..de49448 --- /dev/null +++ b/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataApiTokenDeletedMetadataT(StrEnum): + APITOKENDELETED = "apiTokenDeleted" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata.py new file mode 100644 index 0000000..78c3add --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_created_metadata.py @@ -0,0 +1,120 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenCreatedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenCreatedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + types (list[str]): + auto_cleanup_users (bool): + auto_cleanup_after (None | str): + t (AuditMetadataAutomationTokenCreatedMetadataT | Unset): + """ + + token_id: UUID + name: str + types: list[str] + auto_cleanup_users: bool + auto_cleanup_after: None | str + t: AuditMetadataAutomationTokenCreatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + types = self.types + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str + auto_cleanup_after = self.auto_cleanup_after + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "types": types, + "autoCleanupUsers": auto_cleanup_users, + "autoCleanupAfter": auto_cleanup_after, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + types = cast(list[str], d.pop("types")) + + auto_cleanup_users = d.pop("autoCleanupUsers") + + def _parse_auto_cleanup_after(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenCreatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenCreatedMetadataT(_t) + + audit_metadata_automation_token_created_metadata = cls( + token_id=token_id, + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + t=t, + ) + + audit_metadata_automation_token_created_metadata.additional_properties = d + return audit_metadata_automation_token_created_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py new file mode 100644 index 0000000..71728a5 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenCreatedMetadataT(StrEnum): + AUTOMATIONTOKENCREATED = "automationTokenCreated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py new file mode 100644 index 0000000..98e47b2 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py @@ -0,0 +1,99 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenDeletedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenDeletedMetadata: + """The token was deleted together with the int AutomationTokenDeletedMetadata.DeletedAccountCount accounts it created. + + Attributes: + token_id (UUID): + name (str): + deleted_account_count (int): + t (AuditMetadataAutomationTokenDeletedMetadataT | Unset): + """ + + token_id: UUID + name: str + deleted_account_count: int + t: AuditMetadataAutomationTokenDeletedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + deleted_account_count = self.deleted_account_count + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "deletedAccountCount": deleted_account_count, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + deleted_account_count = d.pop("deletedAccountCount") + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenDeletedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenDeletedMetadataT(_t) + + audit_metadata_automation_token_deleted_metadata = cls( + token_id=token_id, + name=name, + deleted_account_count=deleted_account_count, + t=t, + ) + + audit_metadata_automation_token_deleted_metadata.additional_properties = d + return audit_metadata_automation_token_deleted_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py new file mode 100644 index 0000000..6e81913 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenDeletedMetadataT(StrEnum): + AUTOMATIONTOKENDELETED = "automationTokenDeleted" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py new file mode 100644 index 0000000..86b917e --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py @@ -0,0 +1,90 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenRotatedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenRotatedMetadata: + """ + Attributes: + token_id (UUID): + name (str): + t (AuditMetadataAutomationTokenRotatedMetadataT | Unset): + """ + + token_id: UUID + name: str + t: AuditMetadataAutomationTokenRotatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenRotatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenRotatedMetadataT(_t) + + audit_metadata_automation_token_rotated_metadata = cls( + token_id=token_id, + name=name, + t=t, + ) + + audit_metadata_automation_token_rotated_metadata.additional_properties = d + return audit_metadata_automation_token_rotated_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py new file mode 100644 index 0000000..b9df839 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenRotatedMetadataT(StrEnum): + AUTOMATIONTOKENROTATED = "automationTokenRotated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py new file mode 100644 index 0000000..083f9d7 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py @@ -0,0 +1,121 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenUpdatedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenUpdatedMetadata: + """The token's settings after the update. + + Attributes: + token_id (UUID): + name (str): + types (list[str]): + auto_cleanup_users (bool): + auto_cleanup_after (None | str): + t (AuditMetadataAutomationTokenUpdatedMetadataT | Unset): + """ + + token_id: UUID + name: str + types: list[str] + auto_cleanup_users: bool + auto_cleanup_after: None | str + t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + types = self.types + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str + auto_cleanup_after = self.auto_cleanup_after + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "types": types, + "autoCleanupUsers": auto_cleanup_users, + "autoCleanupAfter": auto_cleanup_after, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + types = cast(list[str], d.pop("types")) + + auto_cleanup_users = d.pop("autoCleanupUsers") + + def _parse_auto_cleanup_after(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenUpdatedMetadataT(_t) + + audit_metadata_automation_token_updated_metadata = cls( + token_id=token_id, + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + t=t, + ) + + audit_metadata_automation_token_updated_metadata.additional_properties = d + return audit_metadata_automation_token_updated_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py new file mode 100644 index 0000000..e47bd5e --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenUpdatedMetadataT(StrEnum): + AUTOMATIONTOKENUPDATED = "automationTokenUpdated" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata.py new file mode 100644 index 0000000..d9bba52 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_used_metadata.py @@ -0,0 +1,100 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataAutomationTokenUsedMetadata") + + +@_attrs_define +class AuditMetadataAutomationTokenUsedMetadata: + """An automation token was used on this account. string AutomationTokenUsedMetadata.Flow is a `AutomationTokenFlow` + name. + + Attributes: + token_id (UUID): + name (str): + flow (str): + t (AuditMetadataAutomationTokenUsedMetadataT | Unset): + """ + + token_id: UUID + name: str + flow: str + t: AuditMetadataAutomationTokenUsedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + token_id = str(self.token_id) + + name = self.name + + flow = self.flow + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "tokenId": token_id, + "name": name, + "flow": flow, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + token_id = UUID(d.pop("tokenId")) + + name = d.pop("name") + + flow = d.pop("flow") + + _t = d.pop("t", UNSET) + t: AuditMetadataAutomationTokenUsedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataAutomationTokenUsedMetadataT(_t) + + audit_metadata_automation_token_used_metadata = cls( + token_id=token_id, + name=name, + flow=flow, + t=t, + ) + + audit_metadata_automation_token_used_metadata.additional_properties = d + return audit_metadata_automation_token_used_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py new file mode 100644 index 0000000..591cb62 --- /dev/null +++ b/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataAutomationTokenUsedMetadataT(StrEnum): + AUTOMATIONTOKENUSED = "automationTokenUsed" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata.py new file mode 100644 index 0000000..c1e7b8a --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_change_requested_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataEmailChangeRequestedMetadata") + + +@_attrs_define +class AuditMetadataEmailChangeRequestedMetadata: + """ + Attributes: + new_email (str): + t (AuditMetadataEmailChangeRequestedMetadataT | Unset): + """ + + new_email: str + t: AuditMetadataEmailChangeRequestedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + new_email = self.new_email + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "newEmail": new_email, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + new_email = d.pop("newEmail") + + _t = d.pop("t", UNSET) + t: AuditMetadataEmailChangeRequestedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataEmailChangeRequestedMetadataT(_t) + + audit_metadata_email_change_requested_metadata = cls( + new_email=new_email, + t=t, + ) + + audit_metadata_email_change_requested_metadata.additional_properties = d + return audit_metadata_email_change_requested_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py new file mode 100644 index 0000000..5cf3cd0 --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataEmailChangeRequestedMetadataT(StrEnum): + EMAILCHANGEREQUESTED = "emailChangeRequested" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata.py b/openshock/rest/models/audit_metadata_email_changed_metadata.py new file mode 100644 index 0000000..59f2ac4 --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_changed_metadata.py @@ -0,0 +1,89 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataEmailChangedMetadata") + + +@_attrs_define +class AuditMetadataEmailChangedMetadata: + """ + Attributes: + old (str): + new (str): + t (AuditMetadataEmailChangedMetadataT | Unset): + """ + + old: str + new: str + t: AuditMetadataEmailChangedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + old = self.old + + new = self.new + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "old": old, + "new": new, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + old = d.pop("old") + + new = d.pop("new") + + _t = d.pop("t", UNSET) + t: AuditMetadataEmailChangedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataEmailChangedMetadataT(_t) + + audit_metadata_email_changed_metadata = cls( + old=old, + new=new, + t=t, + ) + + audit_metadata_email_changed_metadata.additional_properties = d + return audit_metadata_email_changed_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata_t.py b/openshock/rest/models/audit_metadata_email_changed_metadata_t.py new file mode 100644 index 0000000..1bcee56 --- /dev/null +++ b/openshock/rest/models/audit_metadata_email_changed_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataEmailChangedMetadataT(StrEnum): + EMAILCHANGED = "emailChanged" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_login_metadata.py b/openshock/rest/models/audit_metadata_login_metadata.py new file mode 100644 index 0000000..56879d2 --- /dev/null +++ b/openshock/rest/models/audit_metadata_login_metadata.py @@ -0,0 +1,82 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataLoginMetadata") + + +@_attrs_define +class AuditMetadataLoginMetadata: + """ + Attributes: + session_id (UUID): + t (AuditMetadataLoginMetadataT | Unset): + """ + + session_id: UUID + t: AuditMetadataLoginMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + session_id = str(self.session_id) + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "sessionId": session_id, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + session_id = UUID(d.pop("sessionId")) + + _t = d.pop("t", UNSET) + t: AuditMetadataLoginMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataLoginMetadataT(_t) + + audit_metadata_login_metadata = cls( + session_id=session_id, + t=t, + ) + + audit_metadata_login_metadata.additional_properties = d + return audit_metadata_login_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_login_metadata_t.py b/openshock/rest/models/audit_metadata_login_metadata_t.py new file mode 100644 index 0000000..d98a11a --- /dev/null +++ b/openshock/rest/models/audit_metadata_login_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataLoginMetadataT(StrEnum): + LOGIN = "login" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py new file mode 100644 index 0000000..96f4469 --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataOAuthConnectedMetadata") + + +@_attrs_define +class AuditMetadataOAuthConnectedMetadata: + """ + Attributes: + provider (str): + t (AuditMetadataOAuthConnectedMetadataT | Unset): + """ + + provider: str + t: AuditMetadataOAuthConnectedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + provider = self.provider + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "provider": provider, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + provider = d.pop("provider") + + _t = d.pop("t", UNSET) + t: AuditMetadataOAuthConnectedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataOAuthConnectedMetadataT(_t) + + audit_metadata_o_auth_connected_metadata = cls( + provider=provider, + t=t, + ) + + audit_metadata_o_auth_connected_metadata.additional_properties = d + return audit_metadata_o_auth_connected_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py new file mode 100644 index 0000000..6d80bfc --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataOAuthConnectedMetadataT(StrEnum): + OAUTHCONNECTED = "oauthConnected" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py new file mode 100644 index 0000000..b7ee896 --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py @@ -0,0 +1,81 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataOAuthDisconnectedMetadata") + + +@_attrs_define +class AuditMetadataOAuthDisconnectedMetadata: + """ + Attributes: + provider (str): + t (AuditMetadataOAuthDisconnectedMetadataT | Unset): + """ + + provider: str + t: AuditMetadataOAuthDisconnectedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + provider = self.provider + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "provider": provider, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + provider = d.pop("provider") + + _t = d.pop("t", UNSET) + t: AuditMetadataOAuthDisconnectedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataOAuthDisconnectedMetadataT(_t) + + audit_metadata_o_auth_disconnected_metadata = cls( + provider=provider, + t=t, + ) + + audit_metadata_o_auth_disconnected_metadata.additional_properties = d + return audit_metadata_o_auth_disconnected_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py new file mode 100644 index 0000000..c528f73 --- /dev/null +++ b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataOAuthDisconnectedMetadataT(StrEnum): + OAUTHDISCONNECTED = "oauthDisconnected" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata.py b/openshock/rest/models/audit_metadata_username_changed_metadata.py new file mode 100644 index 0000000..a1ee8ea --- /dev/null +++ b/openshock/rest/models/audit_metadata_username_changed_metadata.py @@ -0,0 +1,89 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AuditMetadataUsernameChangedMetadata") + + +@_attrs_define +class AuditMetadataUsernameChangedMetadata: + """ + Attributes: + old (str): + new (str): + t (AuditMetadataUsernameChangedMetadataT | Unset): + """ + + old: str + new: str + t: AuditMetadataUsernameChangedMetadataT | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + old = self.old + + new = self.new + + t: str | Unset = UNSET + if not isinstance(self.t, Unset): + t = self.t.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "old": old, + "new": new, + } + ) + if t is not UNSET: + field_dict["t"] = t + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + old = d.pop("old") + + new = d.pop("new") + + _t = d.pop("t", UNSET) + t: AuditMetadataUsernameChangedMetadataT | Unset + if isinstance(_t, Unset): + t = UNSET + else: + t = AuditMetadataUsernameChangedMetadataT(_t) + + audit_metadata_username_changed_metadata = cls( + old=old, + new=new, + t=t, + ) + + audit_metadata_username_changed_metadata.additional_properties = d + return audit_metadata_username_changed_metadata + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata_t.py b/openshock/rest/models/audit_metadata_username_changed_metadata_t.py new file mode 100644 index 0000000..84465c1 --- /dev/null +++ b/openshock/rest/models/audit_metadata_username_changed_metadata_t.py @@ -0,0 +1,9 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AuditMetadataUsernameChangedMetadataT(StrEnum): + USERNAMECHANGED = "usernameChanged" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/automation_token_dto.py b/openshock/rest/models/automation_token_dto.py new file mode 100644 index 0000000..224cf7a --- /dev/null +++ b/openshock/rest/models/automation_token_dto.py @@ -0,0 +1,197 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="AutomationTokenDto") + + +@_attrs_define +class AutomationTokenDto: + """ + Attributes: + id (UUID): + name (str): + types (list[AutomationTokenType]): + created_at (datetime.datetime): + last_used_at (datetime.datetime | None | Unset): + last_rotated_at (datetime.datetime | None | Unset): + use_count (int | Unset): + auto_cleanup_users (bool | Unset): + auto_cleanup_after (None | str | Unset): + """ + + id: UUID + name: str + types: list[AutomationTokenType] + created_at: datetime.datetime + last_used_at: datetime.datetime | None | Unset = UNSET + last_rotated_at: datetime.datetime | None | Unset = UNSET + use_count: int | Unset = UNSET + auto_cleanup_users: bool | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + types = [] + for types_item_data in self.types: + types_item = types_item_data.value + types.append(types_item) + + created_at = self.created_at.isoformat() + + last_used_at: None | str | Unset + if isinstance(self.last_used_at, Unset): + last_used_at = UNSET + elif isinstance(self.last_used_at, datetime.datetime): + last_used_at = self.last_used_at.isoformat() + else: + last_used_at = self.last_used_at + + last_rotated_at: None | str | Unset + if isinstance(self.last_rotated_at, Unset): + last_rotated_at = UNSET + elif isinstance(self.last_rotated_at, datetime.datetime): + last_rotated_at = self.last_rotated_at.isoformat() + else: + last_rotated_at = self.last_rotated_at + + use_count = self.use_count + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "types": types, + "createdAt": created_at, + } + ) + if last_used_at is not UNSET: + field_dict["lastUsedAt"] = last_used_at + if last_rotated_at is not UNSET: + field_dict["lastRotatedAt"] = last_rotated_at + if use_count is not UNSET: + field_dict["useCount"] = use_count + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + types = [] + _types = d.pop("types") + for types_item_data in _types: + types_item = AutomationTokenType(types_item_data) + + types.append(types_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_last_used_at(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_at_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + last_used_at = _parse_last_used_at(d.pop("lastUsedAt", UNSET)) + + def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) + + return last_rotated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) + + use_count = d.pop("useCount", UNSET) + + auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + automation_token_dto = cls( + id=id, + name=name, + types=types, + created_at=created_at, + last_used_at=last_used_at, + last_rotated_at=last_rotated_at, + use_count=use_count, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + automation_token_dto.additional_properties = d + return automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/automation_token_type.py b/openshock/rest/models/automation_token_type.py new file mode 100644 index 0000000..b270e30 --- /dev/null +++ b/openshock/rest/models/automation_token_type.py @@ -0,0 +1,11 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class AutomationTokenType(StrEnum): + CONTROLSTATSREAD = "ControlStatsRead" + RATELIMIT = "RateLimit" + TURNSTILE = "Turnstile" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/change_email_request.py b/openshock/rest/models/change_email_request.py new file mode 100644 index 0000000..918e9c6 --- /dev/null +++ b/openshock/rest/models/change_email_request.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ChangeEmailRequest") + + +@_attrs_define +class ChangeEmailRequest: + """ + Attributes: + current_password (str): + email (str): + """ + + current_password: str + email: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + current_password = self.current_password + + email = self.email + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "currentPassword": current_password, + "email": email, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + current_password = d.pop("currentPassword") + + email = d.pop("email") + + change_email_request = cls( + current_password=current_password, + email=email, + ) + + change_email_request.additional_properties = d + return change_email_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/change_password_request.py b/openshock/rest/models/change_password_request.py new file mode 100644 index 0000000..6337c0e --- /dev/null +++ b/openshock/rest/models/change_password_request.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ChangePasswordRequest") + + +@_attrs_define +class ChangePasswordRequest: + """ + Attributes: + current_password (str): + new_password (str): + """ + + current_password: str + new_password: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + current_password = self.current_password + + new_password = self.new_password + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "currentPassword": current_password, + "newPassword": new_password, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + current_password = d.pop("currentPassword") + + new_password = d.pop("newPassword") + + change_password_request = cls( + current_password=current_password, + new_password=new_password, + ) + + change_password_request.additional_properties = d + return change_password_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_add_item_request.py b/openshock/rest/models/configuration_add_item_request.py new file mode 100644 index 0000000..a2650e7 --- /dev/null +++ b/openshock/rest/models/configuration_add_item_request.py @@ -0,0 +1,91 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.configuration_value_type import ConfigurationValueType + +T = TypeVar("T", bound="ConfigurationAddItemRequest") + + +@_attrs_define +class ConfigurationAddItemRequest: + """Request DTO for adding a new configuration item. + + Attributes: + name (str): The unique name of the configuration item. + Must consist of uppercase letters and underscores only. + description (str): A human-readable description of the configuration item’s purpose. + type_ (ConfigurationValueType): + value (str): The initial value for the configuration item, serialized as a string. + Must conform to the format required by ConfigurationValueType ConfigurationAddItemRequest.Type. + """ + + name: str + description: str + type_: ConfigurationValueType + value: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + description = self.description + + type_ = self.type_.value + + value = self.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "description": description, + "type": type_, + "value": value, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + description = d.pop("description") + + type_ = ConfigurationValueType(d.pop("type")) + + value = d.pop("value") + + configuration_add_item_request = cls( + name=name, + description=description, + type_=type_, + value=value, + ) + + configuration_add_item_request.additional_properties = d + return configuration_add_item_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_item_dto.py b/openshock/rest/models/configuration_item_dto.py new file mode 100644 index 0000000..428129b --- /dev/null +++ b/openshock/rest/models/configuration_item_dto.py @@ -0,0 +1,106 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.configuration_value_type import ConfigurationValueType + +T = TypeVar("T", bound="ConfigurationItemDto") + + +@_attrs_define +class ConfigurationItemDto: + """Data transfer object representing a configuration item. + + Attributes: + name (str): The unique name of the configuration item. + description (str): A human-readable description of what this configuration item controls. + type_ (ConfigurationValueType): + value (str): The current value of the configuration item, serialized as a string. + updated_at (datetime.datetime): The timestamp when the configuration was last updated. + created_at (datetime.datetime): The timestamp when the configuration was originally created. + """ + + name: str + description: str + type_: ConfigurationValueType + value: str + updated_at: datetime.datetime + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + description = self.description + + type_ = self.type_.value + + value = self.value + + updated_at = self.updated_at.isoformat() + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "description": description, + "type": type_, + "value": value, + "updatedAt": updated_at, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + description = d.pop("description") + + type_ = ConfigurationValueType(d.pop("type")) + + value = d.pop("value") + + updated_at = datetime.datetime.fromisoformat(d.pop("updatedAt")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + configuration_item_dto = cls( + name=name, + description=description, + type_=type_, + value=value, + updated_at=updated_at, + created_at=created_at, + ) + + configuration_item_dto.additional_properties = d + return configuration_item_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_update_item_request.py b/openshock/rest/models/configuration_update_item_request.py new file mode 100644 index 0000000..a2bb38b --- /dev/null +++ b/openshock/rest/models/configuration_update_item_request.py @@ -0,0 +1,110 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="ConfigurationUpdateItemRequest") + + +@_attrs_define +class ConfigurationUpdateItemRequest: + """Request DTO for updating a configuration item. + Either string? ConfigurationUpdateItemRequest.Description or string? ConfigurationUpdateItemRequest.Value (or both) + may be provided. + If both are null, no update action is performed. + + Attributes: + name (str): The name of the configuration item to update. + Must consist only of uppercase letters and underscores. + description (None | str | Unset): (Optional) New description for the configuration item. + value (None | str | Unset): (Optional) New value for the configuration item. + Must match the format expected by its existing ConfigurationValueType. + """ + + name: str + description: None | str | Unset = UNSET + value: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + description: None | str | Unset + if isinstance(self.description, Unset): + description = UNSET + else: + description = self.description + + value: None | str | Unset + if isinstance(self.value, Unset): + value = UNSET + else: + value = self.value + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + } + ) + if description is not UNSET: + field_dict["description"] = description + if value is not UNSET: + field_dict["value"] = value + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + def _parse_description(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + description = _parse_description(d.pop("description", UNSET)) + + def _parse_value(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + value = _parse_value(d.pop("value", UNSET)) + + configuration_update_item_request = cls( + name=name, + description=description, + value=value, + ) + + configuration_update_item_request.additional_properties = d + return configuration_update_item_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/configuration_value_type.py b/openshock/rest/models/configuration_value_type.py new file mode 100644 index 0000000..b809802 --- /dev/null +++ b/openshock/rest/models/configuration_value_type.py @@ -0,0 +1,13 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class ConfigurationValueType(StrEnum): + BOOL = "Bool" + FLOAT = "Float" + INT = "Int" + JSON = "Json" + STRING = "String" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/create_automation_token_dto.py b/openshock/rest/models/create_automation_token_dto.py new file mode 100644 index 0000000..00e0bf8 --- /dev/null +++ b/openshock/rest/models/create_automation_token_dto.py @@ -0,0 +1,112 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="CreateAutomationTokenDto") + + +@_attrs_define +class CreateAutomationTokenDto: + """ + Attributes: + name (str): + types (list[AutomationTokenType]): + auto_cleanup_users (bool | Unset): Whether the automated accounts this token creates are deleted once TimeSpan? + CreateAutomationTokenDto.AutoCleanupAfter has + passed since they were created. Off by default; accounts the token didn't create are never deleted. + auto_cleanup_after (None | str | Unset): + """ + + name: str + types: list[AutomationTokenType] + auto_cleanup_users: bool | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + types = [] + for types_item_data in self.types: + types_item = types_item_data.value + types.append(types_item) + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "types": types, + } + ) + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + types = [] + _types = d.pop("types") + for types_item_data in _types: + types_item = AutomationTokenType(types_item_data) + + types.append(types_item) + + auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + create_automation_token_dto = cls( + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + create_automation_token_dto.additional_properties = d + return create_automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/create_token_request_v2.py b/openshock/rest/models/create_token_request_v2.py new file mode 100644 index 0000000..7dfea1a --- /dev/null +++ b/openshock/rest/models/create_token_request_v2.py @@ -0,0 +1,127 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.shocker_control_settings import ShockerControlSettings + + +T = TypeVar("T", bound="CreateTokenRequestV2") + + +@_attrs_define +class CreateTokenRequestV2: + """ + Attributes: + name (str): + permissions (list[PermissionType]): + shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits + for intensity and duration. + valid_until (datetime.datetime | None | Unset): + """ + + name: str + permissions: list[PermissionType] + shocker_control: ShockerControlSettings + valid_until: datetime.datetime | None | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + shocker_control = self.shocker_control.to_dict() + + valid_until: None | str | Unset + if isinstance(self.valid_until, Unset): + valid_until = UNSET + elif isinstance(self.valid_until, datetime.datetime): + valid_until = self.valid_until.isoformat() + else: + valid_until = self.valid_until + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "permissions": permissions, + "shockerControl": shocker_control, + } + ) + if valid_until is not UNSET: + field_dict["validUntil"] = valid_until + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 + + d = dict(src_dict) + name = d.pop("name") + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) + + def _parse_valid_until(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + valid_until_type_1 = datetime.datetime.fromisoformat(data) + + return valid_until_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + valid_until = _parse_valid_until(d.pop("validUntil", UNSET)) + + create_token_request_v2 = cls( + name=name, + permissions=permissions, + shocker_control=shocker_control, + valid_until=valid_until, + ) + + create_token_request_v2.additional_properties = d + return create_token_request_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/created_automation_token_dto.py b/openshock/rest/models/created_automation_token_dto.py new file mode 100644 index 0000000..882a7e2 --- /dev/null +++ b/openshock/rest/models/created_automation_token_dto.py @@ -0,0 +1,166 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="CreatedAutomationTokenDto") + + +@_attrs_define +class CreatedAutomationTokenDto: + """ + Attributes: + id (UUID): + name (str): + secret (str): + types (list[AutomationTokenType]): + created_at (datetime.datetime): + last_rotated_at (datetime.datetime | None | Unset): + auto_cleanup_users (bool | Unset): + auto_cleanup_after (None | str | Unset): + """ + + id: UUID + name: str + secret: str + types: list[AutomationTokenType] + created_at: datetime.datetime + last_rotated_at: datetime.datetime | None | Unset = UNSET + auto_cleanup_users: bool | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + secret = self.secret + + types = [] + for types_item_data in self.types: + types_item = types_item_data.value + types.append(types_item) + + created_at = self.created_at.isoformat() + + last_rotated_at: None | str | Unset + if isinstance(self.last_rotated_at, Unset): + last_rotated_at = UNSET + elif isinstance(self.last_rotated_at, datetime.datetime): + last_rotated_at = self.last_rotated_at.isoformat() + else: + last_rotated_at = self.last_rotated_at + + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "secret": secret, + "types": types, + "createdAt": created_at, + } + ) + if last_rotated_at is not UNSET: + field_dict["lastRotatedAt"] = last_rotated_at + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + secret = d.pop("secret") + + types = [] + _types = d.pop("types") + for types_item_data in _types: + types_item = AutomationTokenType(types_item_data) + + types.append(types_item) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, str): + raise TypeError() + last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) + + return last_rotated_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None | Unset, data) + + last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) + + auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + created_automation_token_dto = cls( + id=id, + name=name, + secret=secret, + types=types, + created_at=created_at, + last_rotated_at=last_rotated_at, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + created_automation_token_dto.additional_properties = d + return created_automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/edit_token_request_v2.py b/openshock/rest/models/edit_token_request_v2.py new file mode 100644 index 0000000..3cd7cfa --- /dev/null +++ b/openshock/rest/models/edit_token_request_v2.py @@ -0,0 +1,95 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType + +if TYPE_CHECKING: + from ..models.shocker_control_settings import ShockerControlSettings + + +T = TypeVar("T", bound="EditTokenRequestV2") + + +@_attrs_define +class EditTokenRequestV2: + """ + Attributes: + name (str): + permissions (list[PermissionType]): + shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits + for intensity and duration. + """ + + name: str + permissions: list[PermissionType] + shocker_control: ShockerControlSettings + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + shocker_control = self.shocker_control.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + "permissions": permissions, + "shockerControl": shocker_control, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 + + d = dict(src_dict) + name = d.pop("name") + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) + + edit_token_request_v2 = cls( + name=name, + permissions=permissions, + shocker_control=shocker_control, + ) + + edit_token_request_v2.additional_properties = d + return edit_token_request_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_request.py b/openshock/rest/models/email_outbox_bulk_request.py new file mode 100644 index 0000000..fcf889f --- /dev/null +++ b/openshock/rest/models/email_outbox_bulk_request.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxBulkRequest") + + +@_attrs_define +class EmailOutboxBulkRequest: + """A set of email outbox message ids to apply a bulk requeue/cancel/delete to. + + Attributes: + ids (list[UUID]): + """ + + ids: list[UUID] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + ids = [] + for ids_item_data in self.ids: + ids_item = str(ids_item_data) + ids.append(ids_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "ids": ids, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + ids = [] + _ids = d.pop("ids") + for ids_item_data in _ids: + ids_item = UUID(ids_item_data) + + ids.append(ids_item) + + email_outbox_bulk_request = cls( + ids=ids, + ) + + email_outbox_bulk_request.additional_properties = d + return email_outbox_bulk_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_result_dto.py b/openshock/rest/models/email_outbox_bulk_result_dto.py new file mode 100644 index 0000000..2d7ad4f --- /dev/null +++ b/openshock/rest/models/email_outbox_bulk_result_dto.py @@ -0,0 +1,72 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxBulkResultDto") + + +@_attrs_define +class EmailOutboxBulkResultDto: + """Outcome of a bulk email outbox operation: how many ids were requested and how many rows were + actually affected (rows that were missing or in an ineligible state are silently not counted). + + Attributes: + requested (int): + affected (int): + """ + + requested: int + affected: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + requested = self.requested + + affected = self.affected + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "requested": requested, + "affected": affected, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + requested = d.pop("requested") + + affected = d.pop("affected") + + email_outbox_bulk_result_dto = cls( + requested=requested, + affected=affected, + ) + + email_outbox_bulk_result_dto.additional_properties = d + return email_outbox_bulk_result_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto.py b/openshock/rest/models/email_outbox_message_dto.py new file mode 100644 index 0000000..80d3e7c --- /dev/null +++ b/openshock/rest/models/email_outbox_message_dto.py @@ -0,0 +1,226 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.email_status import EmailStatus +from ..models.email_type import EmailType + +if TYPE_CHECKING: + from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload + + +T = TypeVar("T", bound="EmailOutboxMessageDto") + + +@_attrs_define +class EmailOutboxMessageDto: + """An EmailOutboxMessage as exposed to admins on the mail-queue page. Mirrors the row + verbatim - the outbox stores no rendered body and no usable secret, so every field is safe to show. + + Attributes: + id (UUID): + type_ (EmailType): The kind of email an outbox message represents. The outbox stores + only the intent to send one of these, never a rendered body or a usable secret, the + consumer maps the type to the matching template and (for token-bearing types) mints a fresh + secret at send time. + recipient (str): + recipient_name (None | str): + payload (EmailOutboxMessageDtoPayload): + coalesce_key (None | str): + status (EmailStatus): Delivery state of an email outbox message. + attempt_count (int): + next_attempt_at (datetime.datetime): + last_error (None | str): + created_at (datetime.datetime): + sent_at (datetime.datetime | None): + failed_at (datetime.datetime | None): + """ + + id: UUID + type_: EmailType + recipient: str + recipient_name: None | str + payload: EmailOutboxMessageDtoPayload + coalesce_key: None | str + status: EmailStatus + attempt_count: int + next_attempt_at: datetime.datetime + last_error: None | str + created_at: datetime.datetime + sent_at: datetime.datetime | None + failed_at: datetime.datetime | None + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + type_ = self.type_.value + + recipient = self.recipient + + recipient_name: None | str + recipient_name = self.recipient_name + + payload = self.payload.to_dict() + + coalesce_key: None | str + coalesce_key = self.coalesce_key + + status = self.status.value + + attempt_count = self.attempt_count + + next_attempt_at = self.next_attempt_at.isoformat() + + last_error: None | str + last_error = self.last_error + + created_at = self.created_at.isoformat() + + sent_at: None | str + if isinstance(self.sent_at, datetime.datetime): + sent_at = self.sent_at.isoformat() + else: + sent_at = self.sent_at + + failed_at: None | str + if isinstance(self.failed_at, datetime.datetime): + failed_at = self.failed_at.isoformat() + else: + failed_at = self.failed_at + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "type": type_, + "recipient": recipient, + "recipientName": recipient_name, + "payload": payload, + "coalesceKey": coalesce_key, + "status": status, + "attemptCount": attempt_count, + "nextAttemptAt": next_attempt_at, + "lastError": last_error, + "createdAt": created_at, + "sentAt": sent_at, + "failedAt": failed_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + type_ = EmailType(d.pop("type")) + + recipient = d.pop("recipient") + + def _parse_recipient_name(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + recipient_name = _parse_recipient_name(d.pop("recipientName")) + + payload = EmailOutboxMessageDtoPayload.from_dict(d.pop("payload")) + + def _parse_coalesce_key(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + coalesce_key = _parse_coalesce_key(d.pop("coalesceKey")) + + status = EmailStatus(d.pop("status")) + + attempt_count = d.pop("attemptCount") + + next_attempt_at = datetime.datetime.fromisoformat(d.pop("nextAttemptAt")) + + def _parse_last_error(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + last_error = _parse_last_error(d.pop("lastError")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_sent_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + sent_at_type_1 = datetime.datetime.fromisoformat(data) + + return sent_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + sent_at = _parse_sent_at(d.pop("sentAt")) + + def _parse_failed_at(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + failed_at_type_1 = datetime.datetime.fromisoformat(data) + + return failed_at_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + failed_at = _parse_failed_at(d.pop("failedAt")) + + email_outbox_message_dto = cls( + id=id, + type_=type_, + recipient=recipient, + recipient_name=recipient_name, + payload=payload, + coalesce_key=coalesce_key, + status=status, + attempt_count=attempt_count, + next_attempt_at=next_attempt_at, + last_error=last_error, + created_at=created_at, + sent_at=sent_at, + failed_at=failed_at, + ) + + email_outbox_message_dto.additional_properties = d + return email_outbox_message_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto_payload.py b/openshock/rest/models/email_outbox_message_dto_payload.py new file mode 100644 index 0000000..2db2ad1 --- /dev/null +++ b/openshock/rest/models/email_outbox_message_dto_payload.py @@ -0,0 +1,46 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxMessageDtoPayload") + + +@_attrs_define +class EmailOutboxMessageDtoPayload: + additional_properties: dict[str, str] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + email_outbox_message_dto_payload = cls() + + email_outbox_message_dto_payload.additional_properties = d + return email_outbox_message_dto_payload + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> str: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: str) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_stats_dto.py b/openshock/rest/models/email_outbox_stats_dto.py new file mode 100644 index 0000000..1cd818c --- /dev/null +++ b/openshock/rest/models/email_outbox_stats_dto.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailOutboxStatsDto") + + +@_attrs_define +class EmailOutboxStatsDto: + """Count of email outbox rows in each delivery state, for the admin mail-queue overview tiles. + + Attributes: + pending (int): + sending (int): + sent (int): + failed (int): + skipped (int): + total (int): + """ + + pending: int + sending: int + sent: int + failed: int + skipped: int + total: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + pending = self.pending + + sending = self.sending + + sent = self.sent + + failed = self.failed + + skipped = self.skipped + + total = self.total + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "pending": pending, + "sending": sending, + "sent": sent, + "failed": failed, + "skipped": skipped, + "total": total, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + pending = d.pop("pending") + + sending = d.pop("sending") + + sent = d.pop("sent") + + failed = d.pop("failed") + + skipped = d.pop("skipped") + + total = d.pop("total") + + email_outbox_stats_dto = cls( + pending=pending, + sending=sending, + sent=sent, + failed=failed, + skipped=skipped, + total=total, + ) + + email_outbox_stats_dto.additional_properties = d + return email_outbox_stats_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_provider_blacklist_dto.py b/openshock/rest/models/email_provider_blacklist_dto.py new file mode 100644 index 0000000..53a85f4 --- /dev/null +++ b/openshock/rest/models/email_provider_blacklist_dto.py @@ -0,0 +1,80 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="EmailProviderBlacklistDto") + + +@_attrs_define +class EmailProviderBlacklistDto: + """ + Attributes: + id (UUID): + domain (str): + created_at (datetime.datetime): + """ + + id: UUID + domain: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + domain = self.domain + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "domain": domain, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + domain = d.pop("domain") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + email_provider_blacklist_dto = cls( + id=id, + domain=domain, + created_at=created_at, + ) + + email_provider_blacklist_dto.additional_properties = d + return email_provider_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/email_status.py b/openshock/rest/models/email_status.py new file mode 100644 index 0000000..12e74f7 --- /dev/null +++ b/openshock/rest/models/email_status.py @@ -0,0 +1,13 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class EmailStatus(StrEnum): + FAILED = "Failed" + PENDING = "Pending" + SENDING = "Sending" + SENT = "Sent" + SKIPPED = "Skipped" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/email_type.py b/openshock/rest/models/email_type.py new file mode 100644 index 0000000..a778271 --- /dev/null +++ b/openshock/rest/models/email_type.py @@ -0,0 +1,12 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class EmailType(StrEnum): + ACCOUNTACTIVATION = "AccountActivation" + EMAILCHANGENOTICE = "EmailChangeNotice" + EMAILVERIFICATION = "EmailVerification" + PASSWORDRESET = "PasswordReset" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py b/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py new file mode 100644 index 0000000..8aa0cb9 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_online_device_response import AdminOnlineDeviceResponse + + +T = TypeVar("T", bound="LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse") + + +@_attrs_define +class LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse: + """ + Attributes: + message (str): Default: ''. + data (list[AdminOnlineDeviceResponse]): + """ + + data: list[AdminOnlineDeviceResponse] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_online_device_response import AdminOnlineDeviceResponse # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = AdminOnlineDeviceResponse.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_array_of_admin_online_device_response = cls( + message=message, + data=data, + ) + + legacy_data_response_of_array_of_admin_online_device_response.additional_properties = d + return legacy_data_response_of_array_of_admin_online_device_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py b/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py new file mode 100644 index 0000000..757a667 --- /dev/null +++ b/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py @@ -0,0 +1,84 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.ota_item import OtaItem + + +T = TypeVar("T", bound="LegacyDataResponseOfIReadOnlyCollectionOfOtaItem") + + +@_attrs_define +class LegacyDataResponseOfIReadOnlyCollectionOfOtaItem: + """ + Attributes: + message (str): Default: ''. + data (list[OtaItem]): + """ + + data: list[OtaItem] + message: str = "" + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + message = self.message + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "message": message, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.ota_item import OtaItem # noqa: PLC0415 + + d = dict(src_dict) + message = d.pop("message") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = OtaItem.from_dict(data_item_data) + + data.append(data_item) + + legacy_data_response_of_i_read_only_collection_of_ota_item = cls( + message=message, + data=data, + ) + + legacy_data_response_of_i_read_only_collection_of_ota_item.additional_properties = d + return legacy_data_response_of_i_read_only_collection_of_ota_item + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/login_session_response.py b/openshock/rest/models/login_session_response.py new file mode 100644 index 0000000..47328f3 --- /dev/null +++ b/openshock/rest/models/login_session_response.py @@ -0,0 +1,203 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="LoginSessionResponse") + + +@_attrs_define +class LoginSessionResponse: + """ + Attributes: + id (UUID): + ip (str): An IPv4 or IPv6 address in its textual form. + user_agent (str): + created (datetime.datetime): + expires (datetime.datetime): + last_used (datetime.datetime | None): + asn_org (None | str | Unset): + is_vpn (bool | None | Unset): + country_code (None | str | Unset): + city (None | str | Unset): + """ + + id: UUID + ip: str + user_agent: str + created: datetime.datetime + expires: datetime.datetime + last_used: datetime.datetime | None + asn_org: None | str | Unset = UNSET + is_vpn: bool | None | Unset = UNSET + country_code: None | str | Unset = UNSET + city: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + ip = self.ip + + user_agent = self.user_agent + + created = self.created.isoformat() + + expires = self.expires.isoformat() + + last_used: None | str + if isinstance(self.last_used, datetime.datetime): + last_used = self.last_used.isoformat() + else: + last_used = self.last_used + + asn_org: None | str | Unset + if isinstance(self.asn_org, Unset): + asn_org = UNSET + else: + asn_org = self.asn_org + + is_vpn: bool | None | Unset + if isinstance(self.is_vpn, Unset): + is_vpn = UNSET + else: + is_vpn = self.is_vpn + + country_code: None | str | Unset + if isinstance(self.country_code, Unset): + country_code = UNSET + else: + country_code = self.country_code + + city: None | str | Unset + if isinstance(self.city, Unset): + city = UNSET + else: + city = self.city + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "ip": ip, + "userAgent": user_agent, + "created": created, + "expires": expires, + "lastUsed": last_used, + } + ) + if asn_org is not UNSET: + field_dict["asnOrg"] = asn_org + if is_vpn is not UNSET: + field_dict["isVpn"] = is_vpn + if country_code is not UNSET: + field_dict["countryCode"] = country_code + if city is not UNSET: + field_dict["city"] = city + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + ip = d.pop("ip") + + user_agent = d.pop("userAgent") + + created = datetime.datetime.fromisoformat(d.pop("created")) + + expires = datetime.datetime.fromisoformat(d.pop("expires")) + + def _parse_last_used(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + last_used = _parse_last_used(d.pop("lastUsed")) + + def _parse_asn_org(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + asn_org = _parse_asn_org(d.pop("asnOrg", UNSET)) + + def _parse_is_vpn(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + is_vpn = _parse_is_vpn(d.pop("isVpn", UNSET)) + + def _parse_country_code(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + country_code = _parse_country_code(d.pop("countryCode", UNSET)) + + def _parse_city(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + city = _parse_city(d.pop("city", UNSET)) + + login_session_response = cls( + id=id, + ip=ip, + user_agent=user_agent, + created=created, + expires=expires, + last_used=last_used, + asn_org=asn_org, + is_vpn=is_vpn, + country_code=country_code, + city=city, + ) + + login_session_response.additional_properties = d + return login_session_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/match_type_enum.py b/openshock/rest/models/match_type_enum.py new file mode 100644 index 0000000..f734f77 --- /dev/null +++ b/openshock/rest/models/match_type_enum.py @@ -0,0 +1,10 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class MatchTypeEnum(StrEnum): + CONTAINS = "Contains" + EXACT = "Exact" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/o_auth_connection_response.py b/openshock/rest/models/o_auth_connection_response.py new file mode 100644 index 0000000..ce6a08a --- /dev/null +++ b/openshock/rest/models/o_auth_connection_response.py @@ -0,0 +1,93 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="OAuthConnectionResponse") + + +@_attrs_define +class OAuthConnectionResponse: + """ + Attributes: + provider_key (str): + external_id (str): + display_name (None | str): + linked_at (datetime.datetime): + """ + + provider_key: str + external_id: str + display_name: None | str + linked_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + provider_key = self.provider_key + + external_id = self.external_id + + display_name: None | str + display_name = self.display_name + + linked_at = self.linked_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "providerKey": provider_key, + "externalId": external_id, + "displayName": display_name, + "linkedAt": linked_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + provider_key = d.pop("providerKey") + + external_id = d.pop("externalId") + + def _parse_display_name(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + display_name = _parse_display_name(d.pop("displayName")) + + linked_at = datetime.datetime.fromisoformat(d.pop("linkedAt")) + + o_auth_connection_response = cls( + provider_key=provider_key, + external_id=external_id, + display_name=display_name, + linked_at=linked_at, + ) + + o_auth_connection_response.additional_properties = d + return o_auth_connection_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/ota_item.py b/openshock/rest/models/ota_item.py new file mode 100644 index 0000000..7c9e8fd --- /dev/null +++ b/openshock/rest/models/ota_item.py @@ -0,0 +1,103 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.ota_update_status import OtaUpdateStatus + +T = TypeVar("T", bound="OtaItem") + + +@_attrs_define +class OtaItem: + """ + Attributes: + id (int): + started_at (datetime.datetime): + status (OtaUpdateStatus): + version (str): + message (None | str): + """ + + id: int + started_at: datetime.datetime + status: OtaUpdateStatus + version: str + message: None | str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = self.id + + started_at = self.started_at.isoformat() + + status = self.status.value + + version = self.version + + message: None | str + message = self.message + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "startedAt": started_at, + "status": status, + "version": version, + "message": message, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = d.pop("id") + + started_at = datetime.datetime.fromisoformat(d.pop("startedAt")) + + status = OtaUpdateStatus(d.pop("status")) + + version = d.pop("version") + + def _parse_message(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + message = _parse_message(d.pop("message")) + + ota_item = cls( + id=id, + started_at=started_at, + status=status, + version=version, + message=message, + ) + + ota_item.additional_properties = d + return ota_item + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/ota_update_status.py b/openshock/rest/models/ota_update_status.py new file mode 100644 index 0000000..6f8243f --- /dev/null +++ b/openshock/rest/models/ota_update_status.py @@ -0,0 +1,13 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class OtaUpdateStatus(StrEnum): + ERROR = "Error" + FINISHED = "Finished" + RUNNING = "Running" + STARTED = "Started" + TIMEOUT = "Timeout" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/paged_result_of_audit_log_entry_response.py b/openshock/rest/models/paged_result_of_audit_log_entry_response.py new file mode 100644 index 0000000..afb380c --- /dev/null +++ b/openshock/rest/models/paged_result_of_audit_log_entry_response.py @@ -0,0 +1,112 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.audit_log_entry_response import AuditLogEntryResponse + + +T = TypeVar("T", bound="PagedResultOfAuditLogEntryResponse") + + +@_attrs_define +class PagedResultOfAuditLogEntryResponse: + """Page of results for a paginated list endpoint. + + Attributes: + items (list[AuditLogEntryResponse]): Items on the current page. + page (int): 1-based current page index. + page_size (int): Page size used to produce this result. + total_count (int): Total number of items across all pages matching the query. + total_pages (int | Unset): Total number of pages. Always at least 1, even when `TotalCount` is zero. + """ + + items: list[AuditLogEntryResponse] + page: int + page_size: int + total_count: int + total_pages: int | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + items = [] + for items_item_data in self.items: + items_item = items_item_data.to_dict() + items.append(items_item) + + page = self.page + + page_size = self.page_size + + total_count = self.total_count + + total_pages = self.total_pages + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "items": items, + "page": page, + "pageSize": page_size, + "totalCount": total_count, + } + ) + if total_pages is not UNSET: + field_dict["totalPages"] = total_pages + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.audit_log_entry_response import AuditLogEntryResponse # noqa: PLC0415 + + d = dict(src_dict) + items = [] + _items = d.pop("items") + for items_item_data in _items: + items_item = AuditLogEntryResponse.from_dict(items_item_data) + + items.append(items_item) + + page = d.pop("page") + + page_size = d.pop("pageSize") + + total_count = d.pop("totalCount") + + total_pages = d.pop("totalPages", UNSET) + + paged_result_of_audit_log_entry_response = cls( + items=items, + page=page, + page_size=page_size, + total_count=total_count, + total_pages=total_pages, + ) + + paged_result_of_audit_log_entry_response.additional_properties = d + return paged_result_of_audit_log_entry_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_admin_users_view.py b/openshock/rest/models/paginated_of_admin_users_view.py new file mode 100644 index 0000000..fa4499d --- /dev/null +++ b/openshock/rest/models/paginated_of_admin_users_view.py @@ -0,0 +1,100 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.admin_users_view import AdminUsersView + + +T = TypeVar("T", bound="PaginatedOfAdminUsersView") + + +@_attrs_define +class PaginatedOfAdminUsersView: + """ + Attributes: + offset (int): + limit (int): + total (int): + data (list[AdminUsersView]): + """ + + offset: int + limit: int + total: int + data: list[AdminUsersView] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + offset = self.offset + + limit = self.limit + + total = self.total + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "offset": offset, + "limit": limit, + "total": total, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.admin_users_view import AdminUsersView # noqa: PLC0415 + + d = dict(src_dict) + offset = d.pop("offset") + + limit = d.pop("limit") + + total = d.pop("total") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = AdminUsersView.from_dict(data_item_data) + + data.append(data_item) + + paginated_of_admin_users_view = cls( + offset=offset, + limit=limit, + total=total, + data=data, + ) + + paginated_of_admin_users_view.additional_properties = d + return paginated_of_admin_users_view + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_email_outbox_message_dto.py b/openshock/rest/models/paginated_of_email_outbox_message_dto.py new file mode 100644 index 0000000..dffe554 --- /dev/null +++ b/openshock/rest/models/paginated_of_email_outbox_message_dto.py @@ -0,0 +1,100 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.email_outbox_message_dto import EmailOutboxMessageDto + + +T = TypeVar("T", bound="PaginatedOfEmailOutboxMessageDto") + + +@_attrs_define +class PaginatedOfEmailOutboxMessageDto: + """ + Attributes: + offset (int): + limit (int): + total (int): + data (list[EmailOutboxMessageDto]): + """ + + offset: int + limit: int + total: int + data: list[EmailOutboxMessageDto] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + offset = self.offset + + limit = self.limit + + total = self.total + + data = [] + for data_item_data in self.data: + data_item = data_item_data.to_dict() + data.append(data_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "offset": offset, + "limit": limit, + "total": total, + "data": data, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.email_outbox_message_dto import EmailOutboxMessageDto # noqa: PLC0415 + + d = dict(src_dict) + offset = d.pop("offset") + + limit = d.pop("limit") + + total = d.pop("total") + + data = [] + _data = d.pop("data") + for data_item_data in _data: + data_item = EmailOutboxMessageDto.from_dict(data_item_data) + + data.append(data_item) + + paginated_of_email_outbox_message_dto = cls( + offset=offset, + limit=limit, + total=total, + data=data, + ) + + paginated_of_email_outbox_message_dto.additional_properties = d + return paginated_of_email_outbox_message_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/password_hashing_algorithm.py b/openshock/rest/models/password_hashing_algorithm.py new file mode 100644 index 0000000..13a3409 --- /dev/null +++ b/openshock/rest/models/password_hashing_algorithm.py @@ -0,0 +1,11 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class PasswordHashingAlgorithm(StrEnum): + BCRYPT = "BCrypt" + PBKDF2 = "PBKDF2" + UNKNOWN = "Unknown" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/patch_automation_token_dto.py b/openshock/rest/models/patch_automation_token_dto.py new file mode 100644 index 0000000..ac287bc --- /dev/null +++ b/openshock/rest/models/patch_automation_token_dto.py @@ -0,0 +1,154 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.automation_token_type import AutomationTokenType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="PatchAutomationTokenDto") + + +@_attrs_define +class PatchAutomationTokenDto: + """ + Attributes: + name (None | str | Unset): + types (list[AutomationTokenType] | None | Unset): + auto_cleanup_users (bool | None | Unset): + auto_cleanup_after (None | str | Unset): + """ + + name: None | str | Unset = UNSET + types: list[AutomationTokenType] | None | Unset = UNSET + auto_cleanup_users: bool | None | Unset = UNSET + auto_cleanup_after: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name: None | str | Unset + if isinstance(self.name, Unset): + name = UNSET + else: + name = self.name + + types: list[str] | None | Unset + if isinstance(self.types, Unset): + types = UNSET + elif isinstance(self.types, list): + types = [] + for types_type_1_item_data in self.types: + types_type_1_item = types_type_1_item_data.value + types.append(types_type_1_item) + + else: + types = self.types + + auto_cleanup_users: bool | None | Unset + if isinstance(self.auto_cleanup_users, Unset): + auto_cleanup_users = UNSET + else: + auto_cleanup_users = self.auto_cleanup_users + + auto_cleanup_after: None | str | Unset + if isinstance(self.auto_cleanup_after, Unset): + auto_cleanup_after = UNSET + else: + auto_cleanup_after = self.auto_cleanup_after + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if name is not UNSET: + field_dict["name"] = name + if types is not UNSET: + field_dict["types"] = types + if auto_cleanup_users is not UNSET: + field_dict["autoCleanupUsers"] = auto_cleanup_users + if auto_cleanup_after is not UNSET: + field_dict["autoCleanupAfter"] = auto_cleanup_after + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_name(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + name = _parse_name(d.pop("name", UNSET)) + + def _parse_types(data: object) -> list[AutomationTokenType] | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, list): + raise TypeError() + types_type_1 = [] + _types_type_1 = data + for types_type_1_item_data in _types_type_1: + types_type_1_item = AutomationTokenType(types_type_1_item_data) + + types_type_1.append(types_type_1_item) + + return types_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(list[AutomationTokenType] | None | Unset, data) + + types = _parse_types(d.pop("types", UNSET)) + + def _parse_auto_cleanup_users(data: object) -> bool | None | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(bool | None | Unset, data) + + auto_cleanup_users = _parse_auto_cleanup_users(d.pop("autoCleanupUsers", UNSET)) + + def _parse_auto_cleanup_after(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) + + patch_automation_token_dto = cls( + name=name, + types=types, + auto_cleanup_users=auto_cleanup_users, + auto_cleanup_after=auto_cleanup_after, + ) + + patch_automation_token_dto.additional_properties = d + return patch_automation_token_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/report_tokens_request.py b/openshock/rest/models/report_tokens_request.py new file mode 100644 index 0000000..8c6cafb --- /dev/null +++ b/openshock/rest/models/report_tokens_request.py @@ -0,0 +1,70 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="ReportTokensRequest") + + +@_attrs_define +class ReportTokensRequest: + """ + Attributes: + turnstile_response (str): + secrets (list[str]): + """ + + turnstile_response: str + secrets: list[str] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + turnstile_response = self.turnstile_response + + secrets = self.secrets + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "turnstileResponse": turnstile_response, + "secrets": secrets, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + turnstile_response = d.pop("turnstileResponse") + + secrets = cast(list[str], d.pop("secrets")) + + report_tokens_request = cls( + turnstile_response=turnstile_response, + secrets=secrets, + ) + + report_tokens_request.additional_properties = d + return report_tokens_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/send_test_email_dto.py b/openshock/rest/models/send_test_email_dto.py new file mode 100644 index 0000000..e3fd2d6 --- /dev/null +++ b/openshock/rest/models/send_test_email_dto.py @@ -0,0 +1,98 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.email_type import EmailType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="SendTestEmailDto") + + +@_attrs_define +class SendTestEmailDto: + """Request to enqueue a preview/test email of a chosen type to a chosen address. The message is + delivered by the Cron pipeline with placeholder data and a dummy link (no token, no request row). + + Attributes: + type_ (EmailType): The kind of email an outbox message represents. The outbox stores + only the intent to send one of these, never a rendered body or a usable secret, the + consumer maps the type to the matching template and (for token-bearing types) mints a fresh + secret at send time. + recipient (str): Destination address for the test email. + recipient_name (None | str | Unset): Optional display name for the recipient. + """ + + type_: EmailType + recipient: str + recipient_name: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + type_ = self.type_.value + + recipient = self.recipient + + recipient_name: None | str | Unset + if isinstance(self.recipient_name, Unset): + recipient_name = UNSET + else: + recipient_name = self.recipient_name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "type": type_, + "recipient": recipient, + } + ) + if recipient_name is not UNSET: + field_dict["recipientName"] = recipient_name + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + type_ = EmailType(d.pop("type")) + + recipient = d.pop("recipient") + + def _parse_recipient_name(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + recipient_name = _parse_recipient_name(d.pop("recipientName", UNSET)) + + send_test_email_dto = cls( + type_=type_, + recipient=recipient, + recipient_name=recipient_name, + ) + + send_test_email_dto.additional_properties = d + return send_test_email_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_token_paused_request.py b/openshock/rest/models/set_token_paused_request.py new file mode 100644 index 0000000..4a6507c --- /dev/null +++ b/openshock/rest/models/set_token_paused_request.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetTokenPausedRequest") + + +@_attrs_define +class SetTokenPausedRequest: + """ + Attributes: + paused (bool): When true, the token is paused and may not send shocker control messages. + """ + + paused: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + paused = self.paused + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "paused": paused, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + paused = d.pop("paused") + + set_token_paused_request = cls( + paused=paused, + ) + + set_token_paused_request.additional_properties = d + return set_token_paused_request + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_user_email_request_body.py b/openshock/rest/models/set_user_email_request_body.py new file mode 100644 index 0000000..6d555e5 --- /dev/null +++ b/openshock/rest/models/set_user_email_request_body.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetUserEmailRequestBody") + + +@_attrs_define +class SetUserEmailRequestBody: + """ + Attributes: + email (str): + """ + + email: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + email = self.email + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "email": email, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + email = d.pop("email") + + set_user_email_request_body = cls( + email=email, + ) + + set_user_email_request_body.additional_properties = d + return set_user_email_request_body + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_user_name_request_body.py b/openshock/rest/models/set_user_name_request_body.py new file mode 100644 index 0000000..178e806 --- /dev/null +++ b/openshock/rest/models/set_user_name_request_body.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetUserNameRequestBody") + + +@_attrs_define +class SetUserNameRequestBody: + """ + Attributes: + name (str): + """ + + name: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name = self.name + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "name": name, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + name = d.pop("name") + + set_user_name_request_body = cls( + name=name, + ) + + set_user_name_request_body.additional_properties = d + return set_user_name_request_body + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/set_user_password_request_body.py b/openshock/rest/models/set_user_password_request_body.py new file mode 100644 index 0000000..2eba296 --- /dev/null +++ b/openshock/rest/models/set_user_password_request_body.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="SetUserPasswordRequestBody") + + +@_attrs_define +class SetUserPasswordRequestBody: + """ + Attributes: + password (str): + """ + + password: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + password = self.password + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "password": password, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + password = d.pop("password") + + set_user_password_request_body = cls( + password=password, + ) + + set_user_password_request_body.additional_properties = d + return set_user_password_request_body + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/token_created_response_v2.py b/openshock/rest/models/token_created_response_v2.py new file mode 100644 index 0000000..0ff2f4b --- /dev/null +++ b/openshock/rest/models/token_created_response_v2.py @@ -0,0 +1,171 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.permission_type import PermissionType + +if TYPE_CHECKING: + from ..models.shocker_control_settings import ShockerControlSettings + + +T = TypeVar("T", bound="TokenCreatedResponseV2") + + +@_attrs_define +class TokenCreatedResponseV2: + """ + Attributes: + id (UUID): + name (str): + token (str): + created_at (datetime.datetime): + valid_until (datetime.datetime | None): + last_used (datetime.datetime | None): + permissions (list[PermissionType]): + shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits + for intensity and duration. + """ + + id: UUID + name: str + token: str + created_at: datetime.datetime + valid_until: datetime.datetime | None + last_used: datetime.datetime | None + permissions: list[PermissionType] + shocker_control: ShockerControlSettings + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + token = self.token + + created_at = self.created_at.isoformat() + + valid_until: None | str + if isinstance(self.valid_until, datetime.datetime): + valid_until = self.valid_until.isoformat() + else: + valid_until = self.valid_until + + last_used: None | str + if isinstance(self.last_used, datetime.datetime): + last_used = self.last_used.isoformat() + else: + last_used = self.last_used + + permissions = [] + for permissions_item_data in self.permissions: + permissions_item = permissions_item_data.value + permissions.append(permissions_item) + + shocker_control = self.shocker_control.to_dict() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "token": token, + "createdAt": created_at, + "validUntil": valid_until, + "lastUsed": last_used, + "permissions": permissions, + "shockerControl": shocker_control, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 + + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + token = d.pop("token") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + def _parse_valid_until(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + valid_until_type_1 = datetime.datetime.fromisoformat(data) + + return valid_until_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + valid_until = _parse_valid_until(d.pop("validUntil")) + + def _parse_last_used(data: object) -> datetime.datetime | None: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + last_used_type_1 = datetime.datetime.fromisoformat(data) + + return last_used_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(datetime.datetime | None, data) + + last_used = _parse_last_used(d.pop("lastUsed")) + + permissions = [] + _permissions = d.pop("permissions") + for permissions_item_data in _permissions: + permissions_item = PermissionType(permissions_item_data) + + permissions.append(permissions_item) + + shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) + + token_created_response_v2 = cls( + id=id, + name=name, + token=token, + created_at=created_at, + valid_until=valid_until, + last_used=last_used, + permissions=permissions, + shocker_control=shocker_control, + ) + + token_created_response_v2.additional_properties = d + return token_created_response_v2 + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/token_paused_response.py b/openshock/rest/models/token_paused_response.py new file mode 100644 index 0000000..dbce49a --- /dev/null +++ b/openshock/rest/models/token_paused_response.py @@ -0,0 +1,62 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="TokenPausedResponse") + + +@_attrs_define +class TokenPausedResponse: + """ + Attributes: + paused (bool): The now-set paused state of the token. + """ + + paused: bool + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + paused = self.paused + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "paused": paused, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + paused = d.pop("paused") + + token_paused_response = cls( + paused=paused, + ) + + token_paused_response.additional_properties = d + return token_paused_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_name_blacklist_dto.py b/openshock/rest/models/user_name_blacklist_dto.py new file mode 100644 index 0000000..3f1a8e9 --- /dev/null +++ b/openshock/rest/models/user_name_blacklist_dto.py @@ -0,0 +1,90 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.match_type_enum import MatchTypeEnum + +T = TypeVar("T", bound="UserNameBlacklistDto") + + +@_attrs_define +class UserNameBlacklistDto: + """ + Attributes: + id (UUID): + value (str): + match_type (MatchTypeEnum): + created_at (datetime.datetime): + """ + + id: UUID + value: str + match_type: MatchTypeEnum + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + value = self.value + + match_type = self.match_type.value + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "value": value, + "matchType": match_type, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + value = d.pop("value") + + match_type = MatchTypeEnum(d.pop("matchType")) + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + user_name_blacklist_dto = cls( + id=id, + value=value, + match_type=match_type, + created_at=created_at, + ) + + user_name_blacklist_dto.additional_properties = d + return user_name_blacklist_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/user_patch_dto.py b/openshock/rest/models/user_patch_dto.py new file mode 100644 index 0000000..b4432b7 --- /dev/null +++ b/openshock/rest/models/user_patch_dto.py @@ -0,0 +1,94 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="UserPatchDto") + + +@_attrs_define +class UserPatchDto: + """ + Attributes: + name (None | str | Unset): + email (None | str | Unset): + """ + + name: None | str | Unset = UNSET + email: None | str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + name: None | str | Unset + if isinstance(self.name, Unset): + name = UNSET + else: + name = self.name + + email: None | str | Unset + if isinstance(self.email, Unset): + email = UNSET + else: + email = self.email + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update({}) + if name is not UNSET: + field_dict["name"] = name + if email is not UNSET: + field_dict["email"] = email + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + + def _parse_name(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + name = _parse_name(d.pop("name", UNSET)) + + def _parse_email(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + email = _parse_email(d.pop("email", UNSET)) + + user_patch_dto = cls( + name=name, + email=email, + ) + + user_patch_dto.additional_properties = d + return user_patch_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/webhook_dto.py b/openshock/rest/models/webhook_dto.py new file mode 100644 index 0000000..ba0eb10 --- /dev/null +++ b/openshock/rest/models/webhook_dto.py @@ -0,0 +1,88 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar +from uuid import UUID + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +T = TypeVar("T", bound="WebhookDto") + + +@_attrs_define +class WebhookDto: + """ + Attributes: + id (UUID): + name (str): + url (str): + created_at (datetime.datetime): + """ + + id: UUID + name: str + url: str + created_at: datetime.datetime + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = str(self.id) + + name = self.name + + url = self.url + + created_at = self.created_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "name": name, + "url": url, + "createdAt": created_at, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = UUID(d.pop("id")) + + name = d.pop("name") + + url = d.pop("url") + + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + webhook_dto = cls( + id=id, + name=name, + url=url, + created_at=created_at, + ) + + webhook_dto.additional_properties = d + return webhook_dto + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/scripts/generate.py b/scripts/generate.py index ab1dfdc..87820ff 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -33,58 +33,6 @@ DEFAULT_SPEC_URL = "https://api.openshock.app/openapi.json" JSON = "application/json" -METHODS = {"get", "put", "post", "delete", "patch", "head", "options", "trace", "query"} - -# The SDK authenticates with API tokens (or a hub's device token). Operations nobody can -# call that way are left out of the generated client. -EXCLUDED_TAGS = {"Admin"} -SESSION_ONLY = "UserSessionCookie" - - -def excluded(operation: dict[str, Any]) -> bool: - """True for admin operations and for those that only accept a browser login session.""" - if EXCLUDED_TAGS & set(operation.get("tags") or []): - return True - schemes = {name for requirement in operation.get("security") or [] for name in requirement} - return schemes == {SESSION_ONLY} - - -def references(node: Any) -> set[str]: - """Names of the component schemas referenced anywhere below ``node``.""" - found: set[str] = set() - if isinstance(node, dict): - ref = node.get("$ref") - if isinstance(ref, str) and ref.startswith("#/components/schemas/"): - found.add(ref.rsplit("/", 1)[1]) - for value in node.values(): - found |= references(value) - elif isinstance(node, list): - for value in node: - found |= references(value) - return found - - -def drop_excluded(spec: dict[str, Any]) -> None: - paths = spec.get("paths", {}) - for path, item in list(paths.items()): - for method in [m for m, op in item.items() if m in METHODS and isinstance(op, dict) and excluded(op)]: - del item[method] - if not METHODS & item.keys(): - del paths[path] - - # Drop the models only the removed operations used. - schemas = spec.get("components", {}).get("schemas", {}) - keep: set[str] = set() - pending = references(paths) - while pending: - name = pending.pop() - if name not in keep and name in schemas: - keep.add(name) - pending |= references(schemas[name]) - keep - for name in [n for n in schemas if n not in keep]: - del schemas[name] - - HEADER = "# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand.\n" @@ -95,8 +43,6 @@ def prepare(spec: dict[str, Any]) -> dict[str, Any]: if str(spec.get("openapi", "")).startswith("3.2"): spec["openapi"] = "3.1.0" - drop_excluded(spec) - # ASP.NET lists every JSON flavour it accepts (application/json, text/json, # application/*+json). The generator would emit one branch per flavour and send the # last one as Content-Type, so keep plain JSON wherever it is offered. diff --git a/tests/test_generated.py b/tests/test_generated.py index ed2f1b3..d960601 100644 --- a/tests/test_generated.py +++ b/tests/test_generated.py @@ -10,24 +10,10 @@ import openshock.rest.api ROOT = Path(__file__).resolve().parent.parent +SPEC = json.loads((ROOT / "openapi" / "openapi.json").read_text(encoding="utf-8")) METHODS = {"get", "put", "post", "delete", "patch", "head", "options", "trace"} -def load_generate(): - spec = importlib.util.spec_from_file_location("generate", ROOT / "scripts" / "generate.py") - assert spec and spec.loader - module = importlib.util.module_from_spec(spec) - sys.modules["generate"] = module - spec.loader.exec_module(module) - return module - - -generate = load_generate() -RAW = json.loads((ROOT / "openapi" / "openapi.json").read_text(encoding="utf-8")) -#: The document as the generator sees it: without admin and session-only operations. -SPEC = generate.prepare(json.loads(json.dumps(RAW))) - - def operation_modules(): for tag in pkgutil.iter_modules(openshock.rest.api.__path__): package = importlib.import_module(f"openshock.rest.api.{tag.name}") @@ -38,7 +24,7 @@ def operation_modules(): def test_every_operation_has_a_module_with_sync_and_async_variants(): operations = [op for item in SPEC["paths"].values() for method, op in item.items() if method in METHODS] modules = list(operation_modules()) - assert len(modules) == len(operations) > 50 + assert len(modules) == len(operations) > 100 for module in modules: # Operations without a response body only get the *_detailed pair. for variant in ("sync_detailed", "asyncio_detailed"): @@ -53,6 +39,12 @@ def test_every_schema_has_a_model(): def test_spec_preparation(): + spec = importlib.util.spec_from_file_location("generate", ROOT / "scripts" / "generate.py") + assert spec and spec.loader + generate = importlib.util.module_from_spec(spec) + sys.modules["generate"] = generate + spec.loader.exec_module(generate) + document = { "openapi": "3.2.0", "paths": { @@ -76,55 +68,3 @@ def test_spec_preparation(): assert post["requestBody"]["content"] == {"application/json": {"a": 1}} assert post["responses"]["200"]["content"] == {"application/json": {"b": 2}} assert post["responses"]["201"]["content"] == {"text/plain": {"c": 3}} - - -def test_admin_and_session_only_operations_are_not_generated(): - remaining = [op for item in SPEC["paths"].values() for method, op in item.items() if method in METHODS] - assert not any("Admin" in op.get("tags", []) for op in remaining) - assert not any(op.get("security") == [{"UserSessionCookie": []}] for op in remaining) - assert not any(path.startswith("/1/admin") for path in SPEC["paths"]) - # Everything an API token or a hub token can call is still there. - for path, item in RAW["paths"].items(): - for method, op in item.items(): - if method not in METHODS or "Admin" in op.get("tags", []): - continue - schemes = {name for requirement in op.get("security") or [] for name in requirement} - if schemes != {"UserSessionCookie"}: - assert method in SPEC["paths"][path], f"{method} {path}" - - import openshock.rest.api as api - - names = {module.name for module in pkgutil.iter_modules(api.__path__)} - assert "admin" not in names and "sessions" not in names - assert {"shockers", "hub_management", "hub_endpoints", "meta"} <= names - - -def test_excluding_operations_drops_their_models(): - document = { - "paths": { - "/keep": { - "get": { - "responses": { - "200": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/A"}}}} - } - } - }, - "/admin": { - "get": { - "tags": ["Admin"], - "responses": { - "200": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/C"}}}} - }, - } - }, - "/mixed": { - "get": {"security": [{"UserSessionCookie": []}], "responses": {}}, - "post": {"security": [{"ApiToken": []}, {"UserSessionCookie": []}], "responses": {}}, - }, - }, - "components": {"schemas": {"A": {"properties": {"b": {"$ref": "#/components/schemas/B"}}}, "B": {}, "C": {}}}, - } - generate.prepare(document) - assert set(document["paths"]) == {"/keep", "/mixed"} - assert set(document["paths"]["/mixed"]) == {"post"} - assert set(document["components"]["schemas"]) == {"A", "B"} From 059633fe163783b8188b3bec5008871c29b1fd3e Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 17:07:54 +0100 Subject: [PATCH 7/9] Regenerate SDK from openshock.dev OpenAPI --- openapi/openapi.json | 11651 ---------------- .../rest/api/account/account_activate.py | 165 - .../api/account/account_check_username.py | 159 - .../rest/api/account/account_email_verify.py | 170 - .../account/account_email_verify_legacy.py | 170 - .../rest/api/account/account_login_v2.py | 172 - openshock/rest/api/account/account_logout.py | 80 - .../account_password_reset_check_valid.py | 177 - .../account_password_reset_initiate_v2.py | 165 - .../api/account/account_resend_activation.py | 154 - .../rest/api/account/account_sign_up_v2.py | 174 - .../authenticated_account_change_password.py | 170 - .../authenticated_account_change_username.py | 175 - .../authenticated_account_deactivate.py | 133 - .../authenticated_account_get_audit_log.py | 226 - ...ticated_account_list_o_auth_connections.py | 134 - ...icated_account_remove_o_auth_connection.py | 158 - openshock/rest/api/admin/__init__.py | 2 - .../admin_add_email_provider_blacklist.py | 102 - .../api/admin/admin_add_username_blacklist.py | 102 - openshock/rest/api/admin/admin_add_webhook.py | 167 - .../admin/admin_bulk_cancel_email_outbox.py | 177 - .../admin/admin_bulk_delete_email_outbox.py | 173 - .../admin/admin_bulk_requeue_email_outbox.py | 177 - .../api/admin/admin_cancel_email_outbox.py | 172 - .../rest/api/admin/admin_configuration_add.py | 174 - .../api/admin/admin_configuration_delete.py | 169 - .../api/admin/admin_configuration_list.py | 138 - .../admin/admin_create_automation_token.py | 161 - .../rest/api/admin/admin_deactivate_user.py | 127 - .../rest/api/admin/admin_delete_api_token.py | 103 - .../admin/admin_delete_automation_token.py | 168 - .../api/admin/admin_delete_email_outbox.py | 167 - openshock/rest/api/admin/admin_delete_user.py | 118 - .../api/admin/admin_get_admin_audit_log.py | 263 - .../rest/api/admin/admin_get_email_outbox.py | 218 - .../api/admin/admin_get_email_outbox_stats.py | 133 - .../api/admin/admin_get_online_devices.py | 135 - .../api/admin/admin_get_online_gateways.py | 138 - .../rest/api/admin/admin_get_user_by_id.py | 167 - openshock/rest/api/admin/admin_get_users.py | 210 - .../api/admin/admin_list_automation_tokens.py | 134 - .../admin_list_email_provider_blacklist.py | 162 - .../admin/admin_list_username_blacklist.py | 162 - .../rest/api/admin/admin_list_webhooks.py | 138 - openshock/rest/api/admin/admin_modify_user.py | 121 - .../api/admin/admin_patch_automation_token.py | 184 - .../rest/api/admin/admin_reactivate_user.py | 118 - .../admin_remove_email_provider_blacklist.py | 155 - .../admin/admin_remove_username_blacklist.py | 155 - .../rest/api/admin/admin_remove_webhook.py | 163 - .../api/admin/admin_requeue_email_outbox.py | 172 - .../admin/admin_rotate_automation_token.py | 163 - .../rest/api/admin/admin_send_test_email.py | 191 - .../rest/api/admin/admin_set_user_email.py | 184 - .../rest/api/admin/admin_set_user_name.py | 192 - .../rest/api/admin/admin_set_user_password.py | 192 - .../api/api_tokens/tokens_create_token_v2.py | 161 - .../api/api_tokens/tokens_list_tokens_v2.py | 132 - .../api/api_tokens/tokens_report_tokens.py | 104 - .../devices_ota_get_ota_update_history.py | 165 - .../public_get_public_share.py | 20 +- .../public_get_public_share_by_slug.py} | 128 +- .../public_unlock_public_share.py} | 96 +- .../share_links_create_public_share.py | 31 +- .../share_links_edit_public_share.py} | 93 +- .../share_links_set_public_share_password.py} | 100 +- openshock/rest/api/sessions/__init__.py | 2 - .../api/sessions/sessions_delete_session.py | 157 - .../api/sessions/sessions_get_self_session.py | 127 - .../api/sessions/sessions_list_sessions.py | 130 - openshock/rest/api/shocker_shares/__init__.py | 2 - .../shares_delete_share_code.py | 163 - .../shocker_shares/shares_link_share_code.py | 172 - .../shocker_set_shocker_permissions.py} | 102 +- .../user_shares_redeem_invite.py | 5 + .../public_get_user_profile.py} | 71 +- openshock/rest/models/__init__.py | 222 +- .../add_email_provider_blacklist_dto.py | 62 - openshock/rest/models/add_webhook_dto.py | 70 - .../models/admin_online_device_response.py | 216 - .../models/admin_online_gateway_response.py | 146 - openshock/rest/models/admin_user_view.py | 324 - .../rest/models/admin_user_view_api_token.py | 156 - openshock/rest/models/admin_user_view_hub.py | 102 - .../rest/models/admin_user_view_shocker.py | 80 - ...admin_user_view_user_activation_request.py | 71 - .../admin_user_view_user_deactivation.py | 102 - .../rest/models/admin_user_view_user_ref.py | 71 - openshock/rest/models/admin_users_view.py | 304 - openshock/rest/models/audit_action.py | 26 - .../rest/models/audit_log_entry_response.py | 432 - ...t_metadata_account_deactivated_metadata.py | 81 - ...metadata_account_deactivated_metadata_t.py | 9 - ...dit_metadata_api_token_created_metadata.py | 98 - ...t_metadata_api_token_created_metadata_t.py | 9 - ...dit_metadata_api_token_deleted_metadata.py | 90 - ...t_metadata_api_token_deleted_metadata_t.py | 9 - ...adata_automation_token_created_metadata.py | 120 - ...ata_automation_token_created_metadata_t.py | 9 - ...adata_automation_token_deleted_metadata.py | 99 - ...ata_automation_token_deleted_metadata_t.py | 9 - ...adata_automation_token_rotated_metadata.py | 90 - ...ata_automation_token_rotated_metadata_t.py | 9 - ...adata_automation_token_updated_metadata.py | 121 - ...ata_automation_token_updated_metadata_t.py | 9 - ...metadata_automation_token_used_metadata.py | 100 - ...tadata_automation_token_used_metadata_t.py | 9 - ...etadata_email_change_requested_metadata.py | 81 - ...adata_email_change_requested_metadata_t.py | 9 - .../audit_metadata_email_changed_metadata.py | 89 - ...audit_metadata_email_changed_metadata_t.py | 9 - .../models/audit_metadata_login_metadata.py | 82 - .../models/audit_metadata_login_metadata_t.py | 9 - ...udit_metadata_o_auth_connected_metadata.py | 81 - ...it_metadata_o_auth_connected_metadata_t.py | 9 - ...t_metadata_o_auth_disconnected_metadata.py | 81 - ...metadata_o_auth_disconnected_metadata_t.py | 9 - ...udit_metadata_username_changed_metadata.py | 89 - ...it_metadata_username_changed_metadata_t.py | 9 - openshock/rest/models/automation_token_dto.py | 197 - .../rest/models/automation_token_type.py | 11 - openshock/rest/models/change_email_request.py | 70 - .../rest/models/change_password_request.py | 70 - .../rest/models/change_username_request.py | 62 - .../models/configuration_add_item_request.py | 91 - .../rest/models/configuration_item_dto.py | 106 - .../configuration_update_item_request.py | 110 - .../rest/models/configuration_value_type.py | 13 - .../models/create_automation_token_dto.py | 112 - .../rest/models/create_token_request_v2.py | 127 - .../models/created_automation_token_dto.py | 166 - .../rest/models/edit_token_request_v2.py | 95 - .../rest/models/email_outbox_bulk_request.py | 72 - .../models/email_outbox_bulk_result_dto.py | 72 - .../rest/models/email_outbox_message_dto.py | 226 - .../email_outbox_message_dto_payload.py | 46 - .../rest/models/email_outbox_stats_dto.py | 103 - .../models/email_provider_blacklist_dto.py | 80 - openshock/rest/models/email_status.py | 13 - openshock/rest/models/email_type.py | 12 - ...f_array_of_admin_online_device_response.py | 84 - ...ta_response_of_shocker_perm_limit_pair.py} | 30 +- .../rest/models/login_session_response.py | 203 - openshock/rest/models/login_v2.py | 78 - openshock/rest/models/login_v2_ok_response.py | 113 - openshock/rest/models/match_type_enum.py | 10 - .../rest/models/o_auth_connection_response.py | 93 - openshock/rest/models/ota_item.py | 103 - openshock/rest/models/ota_update_status.py | 13 - .../rest/models/own_public_share_response.py | 22 + ...aged_result_of_audit_log_entry_response.py | 112 - .../models/paginated_of_admin_users_view.py | 100 - .../paginated_of_email_outbox_message_dto.py | 100 - .../rest/models/password_hashing_algorithm.py | 11 - .../rest/models/password_reset_request_v2.py | 70 - .../rest/models/patch_automation_token_dto.py | 154 - ...email_change.py => public_share_author.py} | 73 +- openshock/rest/models/public_share_create.py | 41 + ...password_reset.py => public_share_edit.py} | 72 +- ...t_body.py => public_share_password_set.py} | 26 +- .../rest/models/public_share_response.py | 41 +- ...process_data.py => public_share_unlock.py} | 10 +- ...nge.py => public_share_unlock_response.py} | 44 +- .../models/public_user_profile_details.py | 105 + ...py => public_user_profile_public_share.py} | 43 +- .../models/public_user_profile_response.py | 107 + .../rest/models/report_tokens_request.py | 70 - openshock/rest/models/send_test_email_dto.py | 98 - .../rest/models/set_token_paused_request.py | 62 - .../models/set_user_email_request_body.py | 62 - .../rest/models/set_user_name_request_body.py | 62 - openshock/rest/models/shocker_limits.py | 3 +- openshock/rest/models/shocker_response.py | 26 +- openshock/rest/models/shocker_with_device.py | 26 +- openshock/rest/models/sign_up_v2.py | 86 - openshock/rest/models/social_platform.py | 22 + .../rest/models/token_created_response_v2.py | 171 - .../rest/models/token_paused_response.py | 62 - .../rest/models/user_name_blacklist_dto.py | 90 - openshock/rest/models/user_patch_dto.py | 94 - ...lacklist_dto.py => user_profile_social.py} | 30 +- .../rest/models/username_availability.py | 11 - .../rest/models/username_check_response.py | 103 - openshock/rest/models/username_error.py | 72 - openshock/rest/models/username_error_type.py | 14 - 186 files changed, 940 insertions(+), 30189 deletions(-) delete mode 100644 openapi/openapi.json delete mode 100644 openshock/rest/api/account/account_activate.py delete mode 100644 openshock/rest/api/account/account_check_username.py delete mode 100644 openshock/rest/api/account/account_email_verify.py delete mode 100644 openshock/rest/api/account/account_email_verify_legacy.py delete mode 100644 openshock/rest/api/account/account_login_v2.py delete mode 100644 openshock/rest/api/account/account_logout.py delete mode 100644 openshock/rest/api/account/account_password_reset_check_valid.py delete mode 100644 openshock/rest/api/account/account_password_reset_initiate_v2.py delete mode 100644 openshock/rest/api/account/account_resend_activation.py delete mode 100644 openshock/rest/api/account/account_sign_up_v2.py delete mode 100644 openshock/rest/api/account/authenticated_account_change_password.py delete mode 100644 openshock/rest/api/account/authenticated_account_change_username.py delete mode 100644 openshock/rest/api/account/authenticated_account_deactivate.py delete mode 100644 openshock/rest/api/account/authenticated_account_get_audit_log.py delete mode 100644 openshock/rest/api/account/authenticated_account_list_o_auth_connections.py delete mode 100644 openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py delete mode 100644 openshock/rest/api/admin/__init__.py delete mode 100644 openshock/rest/api/admin/admin_add_email_provider_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_add_username_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_add_webhook.py delete mode 100644 openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_bulk_delete_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_cancel_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_configuration_add.py delete mode 100644 openshock/rest/api/admin/admin_configuration_delete.py delete mode 100644 openshock/rest/api/admin/admin_configuration_list.py delete mode 100644 openshock/rest/api/admin/admin_create_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_deactivate_user.py delete mode 100644 openshock/rest/api/admin/admin_delete_api_token.py delete mode 100644 openshock/rest/api/admin/admin_delete_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_delete_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_delete_user.py delete mode 100644 openshock/rest/api/admin/admin_get_admin_audit_log.py delete mode 100644 openshock/rest/api/admin/admin_get_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_get_email_outbox_stats.py delete mode 100644 openshock/rest/api/admin/admin_get_online_devices.py delete mode 100644 openshock/rest/api/admin/admin_get_online_gateways.py delete mode 100644 openshock/rest/api/admin/admin_get_user_by_id.py delete mode 100644 openshock/rest/api/admin/admin_get_users.py delete mode 100644 openshock/rest/api/admin/admin_list_automation_tokens.py delete mode 100644 openshock/rest/api/admin/admin_list_email_provider_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_list_username_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_list_webhooks.py delete mode 100644 openshock/rest/api/admin/admin_modify_user.py delete mode 100644 openshock/rest/api/admin/admin_patch_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_reactivate_user.py delete mode 100644 openshock/rest/api/admin/admin_remove_email_provider_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_remove_username_blacklist.py delete mode 100644 openshock/rest/api/admin/admin_remove_webhook.py delete mode 100644 openshock/rest/api/admin/admin_requeue_email_outbox.py delete mode 100644 openshock/rest/api/admin/admin_rotate_automation_token.py delete mode 100644 openshock/rest/api/admin/admin_send_test_email.py delete mode 100644 openshock/rest/api/admin/admin_set_user_email.py delete mode 100644 openshock/rest/api/admin/admin_set_user_name.py delete mode 100644 openshock/rest/api/admin/admin_set_user_password.py delete mode 100644 openshock/rest/api/api_tokens/tokens_create_token_v2.py delete mode 100644 openshock/rest/api/api_tokens/tokens_list_tokens_v2.py delete mode 100644 openshock/rest/api/api_tokens/tokens_report_tokens.py delete mode 100644 openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py rename openshock/rest/api/{account/account_password_reset_complete.py => public_shocker_shares/public_get_public_share_by_slug.py} (50%) rename openshock/rest/api/{account/authenticated_account_change_email.py => public_shocker_shares/public_unlock_public_share.py} (59%) rename openshock/rest/api/{admin/admin_configuration_update.py => public_shocker_shares/share_links_edit_public_share.py} (60%) rename openshock/rest/api/{api_tokens/tokens_set_token_paused.py => public_shocker_shares/share_links_set_public_share_password.py} (55%) delete mode 100644 openshock/rest/api/sessions/__init__.py delete mode 100644 openshock/rest/api/sessions/sessions_delete_session.py delete mode 100644 openshock/rest/api/sessions/sessions_get_self_session.py delete mode 100644 openshock/rest/api/sessions/sessions_list_sessions.py delete mode 100644 openshock/rest/api/shocker_shares/__init__.py delete mode 100644 openshock/rest/api/shocker_shares/shares_delete_share_code.py delete mode 100644 openshock/rest/api/shocker_shares/shares_link_share_code.py rename openshock/rest/api/{api_tokens/tokens_edit_token_v2.py => shockers/shocker_set_shocker_permissions.py} (51%) rename openshock/rest/api/{api_tokens/tokens_get_token_by_id_v2.py => users/public_get_user_profile.py} (66%) delete mode 100644 openshock/rest/models/add_email_provider_blacklist_dto.py delete mode 100644 openshock/rest/models/add_webhook_dto.py delete mode 100644 openshock/rest/models/admin_online_device_response.py delete mode 100644 openshock/rest/models/admin_online_gateway_response.py delete mode 100644 openshock/rest/models/admin_user_view.py delete mode 100644 openshock/rest/models/admin_user_view_api_token.py delete mode 100644 openshock/rest/models/admin_user_view_hub.py delete mode 100644 openshock/rest/models/admin_user_view_shocker.py delete mode 100644 openshock/rest/models/admin_user_view_user_activation_request.py delete mode 100644 openshock/rest/models/admin_user_view_user_deactivation.py delete mode 100644 openshock/rest/models/admin_user_view_user_ref.py delete mode 100644 openshock/rest/models/admin_users_view.py delete mode 100644 openshock/rest/models/audit_action.py delete mode 100644 openshock/rest/models/audit_log_entry_response.py delete mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_created_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_email_changed_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_login_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_login_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py delete mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata.py delete mode 100644 openshock/rest/models/audit_metadata_username_changed_metadata_t.py delete mode 100644 openshock/rest/models/automation_token_dto.py delete mode 100644 openshock/rest/models/automation_token_type.py delete mode 100644 openshock/rest/models/change_email_request.py delete mode 100644 openshock/rest/models/change_password_request.py delete mode 100644 openshock/rest/models/change_username_request.py delete mode 100644 openshock/rest/models/configuration_add_item_request.py delete mode 100644 openshock/rest/models/configuration_item_dto.py delete mode 100644 openshock/rest/models/configuration_update_item_request.py delete mode 100644 openshock/rest/models/configuration_value_type.py delete mode 100644 openshock/rest/models/create_automation_token_dto.py delete mode 100644 openshock/rest/models/create_token_request_v2.py delete mode 100644 openshock/rest/models/created_automation_token_dto.py delete mode 100644 openshock/rest/models/edit_token_request_v2.py delete mode 100644 openshock/rest/models/email_outbox_bulk_request.py delete mode 100644 openshock/rest/models/email_outbox_bulk_result_dto.py delete mode 100644 openshock/rest/models/email_outbox_message_dto.py delete mode 100644 openshock/rest/models/email_outbox_message_dto_payload.py delete mode 100644 openshock/rest/models/email_outbox_stats_dto.py delete mode 100644 openshock/rest/models/email_provider_blacklist_dto.py delete mode 100644 openshock/rest/models/email_status.py delete mode 100644 openshock/rest/models/email_type.py delete mode 100644 openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py rename openshock/rest/models/{legacy_data_response_of_i_read_only_collection_of_ota_item.py => legacy_data_response_of_shocker_perm_limit_pair.py} (64%) delete mode 100644 openshock/rest/models/login_session_response.py delete mode 100644 openshock/rest/models/login_v2.py delete mode 100644 openshock/rest/models/login_v2_ok_response.py delete mode 100644 openshock/rest/models/match_type_enum.py delete mode 100644 openshock/rest/models/o_auth_connection_response.py delete mode 100644 openshock/rest/models/ota_item.py delete mode 100644 openshock/rest/models/ota_update_status.py delete mode 100644 openshock/rest/models/paged_result_of_audit_log_entry_response.py delete mode 100644 openshock/rest/models/paginated_of_admin_users_view.py delete mode 100644 openshock/rest/models/paginated_of_email_outbox_message_dto.py delete mode 100644 openshock/rest/models/password_hashing_algorithm.py delete mode 100644 openshock/rest/models/password_reset_request_v2.py delete mode 100644 openshock/rest/models/patch_automation_token_dto.py rename openshock/rest/models/{admin_user_view_email_change.py => public_share_author.py} (51%) rename openshock/rest/models/{admin_user_view_password_reset.py => public_share_edit.py} (54%) rename openshock/rest/models/{set_user_password_request_body.py => public_share_password_set.py} (66%) rename openshock/rest/models/{password_reset_process_data.py => public_share_unlock.py} (86%) rename openshock/rest/models/{admin_user_view_name_change.py => public_share_unlock_response.py} (59%) create mode 100644 openshock/rest/models/public_user_profile_details.py rename openshock/rest/models/{webhook_dto.py => public_user_profile_public_share.py} (62%) create mode 100644 openshock/rest/models/public_user_profile_response.py delete mode 100644 openshock/rest/models/report_tokens_request.py delete mode 100644 openshock/rest/models/send_test_email_dto.py delete mode 100644 openshock/rest/models/set_token_paused_request.py delete mode 100644 openshock/rest/models/set_user_email_request_body.py delete mode 100644 openshock/rest/models/set_user_name_request_body.py delete mode 100644 openshock/rest/models/sign_up_v2.py create mode 100644 openshock/rest/models/social_platform.py delete mode 100644 openshock/rest/models/token_created_response_v2.py delete mode 100644 openshock/rest/models/token_paused_response.py delete mode 100644 openshock/rest/models/user_name_blacklist_dto.py delete mode 100644 openshock/rest/models/user_patch_dto.py rename openshock/rest/models/{add_username_blacklist_dto.py => user_profile_social.py} (70%) delete mode 100644 openshock/rest/models/username_availability.py delete mode 100644 openshock/rest/models/username_check_response.py delete mode 100644 openshock/rest/models/username_error.py delete mode 100644 openshock/rest/models/username_error_type.py diff --git a/openapi/openapi.json b/openapi/openapi.json deleted file mode 100644 index 942d583..0000000 --- a/openapi/openapi.json +++ /dev/null @@ -1,11651 +0,0 @@ -{ - "openapi": "3.2.0", - "info": { - "title": "OpenShock.API", - "description": "Backend for the OpenShock solution, that enables controlling shock collars over the internet.", - "version": "1.0" - }, - "servers": [ - { - "url": "https://api.openshock.app" - }, - { - "url": "https://api.openshock.dev" - } - ], - "paths": { - "/1": { - "get": { - "tags": [ - "Meta" - ], - "summary": "Gets the version of the OpenShock backend.", - "operationId": "Version_GetBackendInfo", - "responses": { - "200": { - "description": "The version was successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfBackendInfoResponse" - } - } - } - } - } - } - }, - "/1/users/self": { - "get": { - "tags": [ - "Users" - ], - "summary": "Get the current user's information. Deprecated: use GET /1/account instead.", - "operationId": "Users_GetSelf", - "responses": { - "200": { - "description": "The user's information was successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfLegacyUserSelfResponse" - } - } - } - } - }, - "deprecated": true, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/users/self/control-stats": { - "get": { - "tags": [ - "Users" - ], - "summary": "Get control statistics for the current user, both for their own shockers and for controls they sent.", - "operationId": "Users_GetSelfControlStats", - "parameters": [ - { - "name": "tz", - "in": "query", - "description": "IANA time zone the daily breakdown and the date range are in, e.g. `Europe/Berlin`, defaults to UTC.", - "schema": { - "maxLength": 64, - "type": "string" - } - }, - { - "name": "from", - "in": "query", - "description": "First day to include (inclusive), defaults to all time.", - "schema": { - "type": "string", - "format": "date" - } - }, - { - "name": "to", - "in": "query", - "description": "Last day to include (inclusive), defaults to today.", - "schema": { - "type": "string", - "format": "date" - } - } - ], - "responses": { - "200": { - "description": "The statistics.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ControlStatsResponse" - } - } - } - }, - "400": { - "description": "Unknown time zone or invalid range.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/users/by-name/{username}": { - "get": { - "tags": [ - "Users" - ], - "operationId": "Users_GetByName", - "parameters": [ - { - "name": "username", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/BasicUserInfo" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/BasicUserInfo" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/BasicUserInfo" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/tokens/{tokenId}": { - "delete": { - "tags": [ - "API Tokens" - ], - "summary": "Revoke a token", - "operationId": "TokenDelete_DeleteToken", - "parameters": [ - { - "name": "tokenId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully deleted token" - }, - "403": { - "description": "Api Token is not allowed to delete other Api Tokens", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "404": { - "description": "The token does not exist, or you do not have access to it", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/tokens/self": { - "get": { - "tags": [ - "API Tokens" - ], - "summary": "Gets information about the current token used to access this endpoint", - "operationId": "TokensSelf_GetSelfTokenV2", - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/TokenResponseV2" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/TokenResponseV2" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/TokenResponseV2" - } - } - } - } - }, - "security": [ - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:ApiToken" - ] - } - }, - "/1/tokens/report": { - "post": { - "tags": [ - "API Tokens" - ], - "summary": "Endpoint to delete potentially compromised api tokens", - "operationId": "Tokens_ReportTokens", - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ReportTokensRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ReportTokensRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The tokens were deleted if found" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/2/tokens": { - "get": { - "tags": [ - "API Tokens" - ], - "summary": "List all tokens for the current user", - "operationId": "Tokens_ListTokensV2", - "responses": { - "200": { - "description": "All tokens for the current user", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/TokenResponseV2" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/TokenResponseV2" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/TokenResponseV2" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - }, - "post": { - "tags": [ - "API Tokens" - ], - "summary": "Create a new token", - "operationId": "Tokens_CreateTokenV2", - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateTokenRequestV2" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/CreateTokenRequestV2" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The created token", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TokenCreatedResponseV2" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/2/tokens/{tokenId}": { - "get": { - "tags": [ - "API Tokens" - ], - "summary": "Get a token by id", - "operationId": "Tokens_GetTokenByIdV2", - "parameters": [ - { - "name": "tokenId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "The token", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TokenResponseV2" - } - } - } - }, - "404": { - "description": "The token does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - }, - "patch": { - "tags": [ - "API Tokens" - ], - "summary": "Edit a token", - "operationId": "Tokens_EditTokenV2", - "parameters": [ - { - "name": "tokenId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EditTokenRequestV2" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/EditTokenRequestV2" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The edited token" - }, - "404": { - "description": "The token does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/2/tokens/{tokenId}/paused": { - "patch": { - "tags": [ - "API Tokens" - ], - "summary": "Set whether a token is paused. A paused token may not send shocker control messages.", - "operationId": "Tokens_SetTokenPaused", - "parameters": [ - { - "name": "tokenId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetTokenPausedRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/SetTokenPausedRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The now-set paused state of the token.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TokenPausedResponse" - } - } - } - }, - "404": { - "description": "The token does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/shockers/{shockerId}": { - "patch": { - "tags": [ - "Shockers" - ], - "summary": "Edit a shocker", - "operationId": "Shocker_EditShocker", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/NewShocker" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/NewShocker" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully updated shocker", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Shocker does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "get": { - "tags": [ - "Shockers" - ], - "summary": "Get information about a shocker.", - "operationId": "Shocker_GetShockerById", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "The shocker information was successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfShockerWithDevice" - } - } - } - }, - "404": { - "description": "The shocker does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "delete": { - "tags": [ - "Shockers" - ], - "summary": "Remove a shocker", - "operationId": "Shocker_RemoveShocker", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully deleted shocker", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Shocker does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/{shockerId}/logs": { - "get": { - "tags": [ - "Shockers" - ], - "summary": "Get the logs for a shocker", - "operationId": "Shocker_GetShockerLogs", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "offset", - "in": "query", - "description": "", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer", - "default": 0 - } - }, - { - "name": "limit", - "in": "query", - "description": "", - "schema": { - "maximum": 500, - "minimum": 1, - "type": "integer", - "default": 100 - } - } - ], - "responses": { - "200": { - "description": "The logs", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfLogEntry" - } - } - } - }, - "404": { - "description": "Shocker does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/logs": { - "get": { - "tags": [ - "Shockers" - ], - "summary": "Get a paged set of control logs across the caller's shockers.", - "operationId": "Shocker_GetAllShockerLogs", - "parameters": [ - { - "name": "page", - "in": "query", - "description": "1-based page index. Values below 1 are clamped to 1.", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - } - }, - { - "name": "pageSize", - "in": "query", - "description": "Number of items per page. Clamped to `[1, uint PaginationQuery.MaxPageSize]`.", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - } - }, - { - "name": "search", - "in": "query", - "description": "Optional free-text search term. Whitespace is trimmed; empty becomes null.\nEndpoints decide which fields the term is matched against.", - "schema": { - "type": "string" - } - }, - { - "name": "sort", - "in": "query", - "description": "Optional sort key. Endpoints register the allowed keys and translate them to\nthe underlying column(s). Unknown values fall back to the endpoint default.", - "schema": { - "type": "string" - } - }, - { - "name": "sortDir", - "in": "query", - "description": "Sort direction. Defaults to SortDirection.Desc when omitted, since list\nendpoints almost always want \"newest/highest first\" as the default.", - "schema": { - "$ref": "#/components/schemas/SortDirection" - } - }, - { - "name": "shockerIds", - "in": "query", - "description": "Optional shocker ID filter. When omitted or empty, logs for all of the caller's shockers are returned.", - "schema": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - } - } - ], - "responses": { - "200": { - "description": "A page of logs.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PagedResultOfLogEntryWithHub" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/shared": { - "get": { - "tags": [ - "Shockers" - ], - "summary": "List all shockers shared with the authenticated user.", - "operationId": "Shocker_ListSharedShockers", - "responses": { - "200": { - "description": "The shockers were successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfOwnerShockerResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/own": { - "get": { - "tags": [ - "Shockers" - ], - "summary": "List all shockers belonging to the authenticated user.", - "operationId": "Shocker_ListShockers", - "responses": { - "200": { - "description": "The shockers were successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfDeviceWithShockersResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/{shockerId}/pause": { - "post": { - "tags": [ - "Shockers" - ], - "summary": "Pause or unpause a shocker", - "operationId": "Shocker_PauseShocker", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PauseRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PauseRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully set pause state", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfboolean" - } - } - } - }, - "404": { - "description": "Shocker not found or does not belong to you", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers": { - "post": { - "tags": [ - "Shockers" - ], - "summary": "Register a shocker", - "operationId": "Shocker_RegisterShocker", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/NewShocker" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/NewShocker" - } - } - }, - "required": true - }, - "responses": { - "201": { - "description": "Successfully created shocker", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfGuid" - } - } - } - }, - "400": { - "description": "You can have a maximum of 11 Shockers per Device.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "404": { - "description": "Device does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shockers/control": { - "post": { - "tags": [ - "Shockers" - ], - "summary": "Send a control message to shockers", - "operationId": "Shocker_SendControl", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ControlRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ControlRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The control messages were successfully sent.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "412": { - "description": "Precondition Failed", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/{shockerId}/shares": { - "get": { - "tags": [ - "Shockers" - ], - "summary": "Get all user shares for a shocker", - "operationId": "Shocker_GetUserShares", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "Id of the shocker", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfShareInfo" - } - } - } - }, - "404": { - "description": "The shocker does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "post": { - "tags": [ - "Shockers" - ], - "summary": "Create a share code for a shocker", - "operationId": "Shocker_ShockerShareCodeCreate", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ShockerPermLimitPair" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ShockerPermLimitPair" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The share code was successfully created.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfGuid" - } - } - } - }, - "404": { - "description": "Shocker does not exists or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/{shockerId}/shareCodes": { - "get": { - "tags": [ - "Shockers" - ], - "summary": "List all share codes for a shocker", - "operationId": "Shocker_ShockerShareCodeList", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfShareCodeInfo" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/{shockerId}/shares/{sharedWithUserId}": { - "delete": { - "tags": [ - "Shockers" - ], - "summary": "Remove a share for a shocker", - "operationId": "Shocker_ShockerShareRemove", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "sharedWithUserId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully removed share code" - }, - "404": { - "description": "Share does not exists or device/shocker does not belong to you nor is shared with you", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "patch": { - "tags": [ - "Shockers" - ], - "summary": "Update a share for a shocker", - "operationId": "Shocker_ShockerShareCodeUpdate", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "sharedWithUserId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ShockerPermLimitPair" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ShockerPermLimitPair" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully updated share code" - }, - "404": { - "description": "The share code does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shockers/{shockerId}/shares/{sharedWithUserId}/pause": { - "post": { - "tags": [ - "Shockers" - ], - "summary": "Pause/Unpause a share code for a shocker", - "operationId": "Shocker_ShockerShareCodePause", - "parameters": [ - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "sharedWithUserId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PauseRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PauseRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully updated pause status share", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfboolean" - } - } - } - }, - "404": { - "description": "The share code does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shares/code/{shareCodeId}": { - "delete": { - "tags": [ - "Shocker Shares" - ], - "summary": "Delete a share code", - "operationId": "Shares_DeleteShareCode", - "parameters": [ - { - "name": "shareCodeId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Deleted share code", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Share code not found or does not belong to you", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - }, - "post": { - "tags": [ - "Shocker Shares" - ], - "summary": "Link a share code to your account", - "operationId": "Shares_LinkShareCode", - "parameters": [ - { - "name": "shareCodeId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Linked share code", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "400": { - "description": "You cannot link your own shocker code / You already have this shocker linked to your account", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "404": { - "description": "Share code not found or does not belong to you", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "500": { - "description": "Error while linking share code to your account" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/2/shares/user/invites": { - "post": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_CreateShareInvite", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateShareRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/CreateShareRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "string", - "format": "uuid" - } - } - } - }, - "400": { - "description": "Bad Request", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shares/user": { - "get": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_GetSharesByUsers", - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/V2UserShares" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/V2UserShares" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/V2UserShares" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shares/user/invites/outgoing": { - "get": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_GetOutgoingInvitesList", - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareInviteBaseDetails" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareInviteBaseDetails" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareInviteBaseDetails" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shares/user/invites/incoming": { - "get": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_GetIncomingInvitesList", - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareInviteBaseDetails" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareInviteBaseDetails" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareInviteBaseDetails" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shares/user/invites/outgoing/{inviteId}": { - "delete": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_DeleteOutgoingInvite", - "parameters": [ - { - "name": "inviteId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shares/user/invites/incoming/{inviteId}": { - "delete": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_DenyIncomingInvite", - "parameters": [ - { - "name": "inviteId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "post": { - "tags": [ - "User Shocker Shares" - ], - "summary": "Accept a share request and share the shockers with the current user.", - "operationId": "UserShares_RedeemInvite", - "parameters": [ - { - "name": "inviteId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/V2UserSharesListItem" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/V2UserSharesListItem" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/V2UserSharesListItem" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shares/user/{userId}/shockers/pause": { - "post": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_BulkPauseUserShareShockers", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PauseUserShareShockersRequest" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/PauseUserShareShockersRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PauseUserShareShockersRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/PauseUserShareShockersResponse" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/PauseUserShareShockersResponse" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/PauseUserShareShockersResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/shares/user/{userId}/shockers": { - "delete": { - "tags": [ - "User Shocker Shares" - ], - "operationId": "UserShares_BulkRemoveUserShareShockers", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "minItems": 1, - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - } - }, - "text/json": { - "schema": { - "minItems": 1, - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - } - }, - "application/*+json": { - "schema": { - "minItems": 1, - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/RemoveUserSharesResponse" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/RemoveUserSharesResponse" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/RemoveUserSharesResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "patch": { - "tags": [ - "User Shocker Shares" - ], - "summary": "Update user shares for a shocker", - "operationId": "UserShares_BulkUserShareShockersUpdate", - "parameters": [ - { - "name": "userId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/BulkUserShareShockersUpdateRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/BulkUserShareShockersUpdateRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully updated share code" - }, - "404": { - "description": "The share code does not exist or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shares/links/{publicShareId}/{shockerId}": { - "post": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Add a shocker to a public share", - "operationId": "ShareLinks_AddShocker", - "parameters": [ - { - "name": "publicShareId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully added shocker", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Public share or shocker does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "Shocker already exists in public share", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "patch": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Edit a shocker in a public share", - "operationId": "ShareLinks_EditShocker", - "parameters": [ - { - "name": "publicShareId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PublicShareEditShocker" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PublicShareEditShocker" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully updated shocker", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - }, - "404": { - "description": "Public share or shocker does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "400": { - "description": "Shocker does not exist in public share" - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "delete": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Remove a shocker from a public share", - "operationId": "ShareLinks_RemoveShocker", - "parameters": [ - { - "name": "publicShareId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully removed shocker", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Public share or shocker does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "400": { - "description": "Shocker does not exist in public share" - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shares/links": { - "post": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Create a new public share", - "operationId": "ShareLinks_CreatePublicShare", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PublicShareCreate" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PublicShareCreate" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The created public share", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfGuid" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "get": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Get all public shares for the current user", - "operationId": "ShareLinks_List", - "responses": { - "200": { - "description": "All public shares for the current user", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfOwnPublicShareResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shares/links/{publicShareId}": { - "delete": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Deletes a public share", - "operationId": "ShareLinks_DeletePublicShare", - "parameters": [ - { - "name": "publicShareId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Deleted public share", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Public share not found or does not belong to you", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/shares/links/{publicShareId}/{shockerId}/pause": { - "post": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Pause a shocker in a public share", - "operationId": "ShareLinks_PauseShocker", - "parameters": [ - { - "name": "publicShareId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "shockerId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PauseRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PauseRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully updated paused state shocker", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfPauseReason" - } - } - } - }, - "404": { - "description": "Public share or shocker does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "400": { - "description": "Shocker does not exist in public share" - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/sessions/{sessionId}": { - "delete": { - "tags": [ - "Sessions" - ], - "operationId": "Sessions_DeleteSession", - "parameters": [ - { - "name": "sessionId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/sessions": { - "get": { - "tags": [ - "Sessions" - ], - "operationId": "Sessions_ListSessions", - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/LoginSessionResponse" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/sessions/self": { - "get": { - "tags": [ - "Sessions" - ], - "summary": "Gets information about the current token used to access this endpoint", - "operationId": "Sessions_GetSelfSession", - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/LoginSessionResponse" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/LoginSessionResponse" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/LoginSessionResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/public/stats": { - "get": { - "tags": [ - "Meta" - ], - "summary": "Gets online devices statistics", - "operationId": "Public_GetOnlineDevicesStatistics", - "responses": { - "200": { - "description": "The statistics were successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfStatsResponse" - } - } - } - } - } - } - }, - "/1/public/shares/links/{publicShareId}": { - "get": { - "tags": [ - "Public Shocker Shares" - ], - "summary": "Gets information about a public share.", - "operationId": "Public_GetPublicShare", - "parameters": [ - { - "name": "publicShareId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "The public share information was successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfPublicShareResponse" - } - } - } - }, - "404": { - "description": "The public share does not exist.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/1/integrations/control-stats/changes": { - "post": { - "tags": [ - "Integrations" - ], - "summary": "Lets a service holding many users keep their lifetime control stats in sync with a single call per tick.\nReturns the lifetime totals of every requested user whose stats changed since the given cursor.", - "description": "Requires an automation token granting `ControlStatsRead`. \"Changed since\" is answered from when each\ncontrol log was written, so late writes are still picked up. The lookback is widened by\nTimeSpan IntegrationsController.ChangeOverlap, so a user can be reported again although nothing changed.", - "operationId": "Integrations_GetControlStatChanges", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ControlStatChangesRequest" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ControlStatChangesRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ControlStatChangesRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The changed users' totals and the cursor to pass next time.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ControlStatChangesResponse" - } - } - } - }, - "403": { - "description": "No automation token granting ControlStatsRead was presented.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/1/devices/{deviceId}/ota": { - "get": { - "tags": [ - "Hub Management" - ], - "summary": "Gets the OTA update history for a device", - "operationId": "DevicesOta_GetOtaUpdateHistory", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "description": "Id of the device", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfIReadOnlyCollectionOfOtaItem" - } - } - } - }, - "404": { - "description": "Could not find device or you do not have access to it", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/devices": { - "get": { - "tags": [ - "Hub Management" - ], - "summary": "Get all devices for the current user", - "operationId": "Devices_ListDevices", - "responses": { - "200": { - "description": "All devices for the current user", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfDeviceResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/devices/{deviceId}": { - "get": { - "tags": [ - "Hub Management" - ], - "summary": "Get a device by its id", - "operationId": "Devices_GetDeviceById", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "The device", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfDeviceWithTokenResponse" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "patch": { - "tags": [ - "Hub Management" - ], - "summary": "Edit a device", - "operationId": "Devices_EditDevice", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HubEditRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/HubEditRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successfully updated device" - }, - "404": { - "description": "Device does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "put": { - "tags": [ - "Hub Management" - ], - "summary": "Regenerate a device token", - "operationId": "Devices_RegenerateDeviceToken", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "description": "The id of the device to regenerate the token for", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully regenerated device token", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - }, - "404": { - "description": "Device does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "500": { - "description": "Failed to save regenerated token" - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - }, - "delete": { - "tags": [ - "Hub Management" - ], - "summary": "Remove a device from current user's account", - "operationId": "Devices_RemoveDevice", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "description": "The id of the device to delete", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully deleted device" - }, - "404": { - "description": "Device does not exist", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/devices": { - "post": { - "tags": [ - "Hub Management" - ], - "summary": "Create a new device for the current user", - "operationId": "Devices_CreateDeviceV2", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HubCreateRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/HubCreateRequest" - } - } - }, - "required": true - }, - "responses": { - "201": { - "description": "Successfully created device", - "content": { - "text/plain": { - "schema": { - "type": "string", - "format": "uuid" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/devices/{deviceId}/pair": { - "get": { - "tags": [ - "Hub Management" - ], - "summary": "Get a pair code for a device", - "operationId": "Devices_GetPairCode", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "description": "", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "The pair code", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfstring" - } - } - } - }, - "404": { - "description": "Device does not exist or does not belong to you", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/devices/{deviceId}/lcg": { - "get": { - "tags": [ - "Hub Management" - ], - "summary": "Gets the live control gateway a hub is connected to, including its public port and the full\nlive-control WebSocket path (honoring the gateway's configured path prefix).", - "operationId": "Devices_GetLiveControlGatewayInfoV2", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Successfully retrieved live control gateway info", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LcgResponseV2" - } - } - } - }, - "404": { - "description": "Device does not exist or is not online", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/devices/{deviceId}/shockers": { - "get": { - "tags": [ - "Hub Management" - ], - "summary": "Get all shockers for a device", - "operationId": "Devices_GetShockers", - "parameters": [ - { - "name": "deviceId", - "in": "path", - "description": "The device id", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "All shockers for the device", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfShockerResponse" - } - } - } - }, - "404": { - "description": "Device does not exists or you do not have access to it.", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/2/device/assignLCG": { - "get": { - "tags": [ - "Hub Endpoints" - ], - "summary": "Gets the best suited LCG node for the client", - "operationId": "Device_GetLiveControlGatewayV2", - "parameters": [ - { - "name": "version", - "in": "query", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "Successfully assigned LCG node", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LcgNodeResponseV2" - } - } - } - }, - "400": { - "description": "Bad Request", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "503": { - "description": "Unable to find suitable LCG node", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "HubToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:HubToken" - ] - } - }, - "/1/device/self": { - "get": { - "tags": [ - "Hub Endpoints" - ], - "summary": "Gets information about the authenticated device.", - "operationId": "Device_GetSelf", - "responses": { - "200": { - "description": "The device information was successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfDeviceSelfResponse" - } - } - } - } - }, - "security": [ - { - "HubToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:HubToken" - ] - } - }, - "/1/device/pair/{pairCode}": { - "get": { - "tags": [ - "Hub Endpoints" - ], - "summary": "Pair a device with a pair code.", - "operationId": "Device_Pair", - "parameters": [ - { - "name": "pairCode", - "in": "path", - "description": "The pair code to pair with.", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Successfully assigned LCG node", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfstring" - } - } - } - }, - "404": { - "description": "No such pair code exists", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "HubToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:HubToken" - ] - } - }, - "/1/admin/automationTokens": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Creates an automation token. The secret is only returned once, in this response", - "operationId": "Admin_CreateAutomationToken", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateAutomationTokenDto" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/CreateAutomationTokenDto" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/CreatedAutomationTokenDto" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreatedAutomationTokenDto" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/CreatedAutomationTokenDto" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "get": { - "tags": [ - "Admin" - ], - "summary": "Lists all automation tokens", - "operationId": "Admin_ListAutomationTokens", - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AutomationTokenDto" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AutomationTokenDto" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AutomationTokenDto" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/automationTokens/{id}": { - "delete": { - "tags": [ - "Admin" - ], - "summary": "Deletes an automation token together with every account it created. Refused while any of those\naccounts holds a privileged role", - "operationId": "Admin_DeleteAutomationToken", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not Found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "Conflict", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "patch": { - "tags": [ - "Admin" - ], - "summary": "Updates an automation token", - "operationId": "Admin_PatchAutomationToken", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PatchAutomationTokenDto" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PatchAutomationTokenDto" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/AutomationTokenDto" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/AutomationTokenDto" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/AutomationTokenDto" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/automationTokens/{id}/rotate": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Rotates the secret of an automation token. The new secret is only returned once, in this response", - "operationId": "Admin_RotateAutomationToken", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/CreatedAutomationTokenDto" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreatedAutomationTokenDto" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/CreatedAutomationTokenDto" - } - } - } - }, - "404": { - "description": "Not Found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/config": { - "get": { - "tags": [ - "Admin" - ], - "summary": "Gets all configuration items", - "operationId": "Admin_ConfigurationList", - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ConfigurationItemDto" - } - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "post": { - "tags": [ - "Admin" - ], - "summary": "Adds a new configuration", - "operationId": "Admin_ConfigurationAdd", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ConfigurationAddItemRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ConfigurationAddItemRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Configuration added" - }, - "400": { - "description": "Invalid name or value format", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "Already exists", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "put": { - "tags": [ - "Admin" - ], - "summary": "Updates an existing configuration", - "operationId": "Admin_ConfigurationUpdate", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ConfigurationUpdateItemRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ConfigurationUpdateItemRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Configuration updated (or nothing to do)" - }, - "400": { - "description": "Invalid name or value format or type mismatch", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "404": { - "description": "Not found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "Conflict", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/config/{name}": { - "delete": { - "tags": [ - "Admin" - ], - "summary": "Deletes a configuration", - "operationId": "Admin_ConfigurationDelete", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Configuration deleted" - }, - "400": { - "description": "Invalid name format", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "404": { - "description": "Not found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/users/{userId}/deactivate": { - "put": { - "tags": [ - "Admin" - ], - "summary": "Deactivates a user", - "operationId": "Admin_DeactivateUser", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "deleteLater", - "in": "query", - "schema": { - "type": "boolean" - } - }, - { - "name": "reason", - "in": "query", - "schema": { - "maxLength": 512, - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/apitokens/{tokenId}": { - "delete": { - "tags": [ - "Admin" - ], - "summary": "Deletes an API token", - "operationId": "Admin_DeleteApiToken", - "parameters": [ - { - "name": "tokenId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/users/{userId}": { - "delete": { - "tags": [ - "Admin" - ], - "summary": "Deletes a user", - "operationId": "Admin_DeleteUser", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "reason", - "in": "query", - "schema": { - "maxLength": 512, - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "get": { - "tags": [ - "Admin" - ], - "summary": "Gets a user by id", - "operationId": "Admin_GetUserById", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "User info", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AdminUserView" - } - } - } - }, - "404": { - "description": "Not found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "patch": { - "tags": [ - "Admin" - ], - "summary": "Edits a user", - "operationId": "Admin_ModifyUser", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UserPatchDto" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/UserPatchDto" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not found" - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox/bulk/requeue": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Requeues many email outbox messages at once. Each id is treated exactly like the single-message\nrequeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing\nids are skipped. Returns how many rows were actually requeued.", - "operationId": "Admin_BulkRequeueEmailOutbox", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Bulk requeue applied", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkResultDto" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox/bulk/cancel": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are\nnot pending (already sending or terminal) and missing ids are skipped. Returns how many rows were\nactually cancelled.", - "operationId": "Admin_BulkCancelEmailOutbox", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Bulk cancel applied", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkResultDto" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox/bulk/delete": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many\nrows were actually deleted.", - "operationId": "Admin_BulkDeleteEmailOutbox", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Bulk delete applied", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxBulkResultDto" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox/{id}/cancel": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only\npending messages can be cancelled; a message already being sent or in a terminal state cannot.", - "operationId": "Admin_CancelEmailOutbox", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Cancelled" - }, - "404": { - "description": "No such message", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "Message is not pending", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox/{id}": { - "delete": { - "tags": [ - "Admin" - ], - "summary": "Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds\nthe row gone and does nothing, so a delete never corrupts an in-flight send.", - "operationId": "Admin_DeleteEmailOutbox", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Deleted" - }, - "404": { - "description": "No such message", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox": { - "get": { - "tags": [ - "Admin" - ], - "summary": "Lists email outbox messages, paginated. Supports the same OData-style\n`$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`,\n`recipient ilike '%@example.com'`). Defaults to newest first.", - "operationId": "Admin_GetEmailOutbox", - "parameters": [ - { - "name": "$filter", - "in": "query", - "schema": { - "type": "string", - "default": "" - } - }, - { - "name": "$orderby", - "in": "query", - "schema": { - "type": "string", - "default": "" - } - }, - { - "name": "$offset", - "in": "query", - "schema": { - "maximum": 2147483647, - "minimum": 0, - "type": "integer", - "format": "int32", - "default": 0 - } - }, - { - "name": "$limit", - "in": "query", - "schema": { - "maximum": 1000, - "minimum": 1, - "type": "integer", - "format": "int32", - "default": 100 - } - } - ], - "responses": { - "200": { - "description": "Paginated email outbox messages", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaginatedOfEmailOutboxMessageDto" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox/{id}/requeue": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now,\nwith a fresh attempt budget, and nudges the delivery consumer to send it immediately.", - "operationId": "Admin_RequeueEmailOutbox", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "Requeued" - }, - "404": { - "description": "No such message", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "Message is pending or currently being sent", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/outbox/stats": { - "get": { - "tags": [ - "Admin" - ], - "summary": "Returns the number of email outbox messages in each delivery state.", - "operationId": "Admin_GetEmailOutboxStats", - "responses": { - "200": { - "description": "Per-status counts", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxStatsDto" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/email/test": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Enqueues a preview/test email of the chosen type to the chosen address. It flows through the\nnormal durable delivery pipeline - visible in the outbox listing - but is rendered with\nplaceholder data and a dummy link, so it touches no request row and mints no token.", - "operationId": "Admin_SendTestEmail", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SendTestEmailDto" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/SendTestEmailDto" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Test email enqueued", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmailOutboxMessageDto" - } - } - } - }, - "400": { - "description": "Invalid recipient address", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/blacklist/emailProviders": { - "post": { - "tags": [ - "Admin" - ], - "operationId": "Admin_AddEmailProviderBlacklist", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AddEmailProviderBlacklistDto" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/AddEmailProviderBlacklistDto" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "get": { - "tags": [ - "Admin" - ], - "operationId": "Admin_ListEmailProviderBlacklist", - "parameters": [ - { - "name": "match", - "in": "query", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/EmailProviderBlacklistDto" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/EmailProviderBlacklistDto" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/EmailProviderBlacklistDto" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/blacklist/emailProviders/{id}": { - "delete": { - "tags": [ - "Admin" - ], - "operationId": "Admin_RemoveEmailProviderBlacklist", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not Found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/audit-log": { - "get": { - "tags": [ - "Admin" - ], - "summary": "Get audit log entries across all users. Optionally filter by subject user or actor.", - "operationId": "Admin_GetAdminAuditLog", - "parameters": [ - { - "name": "page", - "in": "query", - "description": "1-based page index. Values below 1 are clamped to 1.", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - } - }, - { - "name": "pageSize", - "in": "query", - "description": "Number of items per page. Clamped to `[1, uint PaginationQuery.MaxPageSize]`.", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - } - }, - { - "name": "search", - "in": "query", - "description": "Optional free-text search term. Whitespace is trimmed; empty becomes null.\nEndpoints decide which fields the term is matched against.", - "schema": { - "type": "string" - } - }, - { - "name": "sort", - "in": "query", - "description": "Optional sort key. Endpoints register the allowed keys and translate them to\nthe underlying column(s). Unknown values fall back to the endpoint default.", - "schema": { - "type": "string" - } - }, - { - "name": "sortDir", - "in": "query", - "description": "Sort direction. Defaults to SortDirection.Desc when omitted, since list\nendpoints almost always want \"newest/highest first\" as the default.", - "schema": { - "$ref": "#/components/schemas/SortDirection" - } - }, - { - "name": "userId", - "in": "query", - "description": "Optional: filter by the subject user (the account that was affected).", - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "actorId", - "in": "query", - "description": "Optional: filter by the actor (who performed the action).", - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "A page of audit log entries.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PagedResultOfAuditLogEntryResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/monitoring/onlineDevices": { - "get": { - "tags": [ - "Admin" - ], - "summary": "Gets all online devices", - "operationId": "Admin_GetOnlineDevices", - "responses": { - "200": { - "description": "All online devices", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/monitoring/gateways": { - "get": { - "tags": [ - "Admin" - ], - "summary": "Gets all online gateways", - "operationId": "Admin_GetOnlineGateways", - "responses": { - "200": { - "description": "All online gateways", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminOnlineGatewayResponse" - } - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/users": { - "get": { - "tags": [ - "Admin" - ], - "summary": "Gets all users, paginated", - "operationId": "Admin_GetUsers", - "parameters": [ - { - "name": "$filter", - "in": "query", - "schema": { - "type": "string", - "default": "" - } - }, - { - "name": "$orderby", - "in": "query", - "schema": { - "type": "string", - "default": "" - } - }, - { - "name": "$offset", - "in": "query", - "schema": { - "maximum": 2147483647, - "minimum": 0, - "type": "integer", - "format": "int32", - "default": 0 - } - }, - { - "name": "$limit", - "in": "query", - "schema": { - "maximum": 1000, - "minimum": 1, - "type": "integer", - "format": "int32", - "default": 100 - } - } - ], - "responses": { - "200": { - "description": "Paginated users", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PaginatedOfAdminUsersView" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/users/{userId}/reactivate": { - "put": { - "tags": [ - "Admin" - ], - "summary": "Reactivates a user", - "operationId": "Admin_ReactivateUser", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "reason", - "in": "query", - "schema": { - "maxLength": 512, - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/users/{userId}/email": { - "put": { - "tags": [ - "Admin" - ], - "summary": "Sets a users email to the supplied value", - "operationId": "Admin_SetUserEmail", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetUserEmailRequestBody" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/SetUserEmailRequestBody" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/SetUserEmailRequestBody" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/users/{userId}/name": { - "put": { - "tags": [ - "Admin" - ], - "summary": "Sets a users name to the supplied value", - "operationId": "Admin_SetUserName", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetUserNameRequestBody" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/SetUserNameRequestBody" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/SetUserNameRequestBody" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "The target account is deactivated or not yet activated", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/users/{userId}/password": { - "put": { - "tags": [ - "Admin" - ], - "summary": "Sets a users password to the supplied value", - "operationId": "Admin_SetUserPassword", - "parameters": [ - { - "name": "userId", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetUserPasswordRequestBody" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/SetUserPasswordRequestBody" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/SetUserPasswordRequestBody" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "The target account is deactivated or not yet activated", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/blacklist/usernames": { - "post": { - "tags": [ - "Admin" - ], - "operationId": "Admin_AddUsernameBlacklist", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AddUsernameBlacklistDto" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/AddUsernameBlacklistDto" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "get": { - "tags": [ - "Admin" - ], - "operationId": "Admin_ListUsernameBlacklist", - "parameters": [ - { - "name": "match", - "in": "query", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/UserNameBlacklistDto" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/UserNameBlacklistDto" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/UserNameBlacklistDto" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/blacklist/usernames/{id}": { - "delete": { - "tags": [ - "Admin" - ], - "operationId": "Admin_RemoveUsernameBlacklist", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not Found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/webhooks": { - "post": { - "tags": [ - "Admin" - ], - "summary": "Creates a webhook", - "operationId": "Admin_AddWebhook", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AddWebhookDto" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/AddWebhookDto" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "400": { - "description": "Bad Request", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - }, - "get": { - "tags": [ - "Admin" - ], - "summary": "List webhooks", - "operationId": "Admin_ListWebhooks", - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/WebhookDto" - } - } - }, - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/WebhookDto" - } - } - }, - "text/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/WebhookDto" - } - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/admin/webhooks/{id}": { - "delete": { - "tags": [ - "Admin" - ], - "summary": "Removes a webhook", - "operationId": "Admin_RemoveWebhook", - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "404": { - "description": "Not Found", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "401": { - "description": "Unauthorized" - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie", - "Roles:Admin" - ] - } - }, - "/1/account/activate": { - "post": { - "tags": [ - "Account" - ], - "summary": "Activate account", - "operationId": "Account_Activate", - "parameters": [ - { - "name": "token", - "in": "query", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "OK" - }, - "400": { - "description": "Bad Request", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/1/account/username/check": { - "post": { - "tags": [ - "Account" - ], - "summary": "Check if a username is available", - "operationId": "Account_CheckUsername", - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ChangeUsernameRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ChangeUsernameRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/UsernameCheckResponse" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/UsernameCheckResponse" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/UsernameCheckResponse" - } - } - } - } - } - } - }, - "/2/account/login": { - "post": { - "tags": [ - "Account" - ], - "summary": "Authenticate a user", - "operationId": "Account_LoginV2", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LoginV2" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/LoginV2" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "User successfully logged in", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LoginV2OkResponse" - } - } - } - }, - "401": { - "description": "Invalid username or password", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/1/account/logout": { - "post": { - "tags": [ - "Account" - ], - "operationId": "Account_Logout", - "responses": { - "200": { - "description": "OK" - } - } - } - }, - "/1/account/password-reset/{passwordResetId}/{secret}": { - "get": { - "tags": [ - "Account" - ], - "summary": "Check if a password reset is in progress", - "operationId": "Account_PasswordResetCheckValid", - "parameters": [ - { - "name": "passwordResetId", - "in": "path", - "description": "The id of the password reset", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "secret", - "in": "path", - "description": "The secret of the password reset", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Valid password reset process", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Password reset process not found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/1/account/password-reset/{passwordResetId}/{secret}/complete": { - "post": { - "tags": [ - "Account" - ], - "summary": "Complete a password reset process", - "operationId": "Account_PasswordResetComplete", - "parameters": [ - { - "name": "passwordResetId", - "in": "path", - "description": "The id of the password reset", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "secret", - "in": "path", - "description": "The secret of the password reset", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PasswordResetProcessData" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PasswordResetProcessData" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Password successfully changed", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/LegacyEmptyResponse" - } - } - } - }, - "404": { - "description": "Password reset process not found", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/2/account/password-reset": { - "post": { - "tags": [ - "Account" - ], - "summary": "Initiate a password reset", - "operationId": "Account_PasswordResetInitiateV2", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PasswordResetRequestV2" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/PasswordResetRequestV2" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Password reset email sent if the email is associated to an registered account" - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/1/account/activate/resend": { - "post": { - "tags": [ - "Account" - ], - "summary": "Resend the account activation email for the account this browser just signed up", - "description": "Identifies the account by the activation-resend cookie set on signup, not by an email address,\nso it can only target an account created from this browser and can't be used to probe registered emails.", - "operationId": "Account_ResendActivation", - "responses": { - "200": { - "description": "Activation email enqueued" - }, - "400": { - "description": "No pending activation for this browser (missing/expired cookie, or already activated)", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "429": { - "description": "An activation email was sent too recently", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/2/account/signup": { - "post": { - "tags": [ - "Account" - ], - "summary": "Signs up a new user", - "operationId": "Account_SignUpV2", - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SignUpV2" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/SignUpV2" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "User successfully signed up" - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "Conflict", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "400": { - "description": "Username or email already exists" - } - } - } - }, - "/1/account/email-change/verify": { - "post": { - "tags": [ - "Account" - ], - "summary": "Verify a pending email change using the token from the verification email.", - "operationId": "Account_EmailVerify", - "parameters": [ - { - "name": "token", - "in": "query", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Email change verified and applied" - }, - "400": { - "description": "Token is invalid, already used, or the request has expired", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "The new email address was claimed by another account before verification completed", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - } - } - }, - "/1/account/verify-email": { - "post": { - "tags": [ - "Account" - ], - "summary": "Verify a pending email change. Deprecated: use POST /email-change/verify instead.", - "operationId": "Account_EmailVerifyLegacy", - "parameters": [ - { - "name": "token", - "in": "query", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Email change verified and applied" - }, - "400": { - "description": "Token is invalid, already used, or the request has expired", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "The new email address was claimed by another account before verification completed", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "deprecated": true - } - }, - "/1/account/email-change": { - "post": { - "tags": [ - "Account" - ], - "summary": "Initiate an email change for the current user. A verification link is sent to the new\naddress; the change is not applied until that link is opened.", - "operationId": "AuthenticatedAccount_ChangeEmail", - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ChangeEmailRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ChangeEmailRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "400": { - "description": "Bad Request", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "401": { - "description": "Unauthorized", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "Conflict", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "429": { - "description": "Too Many Requests", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/account/password": { - "post": { - "tags": [ - "Account" - ], - "summary": "Change the password of the current user", - "operationId": "AuthenticatedAccount_ChangePassword", - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ChangePasswordRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ChangePasswordRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "Conflict", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/account/username": { - "post": { - "tags": [ - "Account" - ], - "summary": "Change the username of the current user", - "operationId": "AuthenticatedAccount_ChangeUsername", - "requestBody": { - "description": "", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ChangeUsernameRequest" - } - }, - "application/*+json": { - "schema": { - "$ref": "#/components/schemas/ChangeUsernameRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "OK" - }, - "400": { - "description": "Bad Request", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - }, - "409": { - "description": "Conflict", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/account": { - "delete": { - "tags": [ - "Account" - ], - "summary": "Deactivate currently logged in account", - "operationId": "AuthenticatedAccount_Deactivate", - "responses": { - "204": { - "description": "Done." - }, - "403": { - "description": "Forbidden", - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/OpenShockProblem" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - }, - "get": { - "tags": [ - "Account" - ], - "summary": "Get the current user's account information.", - "operationId": "AuthenticatedAccount_GetSelf", - "responses": { - "200": { - "description": "The account information was successfully retrieved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UserSelfResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - }, - { - "ApiToken": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie,ApiToken" - ] - } - }, - "/1/account/audit-log": { - "get": { - "tags": [ - "Account" - ], - "summary": "Get the audit log for the current user's account.", - "operationId": "AuthenticatedAccount_GetAuditLog", - "parameters": [ - { - "name": "page", - "in": "query", - "description": "1-based page index. Values below 1 are clamped to 1.", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - } - }, - { - "name": "pageSize", - "in": "query", - "description": "Number of items per page. Clamped to `[1, uint PaginationQuery.MaxPageSize]`.", - "schema": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - } - }, - { - "name": "search", - "in": "query", - "description": "Optional free-text search term. Whitespace is trimmed; empty becomes null.\nEndpoints decide which fields the term is matched against.", - "schema": { - "type": "string" - } - }, - { - "name": "sort", - "in": "query", - "description": "Optional sort key. Endpoints register the allowed keys and translate them to\nthe underlying column(s). Unknown values fall back to the endpoint default.", - "schema": { - "type": "string" - } - }, - { - "name": "sortDir", - "in": "query", - "description": "Sort direction. Defaults to SortDirection.Desc when omitted, since list\nendpoints almost always want \"newest/highest first\" as the default.", - "schema": { - "$ref": "#/components/schemas/SortDirection" - } - } - ], - "responses": { - "200": { - "description": "A page of audit log entries.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PagedResultOfAuditLogEntryResponse" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/account/connections/{provider}": { - "delete": { - "tags": [ - "Account" - ], - "summary": "Remove an existing OAuth connection for the current user.", - "operationId": "AuthenticatedAccount_RemoveOAuthConnection", - "parameters": [ - { - "name": "provider", - "in": "path", - "description": "Provider key (e.g. `discord`).", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "204": { - "description": "Connection removed." - }, - "404": { - "description": "No connection found for this provider.", - "content": { - "text/plain": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "application/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - }, - "text/json": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - }, - "/1/account/connections": { - "get": { - "tags": [ - "Account" - ], - "summary": "List OAuth connections linked to the current user.", - "operationId": "AuthenticatedAccount_ListOAuthConnections", - "responses": { - "200": { - "description": "Returns the list of connections.", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/OAuthConnectionResponse" - } - } - } - } - } - }, - "security": [ - { - "UserSessionCookie": [] - } - ], - "x-authorization": [ - "AuthenticationSchemes:UserSessionCookie" - ] - } - } - }, - "components": { - "schemas": { - "AddEmailProviderBlacklistDto": { - "required": [ - "domains" - ], - "type": "object", - "properties": { - "domains": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "AddUsernameBlacklistDto": { - "required": [ - "value", - "matchType" - ], - "type": "object", - "properties": { - "value": { - "type": "string" - }, - "matchType": { - "$ref": "#/components/schemas/MatchTypeEnum" - } - } - }, - "AddWebhookDto": { - "required": [ - "name", - "url" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 0, - "type": "string" - }, - "url": { - "type": "string", - "format": "uri" - } - } - }, - "AdminOnlineDeviceResponse": { - "required": [ - "id", - "name", - "owner", - "firmwareVersion", - "gateway", - "connectedAt", - "userAgent", - "bootedAt", - "latencyMs", - "rssi", - "country", - "ip", - "asn", - "asnOrg" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "owner": { - "$ref": "#/components/schemas/BasicUserInfo" - }, - "firmwareVersion": { - "examples": [ - "1.0.0-dev+a16f2" - ], - "title": "SemVer", - "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$", - "type": "string" - }, - "gateway": { - "type": "string" - }, - "connectedAt": { - "type": "string", - "format": "date-time" - }, - "userAgent": { - "type": [ - "null", - "string" - ] - }, - "bootedAt": { - "type": "string", - "format": "date-time" - }, - "latencyMs": { - "maximum": 65535, - "minimum": 0, - "type": [ - "null", - "integer" - ], - "format": "int32" - }, - "rssi": { - "type": [ - "null", - "integer" - ], - "format": "int32" - }, - "country": { - "type": [ - "null", - "string" - ] - }, - "ip": { - "examples": [ - "127.0.0.1" - ], - "title": "IpAddress", - "type": [ - "null", - "string" - ], - "description": "An IPv4 or IPv6 address in its textual form." - }, - "asn": { - "type": [ - "null", - "integer" - ], - "format": "int64" - }, - "asnOrg": { - "type": [ - "null", - "string" - ] - } - } - }, - "AdminOnlineGatewayResponse": { - "required": [ - "id", - "host", - "port", - "pathPrefix", - "country", - "latitude", - "longitude", - "load", - "environment", - "connectedHubs" - ], - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "host": { - "type": "string" - }, - "port": { - "maximum": 65535, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "pathPrefix": { - "type": "string" - }, - "country": { - "type": "string" - }, - "latitude": { - "type": [ - "null", - "number" - ], - "format": "double" - }, - "longitude": { - "type": [ - "null", - "number" - ], - "format": "double" - }, - "load": { - "maximum": 255, - "minimum": 0, - "type": "integer", - "description": "Load the gateway advertises for hub assignment, in percent", - "format": "int32" - }, - "environment": { - "type": "string" - }, - "connectedHubs": { - "type": "integer", - "format": "int32" - } - } - }, - "AdminUserView": { - "required": [ - "id", - "name", - "email", - "passwordHashType", - "roles", - "createdAt", - "activatedAt", - "createdByAutomationTokenId", - "activationRequest", - "deactivation", - "hubs", - "apiTokens", - "usersNameChanges", - "usersEmailChanges", - "passwordResets", - "shockerControlLogsCount" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "email": { - "type": "string" - }, - "passwordHashType": { - "$ref": "#/components/schemas/PasswordHashingAlgorithm" - }, - "roles": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RoleType" - } - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "activatedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "createdByAutomationTokenId": { - "type": [ - "null", - "string" - ], - "format": "uuid" - }, - "activationRequest": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/AdminUserView_UserActivationRequest" - } - ] - }, - "deactivation": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/AdminUserView_UserDeactivation" - } - ] - }, - "hubs": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserView_Hub" - } - }, - "apiTokens": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserView_ApiToken" - } - }, - "usersNameChanges": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserView_NameChange" - } - }, - "usersEmailChanges": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserView_EmailChange" - } - }, - "passwordResets": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserView_PasswordReset" - } - }, - "shockerControlLogsCount": { - "type": "integer", - "format": "int32" - } - } - }, - "AdminUserView_ApiToken": { - "required": [ - "id", - "name", - "permissions", - "validUntil", - "lastUsed", - "createdAt", - "createdByIp" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "permissions": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PermissionType" - } - }, - "validUntil": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "lastUsed": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "createdByIp": { - "examples": [ - "127.0.0.1" - ], - "title": "IpAddress", - "type": "string", - "description": "An IPv4 or IPv6 address in its textual form." - } - } - }, - "AdminUserView_EmailChange": { - "required": [ - "id", - "email", - "createdAt", - "usedAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "email": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "usedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - } - } - }, - "AdminUserView_Hub": { - "required": [ - "id", - "name", - "createdAt", - "shockers" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "shockers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserView_Shocker" - } - } - } - }, - "AdminUserView_NameChange": { - "required": [ - "id", - "oldName", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int32" - }, - "oldName": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - }, - "AdminUserView_PasswordReset": { - "required": [ - "id", - "createdAt", - "usedAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "usedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - } - } - }, - "AdminUserView_Shocker": { - "required": [ - "id", - "name", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - }, - "AdminUserView_UserActivationRequest": { - "required": [ - "emailSendAttempts", - "createdAt" - ], - "type": "object", - "properties": { - "emailSendAttempts": { - "type": "integer", - "format": "int32" - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - }, - "AdminUserView_UserDeactivation": { - "required": [ - "deactivatedBy", - "scheduledDeletionTime", - "deactivatedAt" - ], - "type": "object", - "properties": { - "deactivatedBy": { - "$ref": "#/components/schemas/AdminUserView_UserRef" - }, - "scheduledDeletionTime": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "deactivatedAt": { - "type": "string", - "format": "date-time" - } - } - }, - "AdminUserView_UserRef": { - "required": [ - "id", - "name" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - } - } - }, - "AdminUsersView": { - "required": [ - "id", - "name", - "email", - "passwordHashType", - "roles", - "createdAt", - "activatedAt", - "createdByAutomationTokenId", - "deactivatedAt", - "deactivatedByUserId", - "apiTokenCount", - "passwordResetCount", - "shockerUserShareCount", - "shockerPublicShareCount", - "emailChangeRequestCount", - "nameChangeRequestCount", - "deviceCount", - "shockerCount", - "shockerControlLogCount" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "email": { - "type": "string" - }, - "passwordHashType": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/PasswordHashingAlgorithm" - } - ] - }, - "roles": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RoleType" - } - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "activatedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "createdByAutomationTokenId": { - "type": [ - "null", - "string" - ], - "format": "uuid" - }, - "deactivatedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "deactivatedByUserId": { - "type": [ - "null", - "string" - ], - "format": "uuid" - }, - "apiTokenCount": { - "type": "integer", - "format": "int32" - }, - "passwordResetCount": { - "type": "integer", - "format": "int32" - }, - "shockerUserShareCount": { - "type": "integer", - "format": "int32" - }, - "shockerPublicShareCount": { - "type": "integer", - "format": "int32" - }, - "emailChangeRequestCount": { - "type": "integer", - "format": "int32" - }, - "nameChangeRequestCount": { - "type": "integer", - "format": "int32" - }, - "deviceCount": { - "type": "integer", - "format": "int32" - }, - "shockerCount": { - "type": "integer", - "format": "int32" - }, - "shockerControlLogCount": { - "type": "integer", - "format": "int32" - } - } - }, - "AuditAction": { - "enum": [ - "Login", - "Logout", - "PasswordChanged", - "EmailChangeRequested", - "EmailChanged", - "UsernameChanged", - "ApiTokenCreated", - "ApiTokenDeleted", - "OAuthConnected", - "OAuthDisconnected", - "AccountDeactivated", - "AccountReactivated", - "AccountDeleted", - "AutomationTokenCreated", - "AutomationTokenUpdated", - "AutomationTokenRotated", - "AutomationTokenDeleted", - "AutomationTokenUsed" - ], - "type": "string" - }, - "AuditLogEntryResponse": { - "required": [ - "id", - "userId", - "actorId", - "action", - "reason", - "ipAddress", - "userAgent", - "metadata", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "userId": { - "type": "string", - "format": "uuid" - }, - "actorId": { - "type": [ - "null", - "string" - ], - "format": "uuid" - }, - "action": { - "$ref": "#/components/schemas/AuditAction" - }, - "reason": { - "type": [ - "null", - "string" - ] - }, - "ipAddress": { - "examples": [ - "127.0.0.1" - ], - "title": "IpAddress", - "type": [ - "null", - "string" - ], - "description": "An IPv4 or IPv6 address in its textual form." - }, - "userAgent": { - "type": [ - "null", - "string" - ] - }, - "metadata": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/AuditMetadata" - } - ] - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - }, - "AuditMetadata": { - "required": [ - "t" - ], - "type": "object", - "anyOf": [ - { - "$ref": "#/components/schemas/AuditMetadataLoginMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataUsernameChangedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataEmailChangeRequestedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataEmailChangedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataApiTokenCreatedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataApiTokenDeletedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataOAuthConnectedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataOAuthDisconnectedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataAccountDeactivatedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataAutomationTokenCreatedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataAutomationTokenUpdatedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataAutomationTokenRotatedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataAutomationTokenDeletedMetadata" - }, - { - "$ref": "#/components/schemas/AuditMetadataAutomationTokenUsedMetadata" - } - ], - "discriminator": { - "propertyName": "t", - "mapping": { - "login": "#/components/schemas/AuditMetadataLoginMetadata", - "usernameChanged": "#/components/schemas/AuditMetadataUsernameChangedMetadata", - "emailChangeRequested": "#/components/schemas/AuditMetadataEmailChangeRequestedMetadata", - "emailChanged": "#/components/schemas/AuditMetadataEmailChangedMetadata", - "apiTokenCreated": "#/components/schemas/AuditMetadataApiTokenCreatedMetadata", - "apiTokenDeleted": "#/components/schemas/AuditMetadataApiTokenDeletedMetadata", - "oauthConnected": "#/components/schemas/AuditMetadataOAuthConnectedMetadata", - "oauthDisconnected": "#/components/schemas/AuditMetadataOAuthDisconnectedMetadata", - "accountDeactivated": "#/components/schemas/AuditMetadataAccountDeactivatedMetadata", - "automationTokenCreated": "#/components/schemas/AuditMetadataAutomationTokenCreatedMetadata", - "automationTokenUpdated": "#/components/schemas/AuditMetadataAutomationTokenUpdatedMetadata", - "automationTokenRotated": "#/components/schemas/AuditMetadataAutomationTokenRotatedMetadata", - "automationTokenDeleted": "#/components/schemas/AuditMetadataAutomationTokenDeletedMetadata", - "automationTokenUsed": "#/components/schemas/AuditMetadataAutomationTokenUsedMetadata" - } - } - }, - "AuditMetadataAccountDeactivatedMetadata": { - "required": [ - "deleteLater" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "accountDeactivated" - ], - "type": "string" - }, - "deleteLater": { - "type": "boolean" - } - } - }, - "AuditMetadataApiTokenCreatedMetadata": { - "required": [ - "tokenId", - "name", - "permissions" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "apiTokenCreated" - ], - "type": "string" - }, - "tokenId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "permissions": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "AuditMetadataApiTokenDeletedMetadata": { - "required": [ - "tokenId", - "name" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "apiTokenDeleted" - ], - "type": "string" - }, - "tokenId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - } - } - }, - "AuditMetadataAutomationTokenCreatedMetadata": { - "required": [ - "tokenId", - "name", - "types", - "autoCleanupUsers", - "autoCleanupAfter" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "automationTokenCreated" - ], - "type": "string" - }, - "tokenId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "types": { - "type": "array", - "items": { - "type": "string" - } - }, - "autoCleanupUsers": { - "type": "boolean" - }, - "autoCleanupAfter": { - "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", - "type": [ - "null", - "string" - ] - } - } - }, - "AuditMetadataAutomationTokenDeletedMetadata": { - "required": [ - "tokenId", - "name", - "deletedAccountCount" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "automationTokenDeleted" - ], - "type": "string" - }, - "tokenId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "deletedAccountCount": { - "type": "integer", - "format": "int32" - } - }, - "description": "The token was deleted together with the int AutomationTokenDeletedMetadata.DeletedAccountCount accounts it created." - }, - "AuditMetadataAutomationTokenRotatedMetadata": { - "required": [ - "tokenId", - "name" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "automationTokenRotated" - ], - "type": "string" - }, - "tokenId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - } - } - }, - "AuditMetadataAutomationTokenUpdatedMetadata": { - "required": [ - "tokenId", - "name", - "types", - "autoCleanupUsers", - "autoCleanupAfter" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "automationTokenUpdated" - ], - "type": "string" - }, - "tokenId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "types": { - "type": "array", - "items": { - "type": "string" - } - }, - "autoCleanupUsers": { - "type": "boolean" - }, - "autoCleanupAfter": { - "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", - "type": [ - "null", - "string" - ] - } - }, - "description": "The token's settings after the update." - }, - "AuditMetadataAutomationTokenUsedMetadata": { - "required": [ - "tokenId", - "name", - "flow" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "automationTokenUsed" - ], - "type": "string" - }, - "tokenId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "flow": { - "type": "string" - } - }, - "description": "An automation token was used on this account. string AutomationTokenUsedMetadata.Flow is a `AutomationTokenFlow` name." - }, - "AuditMetadataEmailChangeRequestedMetadata": { - "required": [ - "newEmail" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "emailChangeRequested" - ], - "type": "string" - }, - "newEmail": { - "type": "string" - } - } - }, - "AuditMetadataEmailChangedMetadata": { - "required": [ - "old", - "new" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "emailChanged" - ], - "type": "string" - }, - "old": { - "type": "string" - }, - "new": { - "type": "string" - } - } - }, - "AuditMetadataLoginMetadata": { - "required": [ - "sessionId" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "login" - ], - "type": "string" - }, - "sessionId": { - "type": "string", - "format": "uuid" - } - } - }, - "AuditMetadataOAuthConnectedMetadata": { - "required": [ - "provider" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "oauthConnected" - ], - "type": "string" - }, - "provider": { - "type": "string" - } - } - }, - "AuditMetadataOAuthDisconnectedMetadata": { - "required": [ - "provider" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "oauthDisconnected" - ], - "type": "string" - }, - "provider": { - "type": "string" - } - } - }, - "AuditMetadataUsernameChangedMetadata": { - "required": [ - "old", - "new" - ], - "type": "object", - "properties": { - "t": { - "enum": [ - "usernameChanged" - ], - "type": "string" - }, - "old": { - "type": "string" - }, - "new": { - "type": "string" - } - } - }, - "AutomationTokenDto": { - "required": [ - "id", - "name", - "types", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "types": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AutomationTokenType" - } - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "lastUsedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "lastRotatedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "useCount": { - "type": "integer", - "format": "int64" - }, - "autoCleanupUsers": { - "type": "boolean" - }, - "autoCleanupAfter": { - "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", - "type": [ - "null", - "string" - ] - } - } - }, - "AutomationTokenType": { - "enum": [ - "Turnstile", - "RateLimit", - "ControlStatsRead" - ], - "type": "string", - "description": "A protection that an automation token is allowed to switch off, or a service capability it grants." - }, - "BackendInfoResponse": { - "required": [ - "version", - "commit", - "currentTime", - "frontendUrl", - "shortLinkUrl", - "turnstileSiteKey", - "oAuthProviders", - "isMailEnabled", - "isUserAuthenticated" - ], - "type": "object", - "properties": { - "version": { - "type": "string" - }, - "commit": { - "type": "string" - }, - "currentTime": { - "type": "string", - "format": "date-time" - }, - "frontendUrl": { - "type": "string", - "format": "uri" - }, - "shortLinkUrl": { - "type": "string", - "format": "uri" - }, - "turnstileSiteKey": { - "type": [ - "null", - "string" - ] - }, - "oAuthProviders": { - "type": "array", - "items": { - "type": "string" - } - }, - "isMailEnabled": { - "type": "boolean", - "description": "False when the instance has no mail provider configured. Accounts are then activated on\ncreation, and no flow that relies on an emailed link (activation, password reset, email\nchange) can complete." - }, - "isUserAuthenticated": { - "type": "boolean" - } - } - }, - "BasicUserInfo": { - "required": [ - "id", - "name", - "image" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "image": { - "type": "string", - "format": "uri" - } - } - }, - "BulkUserShareShockersUpdateRequest": { - "required": [ - "shockers", - "permissions", - "limits" - ], - "type": "object", - "properties": { - "shockers": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - }, - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - } - } - }, - "ChangeEmailRequest": { - "required": [ - "currentPassword", - "email" - ], - "type": "object", - "properties": { - "currentPassword": { - "minLength": 1, - "type": "string" - }, - "email": { - "examples": [ - "user@example.com" - ], - "type": "string" - } - } - }, - "ChangePasswordRequest": { - "required": [ - "currentPassword", - "newPassword" - ], - "type": "object", - "properties": { - "currentPassword": { - "minLength": 1, - "type": "string" - }, - "newPassword": { - "examples": [ - "Password123!" - ], - "type": "string" - } - } - }, - "ChangeUsernameRequest": { - "required": [ - "username" - ], - "type": "object", - "properties": { - "username": { - "examples": [ - "String" - ], - "type": "string" - } - } - }, - "ConfigurationAddItemRequest": { - "required": [ - "name", - "description", - "type", - "value" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 0, - "type": "string", - "description": "The unique name of the configuration item.\nMust consist of uppercase letters and underscores only." - }, - "description": { - "maxLength": 255, - "minLength": 0, - "type": "string", - "description": "A human-readable description of the configuration item’s purpose." - }, - "type": { - "description": "The data type of the configuration value.", - "$ref": "#/components/schemas/ConfigurationValueType" - }, - "value": { - "maxLength": 4096, - "minLength": 0, - "type": "string", - "description": "The initial value for the configuration item, serialized as a string.\nMust conform to the format required by ConfigurationValueType ConfigurationAddItemRequest.Type." - } - }, - "description": "Request DTO for adding a new configuration item." - }, - "ConfigurationItemDto": { - "required": [ - "name", - "description", - "type", - "value", - "updatedAt", - "createdAt" - ], - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The unique name of the configuration item." - }, - "description": { - "type": "string", - "description": "A human-readable description of what this configuration item controls." - }, - "type": { - "description": "The data type of the configuration value.", - "$ref": "#/components/schemas/ConfigurationValueType" - }, - "value": { - "type": "string", - "description": "The current value of the configuration item, serialized as a string." - }, - "updatedAt": { - "type": "string", - "description": "The timestamp when the configuration was last updated.", - "format": "date-time" - }, - "createdAt": { - "type": "string", - "description": "The timestamp when the configuration was originally created.", - "format": "date-time" - } - }, - "description": "Data transfer object representing a configuration item." - }, - "ConfigurationUpdateItemRequest": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 0, - "type": "string", - "description": "The name of the configuration item to update.\nMust consist only of uppercase letters and underscores." - }, - "description": { - "maxLength": 255, - "minLength": 0, - "type": [ - "null", - "string" - ], - "description": "(Optional) New description for the configuration item." - }, - "value": { - "maxLength": 4096, - "minLength": 0, - "type": [ - "null", - "string" - ], - "description": "(Optional) New value for the configuration item.\nMust match the format expected by its existing ConfigurationValueType." - } - }, - "description": "Request DTO for updating a configuration item.\nEither string? ConfigurationUpdateItemRequest.Description or string? ConfigurationUpdateItemRequest.Value (or both) may be provided.\nIf both are null, no update action is performed." - }, - "ConfigurationValueType": { - "enum": [ - "String", - "Bool", - "Int", - "Float", - "Json" - ], - "type": "string" - }, - "Control": { - "required": [ - "id", - "type", - "intensity", - "duration" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "type": { - "$ref": "#/components/schemas/ControlType" - }, - "intensity": { - "maximum": 100, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "duration": { - "maximum": 65535, - "minimum": 300, - "type": "integer", - "format": "int32" - }, - "exclusive": { - "type": "boolean", - "description": "If true, overrides livecontrol" - } - } - }, - "ControlLimitMode": { - "enum": [ - "Clamp", - "Lerp" - ], - "type": "string", - "description": "Determines how a per-token min/max limit is applied to an incoming control value." - }, - "ControlLogSenderLight": { - "required": [ - "id", - "name", - "image", - "customName" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "image": { - "type": "string", - "format": "uri" - }, - "customName": { - "type": [ - "null", - "string" - ] - } - } - }, - "ControlRequest": { - "required": [ - "shocks" - ], - "type": "object", - "properties": { - "shocks": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Control" - } - }, - "customName": { - "type": [ - "null", - "string" - ] - } - } - }, - "ControlStatChangesRequest": { - "required": [ - "userIds" - ], - "type": "object", - "properties": { - "since": { - "type": [ - "null", - "string" - ], - "description": "The cursor returned by the previous call, omit for an initial sync of every requested user.", - "format": "date-time" - }, - "userIds": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "format": "uuid" - }, - "description": "The users the caller is interested in, only these are ever reported." - } - } - }, - "ControlStatChangesResponse": { - "required": [ - "cursor", - "users" - ], - "type": "object", - "properties": { - "cursor": { - "type": "string", - "description": "Pass as `since` on the next call.", - "format": "date-time" - }, - "users": { - "type": "array", - "items": { - "$ref": "#/components/schemas/UserControlStatTotals" - } - } - } - }, - "ControlStatTotals": { - "required": [ - "type", - "live", - "count", - "durationMs", - "averageIntensity", - "maxIntensity" - ], - "type": "object", - "properties": { - "type": { - "$ref": "#/components/schemas/ControlType" - }, - "live": { - "type": "boolean" - }, - "count": { - "type": "integer", - "description": "Number of controls, for live control the number of continuous bursts.", - "format": "int64" - }, - "durationMs": { - "type": "integer", - "format": "int64" - }, - "averageIntensity": { - "type": "number", - "description": "Average intensity weighted by duration.", - "format": "double" - }, - "maxIntensity": { - "maximum": 255, - "minimum": 0, - "type": "integer", - "format": "int32" - } - }, - "description": "Aggregated activity of one control type, split by whether it was live control." - }, - "ControlStatsResponse": { - "required": [ - "received", - "given" - ], - "type": "object", - "properties": { - "received": { - "description": "Activity on shockers you own.", - "$ref": "#/components/schemas/ReceivedControlStats" - }, - "given": { - "description": "Activity you sent to shockers, your own included.", - "$ref": "#/components/schemas/GivenControlStats" - } - } - }, - "ControlType": { - "enum": [ - "Stop", - "Shock", - "Vibrate", - "Sound" - ], - "type": "string" - }, - "CreateAutomationTokenDto": { - "required": [ - "name", - "types" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 1, - "type": "string" - }, - "types": { - "minItems": 1, - "type": "array", - "items": { - "$ref": "#/components/schemas/AutomationTokenType" - } - }, - "autoCleanupUsers": { - "type": "boolean", - "description": "Whether the automated accounts this token creates are deleted once TimeSpan? CreateAutomationTokenDto.AutoCleanupAfter has\npassed since they were created. Off by default; accounts the token didn't create are never deleted." - }, - "autoCleanupAfter": { - "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", - "type": [ - "null", - "string" - ] - } - } - }, - "CreateShareRequest": { - "required": [ - "shockers" - ], - "type": "object", - "properties": { - "shockers": { - "maxItems": 128, - "type": "array", - "items": { - "$ref": "#/components/schemas/ShockerPermLimitPairWithId" - } - }, - "user": { - "type": [ - "null", - "string" - ], - "format": "uuid" - } - } - }, - "CreateTokenRequestV2": { - "required": [ - "name", - "permissions", - "shockerControl" - ], - "type": "object", - "properties": { - "validUntil": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "name": { - "maxLength": 64, - "minLength": 1, - "type": "string" - }, - "permissions": { - "maxItems": 256, - "type": "array", - "items": { - "$ref": "#/components/schemas/PermissionType" - } - }, - "shockerControl": { - "description": "Per-token shocker control configuration. When omitted, the permissive default is used.", - "$ref": "#/components/schemas/ShockerControlSettings" - } - } - }, - "CreatedAutomationTokenDto": { - "required": [ - "id", - "name", - "secret", - "types", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "secret": { - "type": "string" - }, - "types": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AutomationTokenType" - } - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "lastRotatedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "autoCleanupUsers": { - "type": "boolean" - }, - "autoCleanupAfter": { - "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", - "type": [ - "null", - "string" - ] - } - } - }, - "DailyControlStats": { - "required": [ - "date", - "stats" - ], - "type": "object", - "properties": { - "date": { - "type": "string", - "description": "Day in the requested time zone.", - "format": "date" - }, - "stats": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ControlStatTotals" - } - } - } - }, - "DeviceResponse": { - "required": [ - "id", - "name", - "createdOn" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - } - } - }, - "DeviceSelfResponse": { - "required": [ - "id", - "name", - "shockers" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "shockers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/MinimalShocker" - } - } - } - }, - "DeviceWithShockersResponse": { - "required": [ - "shockers", - "id", - "name", - "createdOn" - ], - "type": "object", - "properties": { - "shockers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShockerResponse" - } - }, - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - } - } - }, - "DeviceWithTokenResponse": { - "required": [ - "token", - "id", - "name", - "createdOn" - ], - "type": "object", - "properties": { - "token": { - "type": [ - "null", - "string" - ] - }, - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - } - } - }, - "DurationLimitSettings": { - "required": [ - "min", - "max" - ], - "type": "object", - "properties": { - "min": { - "maximum": 65535, - "minimum": 300, - "type": "integer", - "format": "int32" - }, - "max": { - "maximum": 65535, - "minimum": 300, - "type": "integer", - "format": "int32" - }, - "mode": { - "$ref": "#/components/schemas/ControlLimitMode" - } - } - }, - "EditTokenRequestV2": { - "required": [ - "name", - "permissions", - "shockerControl" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 1, - "type": "string" - }, - "permissions": { - "maxItems": 256, - "type": "array", - "items": { - "$ref": "#/components/schemas/PermissionType" - } - }, - "shockerControl": { - "description": "Per-token shocker control configuration. When omitted, the permissive default is used.", - "$ref": "#/components/schemas/ShockerControlSettings" - } - } - }, - "EmailOutboxBulkRequest": { - "required": [ - "ids" - ], - "type": "object", - "properties": { - "ids": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - } - }, - "description": "A set of email outbox message ids to apply a bulk requeue/cancel/delete to." - }, - "EmailOutboxBulkResultDto": { - "required": [ - "requested", - "affected" - ], - "type": "object", - "properties": { - "requested": { - "type": "integer", - "format": "int32" - }, - "affected": { - "type": "integer", - "format": "int32" - } - }, - "description": "Outcome of a bulk email outbox operation: how many ids were requested and how many rows were\nactually affected (rows that were missing or in an ineligible state are silently not counted)." - }, - "EmailOutboxMessageDto": { - "required": [ - "id", - "type", - "recipient", - "recipientName", - "payload", - "coalesceKey", - "status", - "attemptCount", - "nextAttemptAt", - "lastError", - "createdAt", - "sentAt", - "failedAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "type": { - "$ref": "#/components/schemas/EmailType" - }, - "recipient": { - "type": "string" - }, - "recipientName": { - "type": [ - "null", - "string" - ] - }, - "payload": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "coalesceKey": { - "type": [ - "null", - "string" - ] - }, - "status": { - "$ref": "#/components/schemas/EmailStatus" - }, - "attemptCount": { - "type": "integer", - "format": "int32" - }, - "nextAttemptAt": { - "type": "string", - "format": "date-time" - }, - "lastError": { - "type": [ - "null", - "string" - ] - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "sentAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "failedAt": { - "type": [ - "null", - "string" - ], - "format": "date-time" - } - }, - "description": "An EmailOutboxMessage as exposed to admins on the mail-queue page. Mirrors the row\nverbatim - the outbox stores no rendered body and no usable secret, so every field is safe to show." - }, - "EmailOutboxStatsDto": { - "required": [ - "pending", - "sending", - "sent", - "failed", - "skipped", - "total" - ], - "type": "object", - "properties": { - "pending": { - "type": "integer", - "format": "int64" - }, - "sending": { - "type": "integer", - "format": "int64" - }, - "sent": { - "type": "integer", - "format": "int64" - }, - "failed": { - "type": "integer", - "format": "int64" - }, - "skipped": { - "type": "integer", - "format": "int64" - }, - "total": { - "type": "integer", - "format": "int64" - } - }, - "description": "Count of email outbox rows in each delivery state, for the admin mail-queue overview tiles." - }, - "EmailProviderBlacklistDto": { - "required": [ - "id", - "domain", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "domain": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - }, - "EmailStatus": { - "enum": [ - "Pending", - "Sending", - "Sent", - "Failed", - "Skipped" - ], - "type": "string", - "description": "Delivery state of an email outbox message." - }, - "EmailType": { - "enum": [ - "AccountActivation", - "PasswordReset", - "EmailVerification", - "EmailChangeNotice" - ], - "type": "string", - "description": "The kind of email an outbox message represents. The outbox stores\nonly the intent to send one of these, never a rendered body or a usable secret, the\nconsumer maps the type to the matching template and (for token-bearing types) mints a fresh\nsecret at send time." - }, - "GivenControlStats": { - "required": [ - "totals", - "owners" - ], - "type": "object", - "properties": { - "totals": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ControlStatTotals" - } - }, - "owners": { - "type": "array", - "items": { - "$ref": "#/components/schemas/UserControlStats" - } - } - } - }, - "HubCreateRequest": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 1, - "type": "string" - } - } - }, - "HubEditRequest": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 1, - "type": "string" - } - } - }, - "IntensityLimitSettings": { - "required": [ - "min", - "max", - "mode" - ], - "type": "object", - "properties": { - "min": { - "maximum": 100, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "max": { - "maximum": 100, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "mode": { - "$ref": "#/components/schemas/ControlLimitMode" - } - } - }, - "LcgNodeResponseV2": { - "required": [ - "host", - "port", - "path", - "country" - ], - "type": "object", - "properties": { - "host": { - "type": "string" - }, - "port": { - "maximum": 65535, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "path": { - "type": "string" - }, - "country": { - "type": "string" - } - } - }, - "LcgResponseV2": { - "required": [ - "host", - "port", - "pathPrefix", - "country" - ], - "type": "object", - "properties": { - "host": { - "type": "string", - "description": "Public host of the gateway the hub is connected to." - }, - "port": { - "maximum": 65535, - "minimum": 0, - "type": "integer", - "description": "Public port to connect to (default 443).", - "format": "int32" - }, - "pathPrefix": { - "type": "string", - "description": "Base path prefix the gateway is served under, e.g. \"/gateway\" (empty for root). The client\nbuilds the full URL and appends the live-control route (`/1/ws/live/{hubId}`) itself." - }, - "country": { - "type": "string" - } - } - }, - "LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminOnlineDeviceResponse" - } - } - } - }, - "LegacyDataResponseOfArrayOfDeviceResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/DeviceResponse" - } - } - } - }, - "LegacyDataResponseOfArrayOfDeviceWithShockersResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/DeviceWithShockersResponse" - } - } - } - }, - "LegacyDataResponseOfArrayOfLogEntry": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/LogEntry" - } - } - } - }, - "LegacyDataResponseOfArrayOfOwnPublicShareResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/OwnPublicShareResponse" - } - } - } - }, - "LegacyDataResponseOfArrayOfOwnerShockerResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/OwnerShockerResponse" - } - } - } - }, - "LegacyDataResponseOfArrayOfShareCodeInfo": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareCodeInfo" - } - } - } - }, - "LegacyDataResponseOfArrayOfShareInfo": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShareInfo" - } - } - } - }, - "LegacyDataResponseOfArrayOfShockerResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShockerResponse" - } - } - } - }, - "LegacyDataResponseOfBackendInfoResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "$ref": "#/components/schemas/BackendInfoResponse" - } - } - }, - "LegacyDataResponseOfDeviceSelfResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "$ref": "#/components/schemas/DeviceSelfResponse" - } - } - }, - "LegacyDataResponseOfDeviceWithTokenResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "$ref": "#/components/schemas/DeviceWithTokenResponse" - } - } - }, - "LegacyDataResponseOfGuid": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "string", - "format": "uuid" - } - } - }, - "LegacyDataResponseOfIReadOnlyCollectionOfOtaItem": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/OtaItem" - } - } - } - }, - "LegacyDataResponseOfLegacyUserSelfResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "$ref": "#/components/schemas/LegacyUserSelfResponse" - } - } - }, - "LegacyDataResponseOfPauseReason": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "examples": [ - 6 - ], - "title": "PauseReason", - "type": "integer", - "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." - } - } - }, - "LegacyDataResponseOfPublicShareResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "$ref": "#/components/schemas/PublicShareResponse" - } - } - }, - "LegacyDataResponseOfShockerWithDevice": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "$ref": "#/components/schemas/ShockerWithDevice" - } - } - }, - "LegacyDataResponseOfStatsResponse": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "$ref": "#/components/schemas/StatsResponse" - } - } - }, - "LegacyDataResponseOfboolean": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "boolean" - } - } - }, - "LegacyDataResponseOfstring": { - "required": [ - "data", - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string", - "default": "" - }, - "data": { - "type": "string" - } - } - }, - "LegacyEmptyResponse": { - "required": [ - "message" - ], - "type": "object", - "properties": { - "message": { - "type": "string" - }, - "data": {} - } - }, - "LegacyUserSelfResponse": { - "required": [ - "id", - "name", - "email", - "image", - "roles", - "rank", - "hasPassword" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "email": { - "type": "string" - }, - "image": { - "type": "string", - "format": "uri" - }, - "roles": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RoleType" - } - }, - "rank": { - "type": "string" - }, - "hasPassword": { - "type": "boolean" - } - }, - "description": "Response shape of the deprecated GET /1/users/self, kept for API token clients that still read `rank`." - }, - "LogEntry": { - "required": [ - "id", - "createdOn", - "type", - "controlledBy", - "intensity", - "duration", - "liveControl" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "type": { - "$ref": "#/components/schemas/ControlType" - }, - "controlledBy": { - "$ref": "#/components/schemas/ControlLogSenderLight" - }, - "intensity": { - "maximum": 255, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "duration": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - }, - "liveControl": { - "type": "boolean" - } - } - }, - "LogEntryWithHub": { - "required": [ - "id", - "hubId", - "hubName", - "shockerId", - "shockerName", - "createdOn", - "type", - "controlledBy", - "intensity", - "duration", - "liveControl" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "hubId": { - "type": "string", - "format": "uuid" - }, - "hubName": { - "type": "string" - }, - "shockerId": { - "type": "string", - "format": "uuid" - }, - "shockerName": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "type": { - "$ref": "#/components/schemas/ControlType" - }, - "controlledBy": { - "$ref": "#/components/schemas/ControlLogSenderLight" - }, - "intensity": { - "maximum": 255, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "duration": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer" - }, - "liveControl": { - "type": "boolean" - } - } - }, - "LoginSessionResponse": { - "required": [ - "id", - "ip", - "userAgent", - "created", - "expires", - "lastUsed" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "ip": { - "examples": [ - "127.0.0.1" - ], - "title": "IpAddress", - "type": "string", - "description": "An IPv4 or IPv6 address in its textual form." - }, - "userAgent": { - "type": "string" - }, - "created": { - "type": "string", - "format": "date-time" - }, - "expires": { - "type": "string", - "format": "date-time" - }, - "lastUsed": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "asnOrg": { - "type": [ - "null", - "string" - ] - }, - "isVpn": { - "type": [ - "null", - "boolean" - ] - }, - "countryCode": { - "type": [ - "null", - "string" - ] - }, - "city": { - "type": [ - "null", - "string" - ] - } - } - }, - "LoginV2": { - "required": [ - "password", - "usernameOrEmail", - "turnstileResponse" - ], - "type": "object", - "properties": { - "password": { - "minLength": 1, - "type": "string" - }, - "usernameOrEmail": { - "minLength": 1, - "type": "string" - }, - "turnstileResponse": { - "maxLength": 2048, - "minLength": 0, - "type": "string" - } - } - }, - "LoginV2OkResponse": { - "required": [ - "accountId", - "accountName", - "accountEmail", - "isVerified", - "profileImage", - "accountRoles" - ], - "type": "object", - "properties": { - "accountId": { - "type": "string", - "format": "uuid" - }, - "accountName": { - "type": "string" - }, - "accountEmail": { - "type": "string" - }, - "isVerified": { - "type": "boolean" - }, - "profileImage": { - "type": "string", - "format": "uri" - }, - "accountRoles": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RoleType" - } - } - } - }, - "MatchTypeEnum": { - "enum": [ - "Exact", - "Contains" - ], - "type": "string" - }, - "MinimalShocker": { - "required": [ - "id", - "rfId", - "model" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "rfId": { - "maximum": 65535, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "model": { - "$ref": "#/components/schemas/ShockerModelType" - } - } - }, - "NewShocker": { - "required": [ - "name", - "rfId", - "device", - "model" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 1, - "type": "string" - }, - "rfId": { - "maximum": 65535, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "device": { - "type": "string", - "format": "uuid" - }, - "model": { - "$ref": "#/components/schemas/ShockerModelType" - } - } - }, - "OAuthConnectionResponse": { - "required": [ - "providerKey", - "externalId", - "displayName", - "linkedAt" - ], - "type": "object", - "properties": { - "providerKey": { - "type": "string" - }, - "externalId": { - "type": "string" - }, - "displayName": { - "type": [ - "null", - "string" - ] - }, - "linkedAt": { - "type": "string", - "format": "date-time" - } - } - }, - "OpenShockProblem": { - "required": [ - "type", - "title" - ], - "type": "object", - "properties": { - "type": { - "type": [ - "null", - "string" - ] - }, - "title": { - "type": [ - "null", - "string" - ] - }, - "status": { - "type": [ - "null", - "integer" - ], - "format": "int32" - }, - "detail": { - "type": [ - "null", - "string" - ] - }, - "instance": { - "type": [ - "null", - "string" - ] - }, - "message": { - "type": "string", - "deprecated": true - }, - "traceId": { - "type": [ - "null", - "string" - ], - "deprecated": true - }, - "requestId": { - "type": [ - "null", - "string" - ] - } - } - }, - "OtaItem": { - "required": [ - "id", - "startedAt", - "status", - "version", - "message" - ], - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int32" - }, - "startedAt": { - "type": "string", - "format": "date-time" - }, - "status": { - "$ref": "#/components/schemas/OtaUpdateStatus" - }, - "version": { - "examples": [ - "1.0.0-dev+a16f2" - ], - "title": "SemVer", - "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$", - "type": "string" - }, - "message": { - "type": [ - "null", - "string" - ] - } - } - }, - "OtaUpdateStatus": { - "enum": [ - "Started", - "Running", - "Finished", - "Error", - "Timeout" - ], - "type": "string" - }, - "OwnPublicShareResponse": { - "required": [ - "id", - "name", - "createdOn" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "expiresOn": { - "type": [ - "null", - "string" - ], - "format": "date-time" - } - } - }, - "OwnerShockerResponse": { - "required": [ - "id", - "name", - "image", - "devices" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "image": { - "type": "string", - "format": "uri" - }, - "devices": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SharedDevice" - } - } - } - }, - "PagedResultOfAuditLogEntryResponse": { - "required": [ - "items", - "page", - "pageSize", - "totalCount" - ], - "type": "object", - "properties": { - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AuditLogEntryResponse" - }, - "description": "Items on the current page." - }, - "page": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer", - "description": "1-based current page index." - }, - "pageSize": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer", - "description": "Page size used to produce this result." - }, - "totalCount": { - "type": "integer", - "description": "Total number of items across all pages matching the query.", - "format": "int32" - }, - "totalPages": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer", - "description": "Total number of pages. Always at least 1, even when `TotalCount` is zero." - } - }, - "description": "Page of results for a paginated list endpoint." - }, - "PagedResultOfLogEntryWithHub": { - "required": [ - "items", - "page", - "pageSize", - "totalCount" - ], - "type": "object", - "properties": { - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/LogEntryWithHub" - }, - "description": "Items on the current page." - }, - "page": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer", - "description": "1-based current page index." - }, - "pageSize": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer", - "description": "Page size used to produce this result." - }, - "totalCount": { - "type": "integer", - "description": "Total number of items across all pages matching the query.", - "format": "int32" - }, - "totalPages": { - "maximum": 4294967295, - "minimum": 0, - "type": "integer", - "description": "Total number of pages. Always at least 1, even when `TotalCount` is zero." - } - }, - "description": "Page of results for a paginated list endpoint." - }, - "PaginatedOfAdminUsersView": { - "required": [ - "offset", - "limit", - "total", - "data" - ], - "type": "object", - "properties": { - "offset": { - "type": "integer", - "format": "int32" - }, - "limit": { - "type": "integer", - "format": "int32" - }, - "total": { - "type": "integer", - "format": "int64" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUsersView" - } - } - } - }, - "PaginatedOfEmailOutboxMessageDto": { - "required": [ - "offset", - "limit", - "total", - "data" - ], - "type": "object", - "properties": { - "offset": { - "type": "integer", - "format": "int32" - }, - "limit": { - "type": "integer", - "format": "int32" - }, - "total": { - "type": "integer", - "format": "int64" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/EmailOutboxMessageDto" - } - } - } - }, - "PasswordHashingAlgorithm": { - "enum": [ - "BCrypt", - "PBKDF2", - "Unknown" - ], - "type": "string" - }, - "PasswordResetProcessData": { - "required": [ - "password" - ], - "type": "object", - "properties": { - "password": { - "type": "string" - } - } - }, - "PasswordResetRequestV2": { - "required": [ - "email", - "turnstileResponse" - ], - "type": "object", - "properties": { - "email": { - "examples": [ - "user@example.com" - ], - "type": "string" - }, - "turnstileResponse": { - "maxLength": 2048, - "minLength": 0, - "type": "string" - } - } - }, - "PatchAutomationTokenDto": { - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 1, - "type": [ - "null", - "string" - ] - }, - "types": { - "minItems": 1, - "type": [ - "null", - "array" - ], - "items": { - "$ref": "#/components/schemas/AutomationTokenType" - } - }, - "autoCleanupUsers": { - "type": [ - "null", - "boolean" - ] - }, - "autoCleanupAfter": { - "pattern": "^-?(\\d+\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", - "type": [ - "null", - "string" - ] - } - } - }, - "PauseRequest": { - "required": [ - "pause" - ], - "type": "object", - "properties": { - "pause": { - "type": "boolean" - } - } - }, - "PauseUserShareShockersRequest": { - "required": [ - "shockers", - "pause" - ], - "type": "object", - "properties": { - "shockers": { - "minItems": 1, - "type": "array", - "items": { - "type": "string", - "format": "uuid" - } - }, - "pause": { - "type": "boolean" - } - } - }, - "PauseUserShareShockersResponse": { - "required": [ - "affectedRecords", - "pauseStates" - ], - "type": "object", - "properties": { - "affectedRecords": { - "type": "integer", - "format": "int32" - }, - "pauseStates": { - "type": "object", - "additionalProperties": { - "examples": [ - 6 - ], - "title": "PauseReason", - "type": "integer", - "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." - } - } - } - }, - "PermissionType": { - "enum": [ - "shockers.use", - "shockers.edit", - "shockers.pause", - "devices.edit", - "devices.auth", - "usershares.edit", - "usershares.pause", - "publicshares.pause", - "publicshares.edit" - ], - "type": "string" - }, - "ProblemDetails": { - "type": "object", - "properties": { - "type": { - "type": [ - "null", - "string" - ] - }, - "title": { - "type": [ - "null", - "string" - ] - }, - "status": { - "type": [ - "null", - "integer" - ], - "format": "int32" - }, - "detail": { - "type": [ - "null", - "string" - ] - }, - "instance": { - "type": [ - "null", - "string" - ] - } - } - }, - "PublicShareCreate": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "name": { - "maxLength": 64, - "minLength": 1, - "type": "string" - }, - "expiresOn": { - "type": [ - "null", - "string" - ], - "format": "date-time" - } - } - }, - "PublicShareDevice": { - "required": [ - "id", - "name", - "shockers" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "shockers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PublicShareShocker" - } - } - } - }, - "PublicShareEditShocker": { - "required": [ - "permissions", - "limits" - ], - "type": "object", - "properties": { - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - }, - "cooldown": { - "maximum": 65535, - "minimum": 300, - "type": [ - "null", - "integer" - ], - "format": "int32" - } - } - }, - "PublicShareResponse": { - "required": [ - "id", - "name", - "createdOn", - "author" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "expiresOn": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "author": { - "$ref": "#/components/schemas/BasicUserInfo" - }, - "devices": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PublicShareDevice" - } - } - } - }, - "PublicShareShocker": { - "required": [ - "id", - "name", - "permissions", - "limits", - "paused" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - }, - "paused": { - "examples": [ - 6 - ], - "title": "PauseReason", - "type": "integer", - "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." - } - } - }, - "ReceivedControlStats": { - "required": [ - "totals", - "shockers", - "controllers", - "days" - ], - "type": "object", - "properties": { - "totals": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ControlStatTotals" - } - }, - "shockers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShockerControlStats" - } - }, - "controllers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/UserControlStats" - } - }, - "days": { - "type": "array", - "items": { - "$ref": "#/components/schemas/DailyControlStats" - } - } - } - }, - "RemoveUserSharesResponse": { - "required": [ - "affectedRecords" - ], - "type": "object", - "properties": { - "affectedRecords": { - "type": "integer", - "format": "int32" - } - } - }, - "ReportTokensRequest": { - "required": [ - "turnstileResponse", - "secrets" - ], - "type": "object", - "properties": { - "turnstileResponse": { - "maxLength": 2048, - "minLength": 0, - "type": "string" - }, - "secrets": { - "maxItems": 512, - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "RoleType": { - "enum": [ - "Support", - "Staff", - "Admin", - "System" - ], - "type": "string" - }, - "SendTestEmailDto": { - "required": [ - "type", - "recipient" - ], - "type": "object", - "properties": { - "type": { - "description": "Which template to preview.", - "$ref": "#/components/schemas/EmailType" - }, - "recipient": { - "examples": [ - "user@example.com" - ], - "type": "string", - "description": "Destination address for the test email." - }, - "recipientName": { - "type": [ - "null", - "string" - ], - "description": "Optional display name for the recipient." - } - }, - "description": "Request to enqueue a preview/test email of a chosen type to a chosen address. The message is\ndelivered by the Cron pipeline with placeholder data and a dummy link (no token, no request row)." - }, - "SetTokenPausedRequest": { - "required": [ - "paused" - ], - "type": "object", - "properties": { - "paused": { - "type": "boolean", - "description": "When true, the token is paused and may not send shocker control messages." - } - } - }, - "SetUserEmailRequestBody": { - "required": [ - "email" - ], - "type": "object", - "properties": { - "email": { - "examples": [ - "user@example.com" - ], - "type": "string" - } - } - }, - "SetUserNameRequestBody": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "name": { - "examples": [ - "String" - ], - "type": "string" - } - } - }, - "SetUserPasswordRequestBody": { - "required": [ - "password" - ], - "type": "object", - "properties": { - "password": { - "examples": [ - "Password123!" - ], - "type": "string" - } - } - }, - "ShareCodeInfo": { - "required": [ - "id", - "createdOn" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "createdOn": { - "type": "string", - "format": "date-time" - } - } - }, - "ShareInfo": { - "required": [ - "sharedWith", - "createdOn", - "permissions", - "limits", - "paused" - ], - "type": "object", - "properties": { - "sharedWith": { - "$ref": "#/components/schemas/BasicUserInfo" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - }, - "paused": { - "type": "boolean" - } - } - }, - "ShareInviteBaseDetails": { - "required": [ - "shockers", - "id", - "createdAt", - "owner", - "sharedWith" - ], - "type": "object", - "properties": { - "shockers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ShockerPermLimitPairWithIdAndName" - } - }, - "id": { - "type": "string", - "format": "uuid" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "owner": { - "$ref": "#/components/schemas/BasicUserInfo" - }, - "sharedWith": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/BasicUserInfo" - } - ] - } - } - }, - "SharedDevice": { - "required": [ - "id", - "name", - "shockers" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "shockers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SharedShocker" - } - } - } - }, - "SharedShocker": { - "required": [ - "id", - "name", - "isPaused", - "permissions", - "limits" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "isPaused": { - "type": "boolean" - }, - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - } - } - }, - "ShockerControlSettings": { - "required": [ - "paused", - "intensity", - "duration" - ], - "type": "object", - "properties": { - "paused": { - "type": "boolean", - "description": "When true, this token is paused and may not send shocker control messages." - }, - "intensity": { - "$ref": "#/components/schemas/IntensityLimitSettings" - }, - "duration": { - "$ref": "#/components/schemas/DurationLimitSettings" - } - }, - "description": "Per-token shocker control configuration: a toggle plus min/max limits for intensity and duration." - }, - "ShockerControlStats": { - "required": [ - "shockerId", - "shockerName", - "stats" - ], - "type": "object", - "properties": { - "shockerId": { - "type": [ - "null", - "string" - ], - "description": "Null for shockers that have since been deleted, these are combined into one entry.", - "format": "uuid" - }, - "shockerName": { - "type": [ - "null", - "string" - ] - }, - "stats": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ControlStatTotals" - } - } - } - }, - "ShockerLimits": { - "required": [ - "intensity", - "duration" - ], - "type": "object", - "properties": { - "intensity": { - "maximum": 100, - "minimum": 0, - "type": [ - "null", - "integer" - ], - "format": "int32" - }, - "duration": { - "maximum": 65535, - "minimum": 300, - "type": [ - "null", - "integer" - ], - "format": "int32" - } - } - }, - "ShockerModelType": { - "enum": [ - "CaiXianlin", - "PetTrainer", - "Petrainer998DR", - "WellturnT330" - ], - "type": "string" - }, - "ShockerPermLimitPair": { - "required": [ - "permissions", - "limits" - ], - "type": "object", - "properties": { - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - } - } - }, - "ShockerPermLimitPairWithId": { - "required": [ - "permissions", - "limits" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - } - } - }, - "ShockerPermLimitPairWithIdAndName": { - "required": [ - "name", - "permissions", - "limits" - ], - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "id": { - "type": "string", - "format": "uuid" - }, - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - } - } - }, - "ShockerPermissions": { - "required": [ - "vibrate", - "sound", - "shock" - ], - "type": "object", - "properties": { - "vibrate": { - "type": "boolean" - }, - "sound": { - "type": "boolean" - }, - "shock": { - "type": "boolean" - }, - "live": { - "type": "boolean" - } - } - }, - "ShockerResponse": { - "required": [ - "name", - "isPaused", - "createdOn", - "id", - "rfId", - "model" - ], - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "isPaused": { - "type": "boolean" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "id": { - "type": "string", - "format": "uuid" - }, - "rfId": { - "maximum": 65535, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "model": { - "$ref": "#/components/schemas/ShockerModelType" - } - } - }, - "ShockerWithDevice": { - "required": [ - "device", - "name", - "isPaused", - "createdOn", - "id", - "rfId", - "model" - ], - "type": "object", - "properties": { - "device": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "isPaused": { - "type": "boolean" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "id": { - "type": "string", - "format": "uuid" - }, - "rfId": { - "maximum": 65535, - "minimum": 0, - "type": "integer", - "format": "int32" - }, - "model": { - "$ref": "#/components/schemas/ShockerModelType" - } - } - }, - "SignUpV2": { - "required": [ - "username", - "password", - "email", - "turnstileResponse" - ], - "type": "object", - "properties": { - "username": { - "examples": [ - "String" - ], - "type": "string" - }, - "password": { - "examples": [ - "Password123!" - ], - "type": "string" - }, - "email": { - "examples": [ - "user@example.com" - ], - "type": "string" - }, - "turnstileResponse": { - "maxLength": 2048, - "minLength": 0, - "type": "string" - } - } - }, - "SortDirection": { - "enum": [ - "Asc", - "Desc" - ], - "type": "string", - "description": "Sort direction for list endpoints." - }, - "StatsResponse": { - "required": [ - "devicesOnline" - ], - "type": "object", - "properties": { - "devicesOnline": { - "type": "integer", - "format": "int64" - } - } - }, - "TokenCreatedResponseV2": { - "required": [ - "id", - "name", - "token", - "createdAt", - "validUntil", - "lastUsed", - "permissions", - "shockerControl" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "token": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "validUntil": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "lastUsed": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "permissions": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PermissionType" - } - }, - "shockerControl": { - "$ref": "#/components/schemas/ShockerControlSettings" - } - } - }, - "TokenPausedResponse": { - "required": [ - "paused" - ], - "type": "object", - "properties": { - "paused": { - "type": "boolean", - "description": "The now-set paused state of the token." - } - } - }, - "TokenResponseV2": { - "required": [ - "id", - "name", - "createdOn", - "validUntil", - "lastUsed", - "permissions", - "shockerControl" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "validUntil": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "lastUsed": { - "type": [ - "null", - "string" - ], - "format": "date-time" - }, - "permissions": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PermissionType" - } - }, - "shockerControl": { - "$ref": "#/components/schemas/ShockerControlSettings" - } - } - }, - "UserControlStatTotals": { - "required": [ - "userId", - "received", - "given" - ], - "type": "object", - "properties": { - "userId": { - "type": "string", - "format": "uuid" - }, - "received": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ControlStatTotals" - }, - "description": "Activity on shockers the user owns." - }, - "given": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ControlStatTotals" - }, - "description": "Activity the user sent to shockers, their own included." - } - }, - "description": "Lifetime totals of one user, the same views as ControlStatsResponse without breakdowns." - }, - "UserControlStats": { - "required": [ - "userId", - "user", - "stats" - ], - "type": "object", - "properties": { - "userId": { - "type": [ - "null", - "string" - ], - "description": "Null for guests (public shares).", - "format": "uuid" - }, - "user": { - "oneOf": [ - { - "type": "null" - }, - { - "description": "Null for guests and deleted users.", - "$ref": "#/components/schemas/BasicUserInfo" - } - ] - }, - "stats": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ControlStatTotals" - } - } - } - }, - "UserNameBlacklistDto": { - "required": [ - "id", - "value", - "matchType", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "value": { - "type": "string" - }, - "matchType": { - "$ref": "#/components/schemas/MatchTypeEnum" - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - }, - "UserPatchDto": { - "type": "object", - "properties": { - "name": { - "type": [ - "null", - "string" - ] - }, - "email": { - "type": [ - "null", - "string" - ] - } - } - }, - "UserSelfResponse": { - "required": [ - "id", - "name", - "email", - "image", - "roles", - "hasPassword" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "email": { - "type": "string" - }, - "image": { - "type": "string", - "format": "uri" - }, - "roles": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RoleType" - } - }, - "hasPassword": { - "type": "boolean" - } - } - }, - "UserShareInfo": { - "required": [ - "id", - "name", - "createdOn", - "permissions", - "limits", - "paused" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "createdOn": { - "type": "string", - "format": "date-time" - }, - "permissions": { - "$ref": "#/components/schemas/ShockerPermissions" - }, - "limits": { - "$ref": "#/components/schemas/ShockerLimits" - }, - "paused": { - "examples": [ - 6 - ], - "title": "PauseReason", - "type": "integer", - "description": "An integer representing the reason(s) for the shocker being paused, expressed as a bitfield where reasons are OR'd together.\n\nEach bit corresponds to:\n- 1: Shocker\n- 2: UserShare\n- 4: PublicShare\n\nFor example, a value of 6 (2 | 4) indicates both 'UserShare' and 'PublicShare' reasons." - } - } - }, - "UsernameAvailability": { - "enum": [ - "Available", - "Taken", - "Invalid" - ], - "type": "string" - }, - "UsernameCheckResponse": { - "required": [ - "availability" - ], - "type": "object", - "properties": { - "availability": { - "$ref": "#/components/schemas/UsernameAvailability" - }, - "error": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/UsernameError" - } - ] - } - } - }, - "UsernameError": { - "required": [ - "message", - "type" - ], - "type": "object", - "properties": { - "message": { - "type": "string" - }, - "type": { - "$ref": "#/components/schemas/UsernameErrorType" - } - } - }, - "UsernameErrorType": { - "enum": [ - "TooShort", - "TooLong", - "StartOrEndWithWhitespace", - "ResembleEmail", - "ObnoxiousCharacters", - "Blacklisted" - ], - "type": "string" - }, - "V2UserShares": { - "required": [ - "outgoing", - "incoming" - ], - "type": "object", - "properties": { - "outgoing": { - "type": "array", - "items": { - "$ref": "#/components/schemas/V2UserSharesListItem" - } - }, - "incoming": { - "type": "array", - "items": { - "$ref": "#/components/schemas/V2UserSharesListItem" - } - } - } - }, - "V2UserSharesListItem": { - "required": [ - "id", - "name", - "image", - "shares" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "image": { - "type": "string", - "format": "uri" - }, - "shares": { - "type": "array", - "items": { - "$ref": "#/components/schemas/UserShareInfo" - } - } - } - }, - "WebhookDto": { - "required": [ - "id", - "name", - "url", - "createdAt" - ], - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string" - }, - "url": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - } - } - } - }, - "securitySchemes": { - "UserSessionCookie": { - "type": "apiKey", - "description": "Enter user session cookie", - "name": "openShockSession", - "in": "cookie" - }, - "ApiToken": { - "type": "apiKey", - "description": "Enter API Token", - "name": "OpenShockToken", - "in": "header" - }, - "HubToken": { - "type": "apiKey", - "description": "Enter hub token", - "name": "DeviceToken", - "in": "header" - } - } - }, - "tags": [ - { - "name": "API Tokens", - "description": "API token management" - }, - { - "name": "Account", - "description": "User account management" - }, - { - "name": "Admin", - "description": "Instance administration, for admins only" - }, - { - "name": "Hub Endpoints", - "description": "For devices (ESP's)" - }, - { - "name": "Hub Management", - "description": "Device management" - }, - { - "name": "Integrations", - "description": "Endpoints for first party services (e.g. the Discord bot). Not tied to a user session, every action checks\nfor an automation token that grants the capability it needs." - }, - { - "name": "Meta", - "description": "Version stuff" - }, - { - "name": "Public Shocker Shares", - "description": "Public shares management" - }, - { - "name": "Sessions", - "description": "Session management" - }, - { - "name": "Shocker Shares", - "description": "Shocker share management" - }, - { - "name": "Shockers", - "description": "Shocker management" - }, - { - "name": "User Shocker Shares", - "description": "Shocker share management" - }, - { - "name": "Users", - "description": "User information" - } - ] -} diff --git a/openshock/rest/api/account/account_activate.py b/openshock/rest/api/account/account_activate.py deleted file mode 100644 index d6f015f..0000000 --- a/openshock/rest/api/account/account_activate.py +++ /dev/null @@ -1,165 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - token: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["token"] = token - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/activate", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Response[Any | OpenShockProblem]: - """Activate account - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token=token, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Any | OpenShockProblem | None: - """Activate account - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - token=token, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Response[Any | OpenShockProblem]: - """Activate account - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token=token, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Any | OpenShockProblem | None: - """Activate account - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - token=token, - ) - ).parsed diff --git a/openshock/rest/api/account/account_check_username.py b/openshock/rest/api/account/account_check_username.py deleted file mode 100644 index b40e546..0000000 --- a/openshock/rest/api/account/account_check_username.py +++ /dev/null @@ -1,159 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.change_username_request import ChangeUsernameRequest -from ...models.username_check_response import UsernameCheckResponse -from ...types import Response - - -def _get_kwargs( - *, - body: ChangeUsernameRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/username/check", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> UsernameCheckResponse | None: - if response.status_code == 200: - response_200 = UsernameCheckResponse.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[UsernameCheckResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, - body: ChangeUsernameRequest, -) -> Response[UsernameCheckResponse]: - """Check if a username is available - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[UsernameCheckResponse] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, - body: ChangeUsernameRequest, -) -> UsernameCheckResponse | None: - """Check if a username is available - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - UsernameCheckResponse - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, - body: ChangeUsernameRequest, -) -> Response[UsernameCheckResponse]: - """Check if a username is available - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[UsernameCheckResponse] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, - body: ChangeUsernameRequest, -) -> UsernameCheckResponse | None: - """Check if a username is available - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - UsernameCheckResponse - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/account_email_verify.py b/openshock/rest/api/account/account_email_verify.py deleted file mode 100644 index d2c68ab..0000000 --- a/openshock/rest/api/account/account_email_verify.py +++ /dev/null @@ -1,170 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - token: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["token"] = token - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/email-change/verify", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Response[Any | OpenShockProblem]: - """Verify a pending email change using the token from the verification email. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token=token, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Any | OpenShockProblem | None: - """Verify a pending email change using the token from the verification email. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - token=token, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Response[Any | OpenShockProblem]: - """Verify a pending email change using the token from the verification email. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token=token, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Any | OpenShockProblem | None: - """Verify a pending email change using the token from the verification email. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - token=token, - ) - ).parsed diff --git a/openshock/rest/api/account/account_email_verify_legacy.py b/openshock/rest/api/account/account_email_verify_legacy.py deleted file mode 100644 index a74c0d2..0000000 --- a/openshock/rest/api/account/account_email_verify_legacy.py +++ /dev/null @@ -1,170 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - token: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["token"] = token - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/verify-email", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Response[Any | OpenShockProblem]: - """Verify a pending email change. Deprecated: use POST /email-change/verify instead. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token=token, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Any | OpenShockProblem | None: - """Verify a pending email change. Deprecated: use POST /email-change/verify instead. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - token=token, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Response[Any | OpenShockProblem]: - """Verify a pending email change. Deprecated: use POST /email-change/verify instead. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - token=token, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, - token: str | Unset = UNSET, -) -> Any | OpenShockProblem | None: - """Verify a pending email change. Deprecated: use POST /email-change/verify instead. - - Args: - token (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - token=token, - ) - ).parsed diff --git a/openshock/rest/api/account/account_login_v2.py b/openshock/rest/api/account/account_login_v2.py deleted file mode 100644 index c98fee0..0000000 --- a/openshock/rest/api/account/account_login_v2.py +++ /dev/null @@ -1,172 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.login_v2 import LoginV2 -from ...models.login_v2_ok_response import LoginV2OkResponse -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: LoginV2, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/2/account/login", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LoginV2OkResponse | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LoginV2OkResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = OpenShockProblem.from_dict(response.json()) - - return response_401 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LoginV2OkResponse | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, - body: LoginV2, -) -> Response[LoginV2OkResponse | OpenShockProblem]: - """Authenticate a user - - Args: - body (LoginV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LoginV2OkResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, - body: LoginV2, -) -> LoginV2OkResponse | OpenShockProblem | None: - """Authenticate a user - - Args: - body (LoginV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LoginV2OkResponse | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, - body: LoginV2, -) -> Response[LoginV2OkResponse | OpenShockProblem]: - """Authenticate a user - - Args: - body (LoginV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LoginV2OkResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, - body: LoginV2, -) -> LoginV2OkResponse | OpenShockProblem | None: - """Authenticate a user - - Args: - body (LoginV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LoginV2OkResponse | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/account_logout.py b/openshock/rest/api/account/account_logout.py deleted file mode 100644 index 606552a..0000000 --- a/openshock/rest/api/account/account_logout.py +++ /dev/null @@ -1,80 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/logout", - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, -) -> Response[Any]: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, -) -> Response[Any]: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/account/account_password_reset_check_valid.py b/openshock/rest/api/account/account_password_reset_check_valid.py deleted file mode 100644 index 16d1ce2..0000000 --- a/openshock/rest/api/account/account_password_reset_check_valid.py +++ /dev/null @@ -1,177 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_empty_response import LegacyEmptyResponse -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - password_reset_id: UUID, - secret: str, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/account/password-reset/{password_reset_id}/{secret}".format( - password_reset_id=quote(str(password_reset_id), safe=""), - secret=quote(str(secret), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LegacyEmptyResponse | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LegacyEmptyResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - password_reset_id: UUID, - secret: str, - *, - client: AuthenticatedClient | Client, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Check if a password reset is in progress - - Args: - password_reset_id (UUID): - secret (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - password_reset_id=password_reset_id, - secret=secret, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - password_reset_id: UUID, - secret: str, - *, - client: AuthenticatedClient | Client, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Check if a password reset is in progress - - Args: - password_reset_id (UUID): - secret (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyEmptyResponse | OpenShockProblem - """ - - return sync_detailed( - password_reset_id=password_reset_id, - secret=secret, - client=client, - ).parsed - - -async def asyncio_detailed( - password_reset_id: UUID, - secret: str, - *, - client: AuthenticatedClient | Client, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Check if a password reset is in progress - - Args: - password_reset_id (UUID): - secret (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - password_reset_id=password_reset_id, - secret=secret, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - password_reset_id: UUID, - secret: str, - *, - client: AuthenticatedClient | Client, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Check if a password reset is in progress - - Args: - password_reset_id (UUID): - secret (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyEmptyResponse | OpenShockProblem - """ - - return ( - await asyncio_detailed( - password_reset_id=password_reset_id, - secret=secret, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/account/account_password_reset_initiate_v2.py b/openshock/rest/api/account/account_password_reset_initiate_v2.py deleted file mode 100644 index 8d0fe30..0000000 --- a/openshock/rest/api/account/account_password_reset_initiate_v2.py +++ /dev/null @@ -1,165 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.password_reset_request_v2 import PasswordResetRequestV2 -from ...types import Response - - -def _get_kwargs( - *, - body: PasswordResetRequestV2, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/2/account/password-reset", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, - body: PasswordResetRequestV2, -) -> Response[Any | OpenShockProblem]: - """Initiate a password reset - - Args: - body (PasswordResetRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, - body: PasswordResetRequestV2, -) -> Any | OpenShockProblem | None: - """Initiate a password reset - - Args: - body (PasswordResetRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, - body: PasswordResetRequestV2, -) -> Response[Any | OpenShockProblem]: - """Initiate a password reset - - Args: - body (PasswordResetRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, - body: PasswordResetRequestV2, -) -> Any | OpenShockProblem | None: - """Initiate a password reset - - Args: - body (PasswordResetRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/account_resend_activation.py b/openshock/rest/api/account/account_resend_activation.py deleted file mode 100644 index ee3eeb3..0000000 --- a/openshock/rest/api/account/account_resend_activation.py +++ /dev/null @@ -1,154 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/activate/resend", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 429: - response_429 = OpenShockProblem.from_dict(response.json()) - - return response_429 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, -) -> Response[Any | OpenShockProblem]: - """Resend the account activation email for the account this browser just signed up - - Identifies the account by the activation-resend cookie set on signup, not by an email address, - so it can only target an account created from this browser and can't be used to probe registered - emails. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, -) -> Any | OpenShockProblem | None: - """Resend the account activation email for the account this browser just signed up - - Identifies the account by the activation-resend cookie set on signup, not by an email address, - so it can only target an account created from this browser and can't be used to probe registered - emails. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, -) -> Response[Any | OpenShockProblem]: - """Resend the account activation email for the account this browser just signed up - - Identifies the account by the activation-resend cookie set on signup, not by an email address, - so it can only target an account created from this browser and can't be used to probe registered - emails. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, -) -> Any | OpenShockProblem | None: - """Resend the account activation email for the account this browser just signed up - - Identifies the account by the activation-resend cookie set on signup, not by an email address, - so it can only target an account created from this browser and can't be used to probe registered - emails. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/account/account_sign_up_v2.py b/openshock/rest/api/account/account_sign_up_v2.py deleted file mode 100644 index 587653c..0000000 --- a/openshock/rest/api/account/account_sign_up_v2.py +++ /dev/null @@ -1,174 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.sign_up_v2 import SignUpV2 -from ...types import Response - - -def _get_kwargs( - *, - body: SignUpV2, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/2/account/signup", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = cast(Any, None) - return response_400 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient | Client, - body: SignUpV2, -) -> Response[Any | OpenShockProblem]: - """Signs up a new user - - Args: - body (SignUpV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient | Client, - body: SignUpV2, -) -> Any | OpenShockProblem | None: - """Signs up a new user - - Args: - body (SignUpV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient | Client, - body: SignUpV2, -) -> Response[Any | OpenShockProblem]: - """Signs up a new user - - Args: - body (SignUpV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient | Client, - body: SignUpV2, -) -> Any | OpenShockProblem | None: - """Signs up a new user - - Args: - body (SignUpV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_password.py b/openshock/rest/api/account/authenticated_account_change_password.py deleted file mode 100644 index 278a24f..0000000 --- a/openshock/rest/api/account/authenticated_account_change_password.py +++ /dev/null @@ -1,170 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.change_password_request import ChangePasswordRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ChangePasswordRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/password", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Response[Any | OpenShockProblem]: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Any | OpenShockProblem | None: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Response[Any | OpenShockProblem]: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ChangePasswordRequest, -) -> Any | OpenShockProblem | None: - """Change the password of the current user - - Args: - body (ChangePasswordRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_username.py b/openshock/rest/api/account/authenticated_account_change_username.py deleted file mode 100644 index 4f5f5c2..0000000 --- a/openshock/rest/api/account/authenticated_account_change_username.py +++ /dev/null @@ -1,175 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.change_username_request import ChangeUsernameRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ChangeUsernameRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/username", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Response[Any | OpenShockProblem]: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Any | OpenShockProblem | None: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Response[Any | OpenShockProblem]: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ChangeUsernameRequest, -) -> Any | OpenShockProblem | None: - """Change the username of the current user - - Args: - body (ChangeUsernameRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_deactivate.py b/openshock/rest/api/account/authenticated_account_deactivate.py deleted file mode 100644 index 1c590a1..0000000 --- a/openshock/rest/api/account/authenticated_account_deactivate.py +++ /dev/null @@ -1,133 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/account", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 204: - response_204 = cast(Any, None) - return response_204 - - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deactivate currently logged in account - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_get_audit_log.py b/openshock/rest/api/account/authenticated_account_get_audit_log.py deleted file mode 100644 index 36ca1f4..0000000 --- a/openshock/rest/api/account/authenticated_account_get_audit_log.py +++ /dev/null @@ -1,226 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse -from ...models.sort_direction import SortDirection -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["page"] = page - - params["pageSize"] = page_size - - params["search"] = search - - params["sort"] = sort - - json_sort_dir: str | Unset = UNSET - if not isinstance(sort_dir, Unset): - json_sort_dir = sort_dir.value - - params["sortDir"] = json_sort_dir - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/account/audit-log", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> PagedResultOfAuditLogEntryResponse | None: - if response.status_code == 200: - response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[PagedResultOfAuditLogEntryResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return sync_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get the audit log for the current user's account. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return ( - await asyncio_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py b/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py deleted file mode 100644 index 4bed30e..0000000 --- a/openshock/rest/api/account/authenticated_account_list_o_auth_connections.py +++ /dev/null @@ -1,134 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.o_auth_connection_response import OAuthConnectionResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/account/connections", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[OAuthConnectionResponse] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = OAuthConnectionResponse.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[OAuthConnectionResponse]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[OAuthConnectionResponse]]: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[OAuthConnectionResponse]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[OAuthConnectionResponse] | None: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[OAuthConnectionResponse] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[OAuthConnectionResponse]]: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[OAuthConnectionResponse]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[OAuthConnectionResponse] | None: - """List OAuth connections linked to the current user. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[OAuthConnectionResponse] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py b/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py deleted file mode 100644 index d91c1ca..0000000 --- a/openshock/rest/api/account/authenticated_account_remove_o_auth_connection.py +++ /dev/null @@ -1,158 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - provider: str, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/account/connections/{provider}".format( - provider=quote(str(provider), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 204: - response_204 = cast(Any, None) - return response_204 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - provider: str, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - provider=provider, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - provider: str, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - provider=provider, - client=client, - ).parsed - - -async def asyncio_detailed( - provider: str, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - provider=provider, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - provider: str, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Remove an existing OAuth connection for the current user. - - Args: - provider (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - provider=provider, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/__init__.py b/openshock/rest/api/admin/__init__.py deleted file mode 100644 index 181fdd9..0000000 --- a/openshock/rest/api/admin/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/admin/admin_add_email_provider_blacklist.py b/openshock/rest/api/admin/admin_add_email_provider_blacklist.py deleted file mode 100644 index 2dcec86..0000000 --- a/openshock/rest/api/admin/admin_add_email_provider_blacklist.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto -from ...types import Response - - -def _get_kwargs( - *, - body: AddEmailProviderBlacklistDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/blacklist/emailProviders", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: AddEmailProviderBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddEmailProviderBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: AddEmailProviderBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddEmailProviderBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_username_blacklist.py b/openshock/rest/api/admin/admin_add_username_blacklist.py deleted file mode 100644 index c5fbddb..0000000 --- a/openshock/rest/api/admin/admin_add_username_blacklist.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.add_username_blacklist_dto import AddUsernameBlacklistDto -from ...types import Response - - -def _get_kwargs( - *, - body: AddUsernameBlacklistDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/blacklist/usernames", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: AddUsernameBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddUsernameBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: AddUsernameBlacklistDto, -) -> Response[Any]: - """ - Args: - body (AddUsernameBlacklistDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_add_webhook.py b/openshock/rest/api/admin/admin_add_webhook.py deleted file mode 100644 index 833d05d..0000000 --- a/openshock/rest/api/admin/admin_add_webhook.py +++ /dev/null @@ -1,167 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.add_webhook_dto import AddWebhookDto -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - *, - body: AddWebhookDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/webhooks", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = ProblemDetails.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Response[Any | ProblemDetails]: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Any | ProblemDetails | None: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Response[Any | ProblemDetails]: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: AddWebhookDto, -) -> Any | ProblemDetails | None: - """Creates a webhook - - Args: - body (AddWebhookDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py b/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py deleted file mode 100644 index a4c511e..0000000 --- a/openshock/rest/api/admin/admin_bulk_cancel_email_outbox.py +++ /dev/null @@ -1,177 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest -from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from ...types import Response - - -def _get_kwargs( - *, - body: EmailOutboxBulkRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/bulk/cancel", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxBulkResultDto | None: - if response.status_code == 200: - response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxBulkResultDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Cancels many still-pending email outbox messages at once by marking them skipped. Rows that are - not pending (already sending or terminal) and missing ids are skipped. Returns how many rows were - actually cancelled. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py b/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py deleted file mode 100644 index 775933d..0000000 --- a/openshock/rest/api/admin/admin_bulk_delete_email_outbox.py +++ /dev/null @@ -1,173 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest -from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from ...types import Response - - -def _get_kwargs( - *, - body: EmailOutboxBulkRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/bulk/delete", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxBulkResultDto | None: - if response.status_code == 200: - response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxBulkResultDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Permanently deletes many email outbox messages at once. Missing ids are skipped. Returns how many - rows were actually deleted. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py b/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py deleted file mode 100644 index 5e3f3ed..0000000 --- a/openshock/rest/api/admin/admin_bulk_requeue_email_outbox.py +++ /dev/null @@ -1,177 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_bulk_request import EmailOutboxBulkRequest -from ...models.email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from ...types import Response - - -def _get_kwargs( - *, - body: EmailOutboxBulkRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/bulk/requeue", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxBulkResultDto | None: - if response.status_code == 200: - response_200 = EmailOutboxBulkResultDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxBulkResultDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Response[Any | EmailOutboxBulkResultDto]: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxBulkResultDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: EmailOutboxBulkRequest, -) -> Any | EmailOutboxBulkResultDto | None: - """Requeues many email outbox messages at once. Each id is treated exactly like the single-message - requeue: only terminal (sent/failed/skipped) rows are affected; pending/sending rows and missing - ids are skipped. Returns how many rows were actually requeued. - - Args: - body (EmailOutboxBulkRequest): A set of email outbox message ids to apply a bulk - requeue/cancel/delete to. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxBulkResultDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_cancel_email_outbox.py b/openshock/rest/api/admin/admin_cancel_email_outbox.py deleted file mode 100644 index 6257ab1..0000000 --- a/openshock/rest/api/admin/admin_cancel_email_outbox.py +++ /dev/null @@ -1,172 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/{id}/cancel".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = ProblemDetails.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Cancels a still-pending email outbox message by marking it skipped, so it is never sent. Only - pending messages can be cancelled; a message already being sent or in a terminal state cannot. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_add.py b/openshock/rest/api/admin/admin_configuration_add.py deleted file mode 100644 index 4347d91..0000000 --- a/openshock/rest/api/admin/admin_configuration_add.py +++ /dev/null @@ -1,174 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.configuration_add_item_request import ConfigurationAddItemRequest -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - *, - body: ConfigurationAddItemRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/config", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Response[Any | OpenShockProblem]: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Any | OpenShockProblem | None: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Response[Any | OpenShockProblem]: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: ConfigurationAddItemRequest, -) -> Any | OpenShockProblem | None: - """Adds a new configuration - - Args: - body (ConfigurationAddItemRequest): Request DTO for adding a new configuration item. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_delete.py b/openshock/rest/api/admin/admin_configuration_delete.py deleted file mode 100644 index 7161385..0000000 --- a/openshock/rest/api/admin/admin_configuration_delete.py +++ /dev/null @@ -1,169 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - name: str, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/config/{name}".format( - name=quote(str(name), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - name: str, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - name=name, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - name: str, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - name=name, - client=client, - ).parsed - - -async def asyncio_detailed( - name: str, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - name=name, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - name: str, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """Deletes a configuration - - Args: - name (str): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - name=name, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_configuration_list.py b/openshock/rest/api/admin/admin_configuration_list.py deleted file mode 100644 index 39dc4fd..0000000 --- a/openshock/rest/api/admin/admin_configuration_list.py +++ /dev/null @@ -1,138 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.configuration_item_dto import ConfigurationItemDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/config", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | list[ConfigurationItemDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = ConfigurationItemDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | list[ConfigurationItemDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[ConfigurationItemDto]]: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[ConfigurationItemDto]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | list[ConfigurationItemDto] | None: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[ConfigurationItemDto] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[ConfigurationItemDto]]: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[ConfigurationItemDto]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | list[ConfigurationItemDto] | None: - """Gets all configuration items - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[ConfigurationItemDto] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_create_automation_token.py b/openshock/rest/api/admin/admin_create_automation_token.py deleted file mode 100644 index 8ebddfe..0000000 --- a/openshock/rest/api/admin/admin_create_automation_token.py +++ /dev/null @@ -1,161 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.create_automation_token_dto import CreateAutomationTokenDto -from ...models.created_automation_token_dto import CreatedAutomationTokenDto -from ...types import Response - - -def _get_kwargs( - *, - body: CreateAutomationTokenDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/automationTokens", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> CreatedAutomationTokenDto | None: - if response.status_code == 200: - response_200 = CreatedAutomationTokenDto.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[CreatedAutomationTokenDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> Response[CreatedAutomationTokenDto]: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> CreatedAutomationTokenDto | None: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> Response[CreatedAutomationTokenDto]: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: CreateAutomationTokenDto, -) -> CreatedAutomationTokenDto | None: - """Creates an automation token. The secret is only returned once, in this response - - Args: - body (CreateAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_deactivate_user.py b/openshock/rest/api/admin/admin_deactivate_user.py deleted file mode 100644 index fb92e0d..0000000 --- a/openshock/rest/api/admin/admin_deactivate_user.py +++ /dev/null @@ -1,127 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - user_id: UUID, - *, - delete_later: bool | Unset = UNSET, - reason: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["deleteLater"] = delete_later - - params["reason"] = reason - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/deactivate".format( - user_id=quote(str(user_id), safe=""), - ), - "params": params, - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - delete_later: bool | Unset = UNSET, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deactivates a user - - Args: - user_id (UUID): - delete_later (bool | Unset): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - delete_later=delete_later, - reason=reason, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - delete_later: bool | Unset = UNSET, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deactivates a user - - Args: - user_id (UUID): - delete_later (bool | Unset): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - delete_later=delete_later, - reason=reason, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_api_token.py b/openshock/rest/api/admin/admin_delete_api_token.py deleted file mode 100644 index aa2c018..0000000 --- a/openshock/rest/api/admin/admin_delete_api_token.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import Response - - -def _get_kwargs( - token_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/apitokens/{token_id}".format( - token_id=quote(str(token_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any]: - """Deletes an API token - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - token_id=token_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - token_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any]: - """Deletes an API token - - Args: - token_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - token_id=token_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_delete_automation_token.py b/openshock/rest/api/admin/admin_delete_automation_token.py deleted file mode 100644 index 0bc899c..0000000 --- a/openshock/rest/api/admin/admin_delete_automation_token.py +++ /dev/null @@ -1,168 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/automationTokens/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = ProblemDetails.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Deletes an automation token together with every account it created. Refused while any of those - accounts holds a privileged role - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_delete_email_outbox.py b/openshock/rest/api/admin/admin_delete_email_outbox.py deleted file mode 100644 index 6a9034d..0000000 --- a/openshock/rest/api/admin/admin_delete_email_outbox.py +++ /dev/null @@ -1,167 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/email/outbox/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Permanently deletes an email outbox message. If the delivery consumer is mid-send it simply finds - the row gone and does nothing, so a delete never corrupts an in-flight send. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_delete_user.py b/openshock/rest/api/admin/admin_delete_user.py deleted file mode 100644 index 4de0110..0000000 --- a/openshock/rest/api/admin/admin_delete_user.py +++ /dev/null @@ -1,118 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - user_id: UUID, - *, - reason: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["reason"] = reason - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/users/{user_id}".format( - user_id=quote(str(user_id), safe=""), - ), - "params": params, - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deletes a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Deletes a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_get_admin_audit_log.py b/openshock/rest/api/admin/admin_get_admin_audit_log.py deleted file mode 100644 index 55d480b..0000000 --- a/openshock/rest/api/admin/admin_get_admin_audit_log.py +++ /dev/null @@ -1,263 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse -from ...models.sort_direction import SortDirection -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["page"] = page - - params["pageSize"] = page_size - - params["search"] = search - - params["sort"] = sort - - json_sort_dir: str | Unset = UNSET - if not isinstance(sort_dir, Unset): - json_sort_dir = sort_dir.value - - params["sortDir"] = json_sort_dir - - json_user_id: str | Unset = UNSET - if not isinstance(user_id, Unset): - json_user_id = str(user_id) - params["userId"] = json_user_id - - json_actor_id: str | Unset = UNSET - if not isinstance(actor_id, Unset): - json_actor_id = str(actor_id) - params["actorId"] = json_actor_id - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/audit-log", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> PagedResultOfAuditLogEntryResponse | None: - if response.status_code == 200: - response_200 = PagedResultOfAuditLogEntryResponse.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[PagedResultOfAuditLogEntryResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return sync_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> Response[PagedResultOfAuditLogEntryResponse]: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[PagedResultOfAuditLogEntryResponse] - """ - - kwargs = _get_kwargs( - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - page: int | Unset = UNSET, - page_size: int | Unset = UNSET, - search: str | Unset = UNSET, - sort: str | Unset = UNSET, - sort_dir: SortDirection | Unset = UNSET, - user_id: UUID | Unset = UNSET, - actor_id: UUID | Unset = UNSET, -) -> PagedResultOfAuditLogEntryResponse | None: - """Get audit log entries across all users. Optionally filter by subject user or actor. - - Args: - page (int | Unset): - page_size (int | Unset): - search (str | Unset): - sort (str | Unset): - sort_dir (SortDirection | Unset): Sort direction for list endpoints. - user_id (UUID | Unset): - actor_id (UUID | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - PagedResultOfAuditLogEntryResponse - """ - - return ( - await asyncio_detailed( - client=client, - page=page, - page_size=page_size, - search=search, - sort=sort, - sort_dir=sort_dir, - user_id=user_id, - actor_id=actor_id, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox.py b/openshock/rest/api/admin/admin_get_email_outbox.py deleted file mode 100644 index af7ea09..0000000 --- a/openshock/rest/api/admin/admin_get_email_outbox.py +++ /dev/null @@ -1,218 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["$filter"] = filter_ - - params["$orderby"] = orderby - - params["$offset"] = offset - - params["$limit"] = limit - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/email/outbox", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | PaginatedOfEmailOutboxMessageDto | None: - if response.status_code == 200: - response_200 = PaginatedOfEmailOutboxMessageDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfEmailOutboxMessageDto] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfEmailOutboxMessageDto | None: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfEmailOutboxMessageDto - """ - - return sync_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfEmailOutboxMessageDto]: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfEmailOutboxMessageDto] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfEmailOutboxMessageDto | None: - """Lists email outbox messages, paginated. Supports the same OData-style - `$filter`/`$orderby` as the users listing (e.g. `status eq 'failed'`, - `recipient ilike '%@example.com'`). Defaults to newest first. - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfEmailOutboxMessageDto - """ - - return ( - await asyncio_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_email_outbox_stats.py b/openshock/rest/api/admin/admin_get_email_outbox_stats.py deleted file mode 100644 index 1e97d6d..0000000 --- a/openshock/rest/api/admin/admin_get_email_outbox_stats.py +++ /dev/null @@ -1,133 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_stats_dto import EmailOutboxStatsDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/email/outbox/stats", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxStatsDto | None: - if response.status_code == 200: - response_200 = EmailOutboxStatsDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxStatsDto]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | EmailOutboxStatsDto]: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxStatsDto] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | EmailOutboxStatsDto | None: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxStatsDto - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | EmailOutboxStatsDto]: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxStatsDto] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | EmailOutboxStatsDto | None: - """Returns the number of email outbox messages in each delivery state. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxStatsDto - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_devices.py b/openshock/rest/api/admin/admin_get_online_devices.py deleted file mode 100644 index 038a002..0000000 --- a/openshock/rest/api/admin/admin_get_online_devices.py +++ /dev/null @@ -1,135 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_data_response_of_array_of_admin_online_device_response import ( - LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, -) -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/monitoring/onlineDevices", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: - if response.status_code == 200: - response_200 = LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse]: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse | None: - """Gets all online devices - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_online_gateways.py b/openshock/rest/api/admin/admin_get_online_gateways.py deleted file mode 100644 index 8e655a1..0000000 --- a/openshock/rest/api/admin/admin_get_online_gateways.py +++ /dev/null @@ -1,138 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.admin_online_gateway_response import AdminOnlineGatewayResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/monitoring/gateways", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | list[AdminOnlineGatewayResponse] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = AdminOnlineGatewayResponse.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | list[AdminOnlineGatewayResponse]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[AdminOnlineGatewayResponse]]: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[AdminOnlineGatewayResponse]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | list[AdminOnlineGatewayResponse] | None: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[AdminOnlineGatewayResponse] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[AdminOnlineGatewayResponse]]: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[AdminOnlineGatewayResponse]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | list[AdminOnlineGatewayResponse] | None: - """Gets all online gateways - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[AdminOnlineGatewayResponse] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_user_by_id.py b/openshock/rest/api/admin/admin_get_user_by_id.py deleted file mode 100644 index 0cdfef5..0000000 --- a/openshock/rest/api/admin/admin_get_user_by_id.py +++ /dev/null @@ -1,167 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.admin_user_view import AdminUserView -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - user_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/users/{user_id}".format( - user_id=quote(str(user_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> AdminUserView | Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = AdminUserView.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[AdminUserView | Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[AdminUserView | Any | ProblemDetails]: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AdminUserView | Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> AdminUserView | Any | ProblemDetails | None: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AdminUserView | Any | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[AdminUserView | Any | ProblemDetails]: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AdminUserView | Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, -) -> AdminUserView | Any | ProblemDetails | None: - """Gets a user by id - - Args: - user_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AdminUserView | Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_get_users.py b/openshock/rest/api/admin/admin_get_users.py deleted file mode 100644 index 87e1045..0000000 --- a/openshock/rest/api/admin/admin_get_users.py +++ /dev/null @@ -1,210 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.paginated_of_admin_users_view import PaginatedOfAdminUsersView -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["$filter"] = filter_ - - params["$orderby"] = orderby - - params["$offset"] = offset - - params["$limit"] = limit - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/users", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | PaginatedOfAdminUsersView | None: - if response.status_code == 200: - response_200 = PaginatedOfAdminUsersView.from_dict(response.json()) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | PaginatedOfAdminUsersView]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfAdminUsersView]: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfAdminUsersView] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfAdminUsersView | None: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfAdminUsersView - """ - - return sync_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Response[Any | PaginatedOfAdminUsersView]: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | PaginatedOfAdminUsersView] - """ - - kwargs = _get_kwargs( - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - filter_: str | Unset = "", - orderby: str | Unset = "", - offset: int | Unset = 0, - limit: int | Unset = 100, -) -> Any | PaginatedOfAdminUsersView | None: - """Gets all users, paginated - - Args: - filter_ (str | Unset): Default: ''. - orderby (str | Unset): Default: ''. - offset (int | Unset): Default: 0. - limit (int | Unset): Default: 100. - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | PaginatedOfAdminUsersView - """ - - return ( - await asyncio_detailed( - client=client, - filter_=filter_, - orderby=orderby, - offset=offset, - limit=limit, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_automation_tokens.py b/openshock/rest/api/admin/admin_list_automation_tokens.py deleted file mode 100644 index 23171a0..0000000 --- a/openshock/rest/api/admin/admin_list_automation_tokens.py +++ /dev/null @@ -1,134 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.automation_token_dto import AutomationTokenDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/automationTokens", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[AutomationTokenDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = AutomationTokenDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[AutomationTokenDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[AutomationTokenDto]]: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[AutomationTokenDto]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[AutomationTokenDto] | None: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[AutomationTokenDto] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[AutomationTokenDto]]: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[AutomationTokenDto]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[AutomationTokenDto] | None: - """Lists all automation tokens - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[AutomationTokenDto] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_email_provider_blacklist.py b/openshock/rest/api/admin/admin_list_email_provider_blacklist.py deleted file mode 100644 index f6011ba..0000000 --- a/openshock/rest/api/admin/admin_list_email_provider_blacklist.py +++ /dev/null @@ -1,162 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_provider_blacklist_dto import EmailProviderBlacklistDto -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - match: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["match"] = match - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/blacklist/emailProviders", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[EmailProviderBlacklistDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = EmailProviderBlacklistDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[EmailProviderBlacklistDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[EmailProviderBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[EmailProviderBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[EmailProviderBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[EmailProviderBlacklistDto] - """ - - return sync_detailed( - client=client, - match=match, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[EmailProviderBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[EmailProviderBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[EmailProviderBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[EmailProviderBlacklistDto] - """ - - return ( - await asyncio_detailed( - client=client, - match=match, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_username_blacklist.py b/openshock/rest/api/admin/admin_list_username_blacklist.py deleted file mode 100644 index c1f1b45..0000000 --- a/openshock/rest/api/admin/admin_list_username_blacklist.py +++ /dev/null @@ -1,162 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.user_name_blacklist_dto import UserNameBlacklistDto -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - *, - match: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["match"] = match - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/blacklist/usernames", - "params": params, - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[UserNameBlacklistDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = UserNameBlacklistDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[UserNameBlacklistDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[UserNameBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[UserNameBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[UserNameBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[UserNameBlacklistDto] - """ - - return sync_detailed( - client=client, - match=match, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> Response[list[UserNameBlacklistDto]]: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[UserNameBlacklistDto]] - """ - - kwargs = _get_kwargs( - match=match, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - match: str | Unset = UNSET, -) -> list[UserNameBlacklistDto] | None: - """ - Args: - match (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[UserNameBlacklistDto] - """ - - return ( - await asyncio_detailed( - client=client, - match=match, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_list_webhooks.py b/openshock/rest/api/admin/admin_list_webhooks.py deleted file mode 100644 index 87efc54..0000000 --- a/openshock/rest/api/admin/admin_list_webhooks.py +++ /dev/null @@ -1,138 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.webhook_dto import WebhookDto -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/admin/webhooks", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | list[WebhookDto] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = WebhookDto.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | list[WebhookDto]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[WebhookDto]]: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[WebhookDto]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> Any | list[WebhookDto] | None: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[WebhookDto] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[Any | list[WebhookDto]]: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | list[WebhookDto]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> Any | list[WebhookDto] | None: - """List webhooks - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | list[WebhookDto] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_modify_user.py b/openshock/rest/api/admin/admin_modify_user.py deleted file mode 100644 index fa09ec9..0000000 --- a/openshock/rest/api/admin/admin_modify_user.py +++ /dev/null @@ -1,121 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.user_patch_dto import UserPatchDto -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: UserPatchDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/1/admin/users/{user_id}".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if response.status_code == 404: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: UserPatchDto, -) -> Response[Any]: - """Edits a user - - Args: - user_id (UUID): - body (UserPatchDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: UserPatchDto, -) -> Response[Any]: - """Edits a user - - Args: - user_id (UUID): - body (UserPatchDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_patch_automation_token.py b/openshock/rest/api/admin/admin_patch_automation_token.py deleted file mode 100644 index 53798c1..0000000 --- a/openshock/rest/api/admin/admin_patch_automation_token.py +++ /dev/null @@ -1,184 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.automation_token_dto import AutomationTokenDto -from ...models.patch_automation_token_dto import PatchAutomationTokenDto -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, - *, - body: PatchAutomationTokenDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/1/admin/automationTokens/{id}".format( - id=quote(str(id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> AutomationTokenDto | ProblemDetails | None: - if response.status_code == 200: - response_200 = AutomationTokenDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[AutomationTokenDto | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> Response[AutomationTokenDto | ProblemDetails]: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> AutomationTokenDto | ProblemDetails | None: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AutomationTokenDto | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> Response[AutomationTokenDto | ProblemDetails]: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[AutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, - body: PatchAutomationTokenDto, -) -> AutomationTokenDto | ProblemDetails | None: - """Updates an automation token - - Args: - id (UUID): - body (PatchAutomationTokenDto): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - AutomationTokenDto | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_reactivate_user.py b/openshock/rest/api/admin/admin_reactivate_user.py deleted file mode 100644 index 8a950b1..0000000 --- a/openshock/rest/api/admin/admin_reactivate_user.py +++ /dev/null @@ -1,118 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...types import UNSET, Response, Unset - - -def _get_kwargs( - user_id: UUID, - *, - reason: str | Unset = UNSET, -) -> dict[str, Any]: - - params: dict[str, Any] = {} - - params["reason"] = reason - - params = {k: v for k, v in params.items() if v is not UNSET and v is not None} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/reactivate".format( - user_id=quote(str(user_id), safe=""), - ), - "params": params, - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if response.status_code == 401: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Reactivates a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - reason: str | Unset = UNSET, -) -> Response[Any]: - """Reactivates a user - - Args: - user_id (UUID): - reason (str | Unset): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - user_id=user_id, - reason=reason, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py b/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py deleted file mode 100644 index e38dd29..0000000 --- a/openshock/rest/api/admin/admin_remove_email_provider_blacklist.py +++ /dev/null @@ -1,155 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/blacklist/emailProviders/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_remove_username_blacklist.py b/openshock/rest/api/admin/admin_remove_username_blacklist.py deleted file mode 100644 index c019ba9..0000000 --- a/openshock/rest/api/admin/admin_remove_username_blacklist.py +++ /dev/null @@ -1,155 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/blacklist/usernames/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """ - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_remove_webhook.py b/openshock/rest/api/admin/admin_remove_webhook.py deleted file mode 100644 index 3248192..0000000 --- a/openshock/rest/api/admin/admin_remove_webhook.py +++ /dev/null @@ -1,163 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/admin/webhooks/{id}".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Removes a webhook - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_requeue_email_outbox.py b/openshock/rest/api/admin/admin_requeue_email_outbox.py deleted file mode 100644 index 4922023..0000000 --- a/openshock/rest/api/admin/admin_requeue_email_outbox.py +++ /dev/null @@ -1,172 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/outbox/{id}/requeue".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = ProblemDetails.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | ProblemDetails]: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> Any | ProblemDetails | None: - """Requeues a terminal (sent/failed/skipped) email outbox message: resets it to pending, due now, - with a fresh attempt budget, and nudges the delivery consumer to send it immediately. - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_rotate_automation_token.py b/openshock/rest/api/admin/admin_rotate_automation_token.py deleted file mode 100644 index 38a1b67..0000000 --- a/openshock/rest/api/admin/admin_rotate_automation_token.py +++ /dev/null @@ -1,163 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.created_automation_token_dto import CreatedAutomationTokenDto -from ...models.problem_details import ProblemDetails -from ...types import Response - - -def _get_kwargs( - id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/automationTokens/{id}/rotate".format( - id=quote(str(id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> CreatedAutomationTokenDto | ProblemDetails | None: - if response.status_code == 200: - response_200 = CreatedAutomationTokenDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[CreatedAutomationTokenDto | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[CreatedAutomationTokenDto | ProblemDetails]: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - id: UUID, - *, - client: AuthenticatedClient, -) -> CreatedAutomationTokenDto | ProblemDetails | None: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto | ProblemDetails - """ - - return sync_detailed( - id=id, - client=client, - ).parsed - - -async def asyncio_detailed( - id: UUID, - *, - client: AuthenticatedClient, -) -> Response[CreatedAutomationTokenDto | ProblemDetails]: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[CreatedAutomationTokenDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - id=id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - id: UUID, - *, - client: AuthenticatedClient, -) -> CreatedAutomationTokenDto | ProblemDetails | None: - """Rotates the secret of an automation token. The new secret is only returned once, in this response - - Args: - id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - CreatedAutomationTokenDto | ProblemDetails - """ - - return ( - await asyncio_detailed( - id=id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_send_test_email.py b/openshock/rest/api/admin/admin_send_test_email.py deleted file mode 100644 index 90bf759..0000000 --- a/openshock/rest/api/admin/admin_send_test_email.py +++ /dev/null @@ -1,191 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.email_outbox_message_dto import EmailOutboxMessageDto -from ...models.problem_details import ProblemDetails -from ...models.send_test_email_dto import SendTestEmailDto -from ...types import Response - - -def _get_kwargs( - *, - body: SendTestEmailDto, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/admin/email/test", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | EmailOutboxMessageDto | ProblemDetails | None: - if response.status_code == 200: - response_200 = EmailOutboxMessageDto.from_dict(response.json()) - - return response_200 - - if response.status_code == 400: - response_400 = ProblemDetails.from_dict(response.json()) - - return response_400 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxMessageDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Any | EmailOutboxMessageDto | ProblemDetails | None: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxMessageDto | ProblemDetails - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Response[Any | EmailOutboxMessageDto | ProblemDetails]: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | EmailOutboxMessageDto | ProblemDetails] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: SendTestEmailDto, -) -> Any | EmailOutboxMessageDto | ProblemDetails | None: - """Enqueues a preview/test email of the chosen type to the chosen address. It flows through the - normal durable delivery pipeline - visible in the outbox listing - but is rendered with - placeholder data and a dummy link, so it touches no request row and mints no token. - - Args: - body (SendTestEmailDto): Request to enqueue a preview/test email of a chosen type to a - chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no - request row). - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | EmailOutboxMessageDto | ProblemDetails - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_email.py b/openshock/rest/api/admin/admin_set_user_email.py deleted file mode 100644 index a8fee2d..0000000 --- a/openshock/rest/api/admin/admin_set_user_email.py +++ /dev/null @@ -1,184 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.problem_details import ProblemDetails -from ...models.set_user_email_request_body import SetUserEmailRequestBody -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: SetUserEmailRequestBody, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/email".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Response[Any | ProblemDetails]: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Any | ProblemDetails | None: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Response[Any | ProblemDetails]: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserEmailRequestBody, -) -> Any | ProblemDetails | None: - """Sets a users email to the supplied value - - Args: - user_id (UUID): - body (SetUserEmailRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_name.py b/openshock/rest/api/admin/admin_set_user_name.py deleted file mode 100644 index fc6ff10..0000000 --- a/openshock/rest/api/admin/admin_set_user_name.py +++ /dev/null @@ -1,192 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.problem_details import ProblemDetails -from ...models.set_user_name_request_body import SetUserNameRequestBody -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: SetUserNameRequestBody, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/name".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserNameRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users name to the supplied value - - Args: - user_id (UUID): - body (SetUserNameRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/admin/admin_set_user_password.py b/openshock/rest/api/admin/admin_set_user_password.py deleted file mode 100644 index 60ab728..0000000 --- a/openshock/rest/api/admin/admin_set_user_password.py +++ /dev/null @@ -1,192 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...models.problem_details import ProblemDetails -from ...models.set_user_password_request_body import SetUserPasswordRequestBody -from ...types import Response - - -def _get_kwargs( - user_id: UUID, - *, - body: SetUserPasswordRequestBody, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "put", - "url": "/1/admin/users/{user_id}/password".format( - user_id=quote(str(user_id), safe=""), - ), - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | ProblemDetails | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - - if response.status_code == 404: - response_404 = ProblemDetails.from_dict(response.json()) - - return response_404 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) - - return response_409 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem | ProblemDetails]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return sync_detailed( - user_id=user_id, - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Response[Any | OpenShockProblem | ProblemDetails]: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem | ProblemDetails] - """ - - kwargs = _get_kwargs( - user_id=user_id, - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - user_id: UUID, - *, - client: AuthenticatedClient, - body: SetUserPasswordRequestBody, -) -> Any | OpenShockProblem | ProblemDetails | None: - """Sets a users password to the supplied value - - Args: - user_id (UUID): - body (SetUserPasswordRequestBody): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem | ProblemDetails - """ - - return ( - await asyncio_detailed( - user_id=user_id, - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_create_token_v2.py b/openshock/rest/api/api_tokens/tokens_create_token_v2.py deleted file mode 100644 index 3c43d0b..0000000 --- a/openshock/rest/api/api_tokens/tokens_create_token_v2.py +++ /dev/null @@ -1,161 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.create_token_request_v2 import CreateTokenRequestV2 -from ...models.token_created_response_v2 import TokenCreatedResponseV2 -from ...types import Response - - -def _get_kwargs( - *, - body: CreateTokenRequestV2, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/2/tokens", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> TokenCreatedResponseV2 | None: - if response.status_code == 200: - response_200 = TokenCreatedResponseV2.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[TokenCreatedResponseV2]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> Response[TokenCreatedResponseV2]: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[TokenCreatedResponseV2] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> TokenCreatedResponseV2 | None: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - TokenCreatedResponseV2 - """ - - return sync_detailed( - client=client, - body=body, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> Response[TokenCreatedResponseV2]: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[TokenCreatedResponseV2] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, - body: CreateTokenRequestV2, -) -> TokenCreatedResponseV2 | None: - """Create a new token - - Args: - body (CreateTokenRequestV2): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - TokenCreatedResponseV2 - """ - - return ( - await asyncio_detailed( - client=client, - body=body, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py b/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py deleted file mode 100644 index f0a4125..0000000 --- a/openshock/rest/api/api_tokens/tokens_list_tokens_v2.py +++ /dev/null @@ -1,132 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.token_response_v2 import TokenResponseV2 -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/2/tokens", - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> list[TokenResponseV2] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = TokenResponseV2.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[TokenResponseV2]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[TokenResponseV2]]: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[TokenResponseV2]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[TokenResponseV2] | None: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[TokenResponseV2] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[TokenResponseV2]]: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[TokenResponseV2]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[TokenResponseV2] | None: - """List all tokens for the current user - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[TokenResponseV2] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_report_tokens.py b/openshock/rest/api/api_tokens/tokens_report_tokens.py deleted file mode 100644 index b505c71..0000000 --- a/openshock/rest/api/api_tokens/tokens_report_tokens.py +++ /dev/null @@ -1,104 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.report_tokens_request import ReportTokensRequest -from ...types import Response - - -def _get_kwargs( - *, - body: ReportTokensRequest, -) -> dict[str, Any]: - headers: dict[str, Any] = {} - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/tokens/report", - } - - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - - _kwargs["headers"] = headers - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Any | None: - if response.status_code == 200: - return None - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> Response[Any]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, - body: ReportTokensRequest, -) -> Response[Any]: - """Endpoint to delete potentially compromised api tokens - - Args: - body (ReportTokensRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, - body: ReportTokensRequest, -) -> Response[Any]: - """Endpoint to delete potentially compromised api tokens - - Args: - body (ReportTokensRequest): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any] - """ - - kwargs = _get_kwargs( - body=body, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) diff --git a/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py b/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py deleted file mode 100644 index ce2caf2..0000000 --- a/openshock/rest/api/hub_management/devices_ota_get_ota_update_history.py +++ /dev/null @@ -1,165 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_data_response_of_i_read_only_collection_of_ota_item import ( - LegacyDataResponseOfIReadOnlyCollectionOfOtaItem, -) -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - device_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/devices/{device_id}/ota".format( - device_id=quote(str(device_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LegacyDataResponseOfIReadOnlyCollectionOfOtaItem.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] - """ - - kwargs = _get_kwargs( - device_id=device_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem - """ - - return sync_detailed( - device_id=device_id, - client=client, - ).parsed - - -async def asyncio_detailed( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem]: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem] - """ - - kwargs = _get_kwargs( - device_id=device_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - device_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem | None: - """Gets the OTA update history for a device - - Args: - device_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyDataResponseOfIReadOnlyCollectionOfOtaItem | OpenShockProblem - """ - - return ( - await asyncio_detailed( - device_id=device_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/public_shocker_shares/public_get_public_share.py b/openshock/rest/api/public_shocker_shares/public_get_public_share.py index 300e186..0378d86 100644 --- a/openshock/rest/api/public_shocker_shares/public_get_public_share.py +++ b/openshock/rest/api/public_shocker_shares/public_get_public_share.py @@ -10,12 +10,17 @@ from ...client import AuthenticatedClient, Client from ...models.legacy_data_response_of_public_share_response import LegacyDataResponseOfPublicShareResponse from ...models.open_shock_problem import OpenShockProblem -from ...types import Response +from ...types import UNSET, Response, Unset def _get_kwargs( public_share_id: UUID, + *, + open_shock_public_share_unlock: str | Unset = UNSET, ) -> dict[str, Any]: + headers: dict[str, Any] = {} + if not isinstance(open_shock_public_share_unlock, Unset): + headers["OpenShockPublicShareUnlock"] = open_shock_public_share_unlock _kwargs: dict[str, Any] = { "method": "get", @@ -24,6 +29,7 @@ def _get_kwargs( ), } + _kwargs["headers"] = headers return _kwargs @@ -61,11 +67,13 @@ def sync_detailed( public_share_id: UUID, *, client: AuthenticatedClient | Client, + open_shock_public_share_unlock: str | Unset = UNSET, ) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: """Gets information about a public share. Args: public_share_id (UUID): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -77,6 +85,7 @@ def sync_detailed( kwargs = _get_kwargs( public_share_id=public_share_id, + open_shock_public_share_unlock=open_shock_public_share_unlock, ) response = client.get_httpx_client().request( @@ -90,11 +99,13 @@ def sync( public_share_id: UUID, *, client: AuthenticatedClient | Client, + open_shock_public_share_unlock: str | Unset = UNSET, ) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: """Gets information about a public share. Args: public_share_id (UUID): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -107,6 +118,7 @@ def sync( return sync_detailed( public_share_id=public_share_id, client=client, + open_shock_public_share_unlock=open_shock_public_share_unlock, ).parsed @@ -114,11 +126,13 @@ async def asyncio_detailed( public_share_id: UUID, *, client: AuthenticatedClient | Client, + open_shock_public_share_unlock: str | Unset = UNSET, ) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: """Gets information about a public share. Args: public_share_id (UUID): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -130,6 +144,7 @@ async def asyncio_detailed( kwargs = _get_kwargs( public_share_id=public_share_id, + open_shock_public_share_unlock=open_shock_public_share_unlock, ) response = await client.get_async_httpx_client().request(**kwargs) @@ -141,11 +156,13 @@ async def asyncio( public_share_id: UUID, *, client: AuthenticatedClient | Client, + open_shock_public_share_unlock: str | Unset = UNSET, ) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: """Gets information about a public share. Args: public_share_id (UUID): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -159,5 +176,6 @@ async def asyncio( await asyncio_detailed( public_share_id=public_share_id, client=client, + open_shock_public_share_unlock=open_shock_public_share_unlock, ) ).parsed diff --git a/openshock/rest/api/account/account_password_reset_complete.py b/openshock/rest/api/public_shocker_shares/public_get_public_share_by_slug.py similarity index 50% rename from openshock/rest/api/account/account_password_reset_complete.py rename to openshock/rest/api/public_shocker_shares/public_get_public_share_by_slug.py index 909b8d2..9e4f25d 100644 --- a/openshock/rest/api/account/account_password_reset_complete.py +++ b/openshock/rest/api/public_shocker_shares/public_get_public_share_by_slug.py @@ -2,47 +2,43 @@ from http import HTTPStatus from typing import Any from urllib.parse import quote -from uuid import UUID import httpx2 from ... import errors from ...client import AuthenticatedClient, Client -from ...models.legacy_empty_response import LegacyEmptyResponse +from ...models.legacy_data_response_of_public_share_response import LegacyDataResponseOfPublicShareResponse from ...models.open_shock_problem import OpenShockProblem -from ...models.password_reset_process_data import PasswordResetProcessData -from ...types import Response +from ...types import UNSET, Response, Unset def _get_kwargs( - password_reset_id: UUID, - secret: str, + username: str, + slug: str, *, - body: PasswordResetProcessData, + open_shock_public_share_unlock: str | Unset = UNSET, ) -> dict[str, Any]: headers: dict[str, Any] = {} + if not isinstance(open_shock_public_share_unlock, Unset): + headers["OpenShockPublicShareUnlock"] = open_shock_public_share_unlock _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/account/password-reset/{password_reset_id}/{secret}/complete".format( - password_reset_id=quote(str(password_reset_id), safe=""), - secret=quote(str(secret), safe=""), + "method": "get", + "url": "/1/public/shares/links/by-slug/{username}/{slug}".format( + username=quote(str(username), safe=""), + slug=quote(str(slug), safe=""), ), } - _kwargs["json"] = body.to_dict() - - headers["Content-Type"] = "application/json" - _kwargs["headers"] = headers return _kwargs def _parse_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LegacyEmptyResponse | OpenShockProblem | None: +) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: if response.status_code == 200: - response_200 = LegacyEmptyResponse.from_dict(response.json()) + response_200 = LegacyDataResponseOfPublicShareResponse.from_dict(response.json()) return response_200 @@ -59,7 +55,7 @@ def _parse_response( def _build_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LegacyEmptyResponse | OpenShockProblem]: +) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, @@ -69,31 +65,31 @@ def _build_response( def sync_detailed( - password_reset_id: UUID, - secret: str, + username: str, + slug: str, *, client: AuthenticatedClient | Client, - body: PasswordResetProcessData, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Complete a password reset process + open_shock_public_share_unlock: str | Unset = UNSET, +) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: + """Gets information about a public share by its owner's username and custom slug. Args: - password_reset_id (UUID): - secret (str): - body (PasswordResetProcessData): + username (str): + slug (str): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[LegacyEmptyResponse | OpenShockProblem] + Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem] """ kwargs = _get_kwargs( - password_reset_id=password_reset_id, - secret=secret, - body=body, + username=username, + slug=slug, + open_shock_public_share_unlock=open_shock_public_share_unlock, ) response = client.get_httpx_client().request( @@ -104,61 +100,61 @@ def sync_detailed( def sync( - password_reset_id: UUID, - secret: str, + username: str, + slug: str, *, client: AuthenticatedClient | Client, - body: PasswordResetProcessData, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Complete a password reset process + open_shock_public_share_unlock: str | Unset = UNSET, +) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: + """Gets information about a public share by its owner's username and custom slug. Args: - password_reset_id (UUID): - secret (str): - body (PasswordResetProcessData): + username (str): + slug (str): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - LegacyEmptyResponse | OpenShockProblem + LegacyDataResponseOfPublicShareResponse | OpenShockProblem """ return sync_detailed( - password_reset_id=password_reset_id, - secret=secret, + username=username, + slug=slug, client=client, - body=body, + open_shock_public_share_unlock=open_shock_public_share_unlock, ).parsed async def asyncio_detailed( - password_reset_id: UUID, - secret: str, + username: str, + slug: str, *, client: AuthenticatedClient | Client, - body: PasswordResetProcessData, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Complete a password reset process + open_shock_public_share_unlock: str | Unset = UNSET, +) -> Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem]: + """Gets information about a public share by its owner's username and custom slug. Args: - password_reset_id (UUID): - secret (str): - body (PasswordResetProcessData): + username (str): + slug (str): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[LegacyEmptyResponse | OpenShockProblem] + Response[LegacyDataResponseOfPublicShareResponse | OpenShockProblem] """ kwargs = _get_kwargs( - password_reset_id=password_reset_id, - secret=secret, - body=body, + username=username, + slug=slug, + open_shock_public_share_unlock=open_shock_public_share_unlock, ) response = await client.get_async_httpx_client().request(**kwargs) @@ -167,32 +163,32 @@ async def asyncio_detailed( async def asyncio( - password_reset_id: UUID, - secret: str, + username: str, + slug: str, *, client: AuthenticatedClient | Client, - body: PasswordResetProcessData, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Complete a password reset process + open_shock_public_share_unlock: str | Unset = UNSET, +) -> LegacyDataResponseOfPublicShareResponse | OpenShockProblem | None: + """Gets information about a public share by its owner's username and custom slug. Args: - password_reset_id (UUID): - secret (str): - body (PasswordResetProcessData): + username (str): + slug (str): + open_shock_public_share_unlock (str | Unset): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - LegacyEmptyResponse | OpenShockProblem + LegacyDataResponseOfPublicShareResponse | OpenShockProblem """ return ( await asyncio_detailed( - password_reset_id=password_reset_id, - secret=secret, + username=username, + slug=slug, client=client, - body=body, + open_shock_public_share_unlock=open_shock_public_share_unlock, ) ).parsed diff --git a/openshock/rest/api/account/authenticated_account_change_email.py b/openshock/rest/api/public_shocker_shares/public_unlock_public_share.py similarity index 59% rename from openshock/rest/api/account/authenticated_account_change_email.py rename to openshock/rest/api/public_shocker_shares/public_unlock_public_share.py index 61c9030..e2df6aa 100644 --- a/openshock/rest/api/account/authenticated_account_change_email.py +++ b/openshock/rest/api/public_shocker_shares/public_unlock_public_share.py @@ -1,25 +1,31 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. from http import HTTPStatus -from typing import Any, cast +from typing import Any +from urllib.parse import quote +from uuid import UUID import httpx2 from ... import errors from ...client import AuthenticatedClient, Client -from ...models.change_email_request import ChangeEmailRequest from ...models.open_shock_problem import OpenShockProblem +from ...models.public_share_unlock import PublicShareUnlock +from ...models.public_share_unlock_response import PublicShareUnlockResponse from ...types import Response def _get_kwargs( + public_share_id: UUID, *, - body: ChangeEmailRequest, + body: PublicShareUnlock, ) -> dict[str, Any]: headers: dict[str, Any] = {} _kwargs: dict[str, Any] = { "method": "post", - "url": "/1/account/email-change", + "url": "/1/public/shares/links/{public_share_id}/unlock".format( + public_share_id=quote(str(public_share_id), safe=""), + ), } _kwargs["json"] = body.to_dict() @@ -32,9 +38,10 @@ def _get_kwargs( def _parse_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: +) -> OpenShockProblem | PublicShareUnlockResponse | None: if response.status_code == 200: - response_200 = cast(Any, None) + response_200 = PublicShareUnlockResponse.from_dict(response.json()) + return response_200 if response.status_code == 400: @@ -47,15 +54,10 @@ def _parse_response( return response_401 - if response.status_code == 403: - response_403 = OpenShockProblem.from_dict(response.json()) - - return response_403 - - if response.status_code == 409: - response_409 = OpenShockProblem.from_dict(response.json()) + if response.status_code == 404: + response_404 = OpenShockProblem.from_dict(response.json()) - return response_409 + return response_404 if response.status_code == 429: response_429 = OpenShockProblem.from_dict(response.json()) @@ -70,7 +72,7 @@ def _parse_response( def _build_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: +) -> Response[OpenShockProblem | PublicShareUnlockResponse]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, @@ -80,25 +82,27 @@ def _build_response( def sync_detailed( + public_share_id: UUID, *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Response[Any | OpenShockProblem]: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. + client: AuthenticatedClient | Client, + body: PublicShareUnlock, +) -> Response[OpenShockProblem | PublicShareUnlockResponse]: + """Unlocks a password-protected public share. Args: - body (ChangeEmailRequest): + public_share_id (UUID): + body (PublicShareUnlock): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[Any | OpenShockProblem] + Response[OpenShockProblem | PublicShareUnlockResponse] """ kwargs = _get_kwargs( + public_share_id=public_share_id, body=body, ) @@ -110,50 +114,54 @@ def sync_detailed( def sync( + public_share_id: UUID, *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Any | OpenShockProblem | None: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. + client: AuthenticatedClient | Client, + body: PublicShareUnlock, +) -> OpenShockProblem | PublicShareUnlockResponse | None: + """Unlocks a password-protected public share. Args: - body (ChangeEmailRequest): + public_share_id (UUID): + body (PublicShareUnlock): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Any | OpenShockProblem + OpenShockProblem | PublicShareUnlockResponse """ return sync_detailed( + public_share_id=public_share_id, client=client, body=body, ).parsed async def asyncio_detailed( + public_share_id: UUID, *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Response[Any | OpenShockProblem]: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. + client: AuthenticatedClient | Client, + body: PublicShareUnlock, +) -> Response[OpenShockProblem | PublicShareUnlockResponse]: + """Unlocks a password-protected public share. Args: - body (ChangeEmailRequest): + public_share_id (UUID): + body (PublicShareUnlock): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[Any | OpenShockProblem] + Response[OpenShockProblem | PublicShareUnlockResponse] """ kwargs = _get_kwargs( + public_share_id=public_share_id, body=body, ) @@ -163,26 +171,28 @@ async def asyncio_detailed( async def asyncio( + public_share_id: UUID, *, - client: AuthenticatedClient, - body: ChangeEmailRequest, -) -> Any | OpenShockProblem | None: - """Initiate an email change for the current user. A verification link is sent to the new - address; the change is not applied until that link is opened. + client: AuthenticatedClient | Client, + body: PublicShareUnlock, +) -> OpenShockProblem | PublicShareUnlockResponse | None: + """Unlocks a password-protected public share. Args: - body (ChangeEmailRequest): + public_share_id (UUID): + body (PublicShareUnlock): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Any | OpenShockProblem + OpenShockProblem | PublicShareUnlockResponse """ return ( await asyncio_detailed( + public_share_id=public_share_id, client=client, body=body, ) diff --git a/openshock/rest/api/public_shocker_shares/share_links_create_public_share.py b/openshock/rest/api/public_shocker_shares/share_links_create_public_share.py index 8e7e04b..83bfcc1 100644 --- a/openshock/rest/api/public_shocker_shares/share_links_create_public_share.py +++ b/openshock/rest/api/public_shocker_shares/share_links_create_public_share.py @@ -7,6 +7,7 @@ from ... import errors from ...client import AuthenticatedClient, Client from ...models.legacy_data_response_of_guid import LegacyDataResponseOfGuid +from ...models.open_shock_problem import OpenShockProblem from ...models.public_share_create import PublicShareCreate from ...types import Response @@ -32,12 +33,22 @@ def _get_kwargs( def _parse_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LegacyDataResponseOfGuid | None: +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: if response.status_code == 200: response_200 = LegacyDataResponseOfGuid.from_dict(response.json()) return response_200 + if response.status_code == 400: + response_400 = OpenShockProblem.from_dict(response.json()) + + return response_400 + + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + if client.raise_on_unexpected_status: raise errors.UnexpectedStatus(response.status_code, response.content) else: @@ -46,7 +57,7 @@ def _parse_response( def _build_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LegacyDataResponseOfGuid]: +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, @@ -59,7 +70,7 @@ def sync_detailed( *, client: AuthenticatedClient, body: PublicShareCreate, -) -> Response[LegacyDataResponseOfGuid]: +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: """Create a new public share Args: @@ -70,7 +81,7 @@ def sync_detailed( httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[LegacyDataResponseOfGuid] + Response[LegacyDataResponseOfGuid | OpenShockProblem] """ kwargs = _get_kwargs( @@ -88,7 +99,7 @@ def sync( *, client: AuthenticatedClient, body: PublicShareCreate, -) -> LegacyDataResponseOfGuid | None: +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: """Create a new public share Args: @@ -99,7 +110,7 @@ def sync( httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - LegacyDataResponseOfGuid + LegacyDataResponseOfGuid | OpenShockProblem """ return sync_detailed( @@ -112,7 +123,7 @@ async def asyncio_detailed( *, client: AuthenticatedClient, body: PublicShareCreate, -) -> Response[LegacyDataResponseOfGuid]: +) -> Response[LegacyDataResponseOfGuid | OpenShockProblem]: """Create a new public share Args: @@ -123,7 +134,7 @@ async def asyncio_detailed( httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[LegacyDataResponseOfGuid] + Response[LegacyDataResponseOfGuid | OpenShockProblem] """ kwargs = _get_kwargs( @@ -139,7 +150,7 @@ async def asyncio( *, client: AuthenticatedClient, body: PublicShareCreate, -) -> LegacyDataResponseOfGuid | None: +) -> LegacyDataResponseOfGuid | OpenShockProblem | None: """Create a new public share Args: @@ -150,7 +161,7 @@ async def asyncio( httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - LegacyDataResponseOfGuid + LegacyDataResponseOfGuid | OpenShockProblem """ return ( diff --git a/openshock/rest/api/admin/admin_configuration_update.py b/openshock/rest/api/public_shocker_shares/share_links_edit_public_share.py similarity index 60% rename from openshock/rest/api/admin/admin_configuration_update.py rename to openshock/rest/api/public_shocker_shares/share_links_edit_public_share.py index 93f5294..76a9463 100644 --- a/openshock/rest/api/admin/admin_configuration_update.py +++ b/openshock/rest/api/public_shocker_shares/share_links_edit_public_share.py @@ -1,25 +1,31 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. from http import HTTPStatus -from typing import Any, cast +from typing import Any +from urllib.parse import quote +from uuid import UUID import httpx2 from ... import errors from ...client import AuthenticatedClient, Client -from ...models.configuration_update_item_request import ConfigurationUpdateItemRequest from ...models.open_shock_problem import OpenShockProblem +from ...models.own_public_share_response import OwnPublicShareResponse +from ...models.public_share_edit import PublicShareEdit from ...types import Response def _get_kwargs( + public_share_id: UUID, *, - body: ConfigurationUpdateItemRequest, + body: PublicShareEdit, ) -> dict[str, Any]: headers: dict[str, Any] = {} _kwargs: dict[str, Any] = { "method": "put", - "url": "/1/admin/config", + "url": "/1/shares/links/{public_share_id}".format( + public_share_id=quote(str(public_share_id), safe=""), + ), } _kwargs["json"] = body.to_dict() @@ -32,9 +38,10 @@ def _get_kwargs( def _parse_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: +) -> OpenShockProblem | OwnPublicShareResponse | None: if response.status_code == 200: - response_200 = cast(Any, None) + response_200 = OwnPublicShareResponse.from_dict(response.json()) + return response_200 if response.status_code == 400: @@ -42,10 +49,6 @@ def _parse_response( return response_400 - if response.status_code == 401: - response_401 = cast(Any, None) - return response_401 - if response.status_code == 404: response_404 = OpenShockProblem.from_dict(response.json()) @@ -64,7 +67,7 @@ def _parse_response( def _build_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: +) -> Response[OpenShockProblem | OwnPublicShareResponse]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, @@ -74,27 +77,28 @@ def _build_response( def sync_detailed( + public_share_id: UUID, *, client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Response[Any | OpenShockProblem]: - """Updates an existing configuration + body: PublicShareEdit, +) -> Response[OpenShockProblem | OwnPublicShareResponse]: + """Edit the name, expiry and slug of a public share Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. + public_share_id (UUID): + body (PublicShareEdit): Replaces all editable fields of a public share, null clears the + expiry or slug. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[Any | OpenShockProblem] + Response[OpenShockProblem | OwnPublicShareResponse] """ kwargs = _get_kwargs( + public_share_id=public_share_id, body=body, ) @@ -106,54 +110,56 @@ def sync_detailed( def sync( + public_share_id: UUID, *, client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Any | OpenShockProblem | None: - """Updates an existing configuration + body: PublicShareEdit, +) -> OpenShockProblem | OwnPublicShareResponse | None: + """Edit the name, expiry and slug of a public share Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. + public_share_id (UUID): + body (PublicShareEdit): Replaces all editable fields of a public share, null clears the + expiry or slug. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Any | OpenShockProblem + OpenShockProblem | OwnPublicShareResponse """ return sync_detailed( + public_share_id=public_share_id, client=client, body=body, ).parsed async def asyncio_detailed( + public_share_id: UUID, *, client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Response[Any | OpenShockProblem]: - """Updates an existing configuration + body: PublicShareEdit, +) -> Response[OpenShockProblem | OwnPublicShareResponse]: + """Edit the name, expiry and slug of a public share Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. + public_share_id (UUID): + body (PublicShareEdit): Replaces all editable fields of a public share, null clears the + expiry or slug. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[Any | OpenShockProblem] + Response[OpenShockProblem | OwnPublicShareResponse] """ kwargs = _get_kwargs( + public_share_id=public_share_id, body=body, ) @@ -163,28 +169,29 @@ async def asyncio_detailed( async def asyncio( + public_share_id: UUID, *, client: AuthenticatedClient, - body: ConfigurationUpdateItemRequest, -) -> Any | OpenShockProblem | None: - """Updates an existing configuration + body: PublicShareEdit, +) -> OpenShockProblem | OwnPublicShareResponse | None: + """Edit the name, expiry and slug of a public share Args: - body (ConfigurationUpdateItemRequest): Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? - ConfigurationUpdateItemRequest.Value (or both) may be provided. - If both are null, no update action is performed. + public_share_id (UUID): + body (PublicShareEdit): Replaces all editable fields of a public share, null clears the + expiry or slug. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Any | OpenShockProblem + OpenShockProblem | OwnPublicShareResponse """ return ( await asyncio_detailed( + public_share_id=public_share_id, client=client, body=body, ) diff --git a/openshock/rest/api/api_tokens/tokens_set_token_paused.py b/openshock/rest/api/public_shocker_shares/share_links_set_public_share_password.py similarity index 55% rename from openshock/rest/api/api_tokens/tokens_set_token_paused.py rename to openshock/rest/api/public_shocker_shares/share_links_set_public_share_password.py index feefc15..621386d 100644 --- a/openshock/rest/api/api_tokens/tokens_set_token_paused.py +++ b/openshock/rest/api/public_shocker_shares/share_links_set_public_share_password.py @@ -9,22 +9,22 @@ from ... import errors from ...client import AuthenticatedClient, Client from ...models.open_shock_problem import OpenShockProblem -from ...models.set_token_paused_request import SetTokenPausedRequest -from ...models.token_paused_response import TokenPausedResponse +from ...models.own_public_share_response import OwnPublicShareResponse +from ...models.public_share_password_set import PublicSharePasswordSet from ...types import Response def _get_kwargs( - token_id: UUID, + public_share_id: UUID, *, - body: SetTokenPausedRequest, + body: PublicSharePasswordSet, ) -> dict[str, Any]: headers: dict[str, Any] = {} _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/2/tokens/{token_id}/paused".format( - token_id=quote(str(token_id), safe=""), + "method": "put", + "url": "/1/shares/links/{public_share_id}/password".format( + public_share_id=quote(str(public_share_id), safe=""), ), } @@ -38,9 +38,9 @@ def _get_kwargs( def _parse_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> OpenShockProblem | TokenPausedResponse | None: +) -> OpenShockProblem | OwnPublicShareResponse | None: if response.status_code == 200: - response_200 = TokenPausedResponse.from_dict(response.json()) + response_200 = OwnPublicShareResponse.from_dict(response.json()) return response_200 @@ -57,7 +57,7 @@ def _parse_response( def _build_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[OpenShockProblem | TokenPausedResponse]: +) -> Response[OpenShockProblem | OwnPublicShareResponse]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, @@ -67,27 +67,31 @@ def _build_response( def sync_detailed( - token_id: UUID, + public_share_id: UUID, *, client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> Response[OpenShockProblem | TokenPausedResponse]: - """Set whether a token is paused. A paused token may not send shocker control messages. + body: PublicSharePasswordSet, +) -> Response[OpenShockProblem | OwnPublicShareResponse]: + """Set, change or remove the password of a public share + + Setting or changing the password disconnects everyone currently using the share; they have to enter + the + new one. Removing it keeps them connected. Args: - token_id (UUID): - body (SetTokenPausedRequest): + public_share_id (UUID): + body (PublicSharePasswordSet): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[OpenShockProblem | TokenPausedResponse] + Response[OpenShockProblem | OwnPublicShareResponse] """ kwargs = _get_kwargs( - token_id=token_id, + public_share_id=public_share_id, body=body, ) @@ -99,54 +103,62 @@ def sync_detailed( def sync( - token_id: UUID, + public_share_id: UUID, *, client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> OpenShockProblem | TokenPausedResponse | None: - """Set whether a token is paused. A paused token may not send shocker control messages. + body: PublicSharePasswordSet, +) -> OpenShockProblem | OwnPublicShareResponse | None: + """Set, change or remove the password of a public share + + Setting or changing the password disconnects everyone currently using the share; they have to enter + the + new one. Removing it keeps them connected. Args: - token_id (UUID): - body (SetTokenPausedRequest): + public_share_id (UUID): + body (PublicSharePasswordSet): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - OpenShockProblem | TokenPausedResponse + OpenShockProblem | OwnPublicShareResponse """ return sync_detailed( - token_id=token_id, + public_share_id=public_share_id, client=client, body=body, ).parsed async def asyncio_detailed( - token_id: UUID, + public_share_id: UUID, *, client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> Response[OpenShockProblem | TokenPausedResponse]: - """Set whether a token is paused. A paused token may not send shocker control messages. + body: PublicSharePasswordSet, +) -> Response[OpenShockProblem | OwnPublicShareResponse]: + """Set, change or remove the password of a public share + + Setting or changing the password disconnects everyone currently using the share; they have to enter + the + new one. Removing it keeps them connected. Args: - token_id (UUID): - body (SetTokenPausedRequest): + public_share_id (UUID): + body (PublicSharePasswordSet): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[OpenShockProblem | TokenPausedResponse] + Response[OpenShockProblem | OwnPublicShareResponse] """ kwargs = _get_kwargs( - token_id=token_id, + public_share_id=public_share_id, body=body, ) @@ -156,28 +168,32 @@ async def asyncio_detailed( async def asyncio( - token_id: UUID, + public_share_id: UUID, *, client: AuthenticatedClient, - body: SetTokenPausedRequest, -) -> OpenShockProblem | TokenPausedResponse | None: - """Set whether a token is paused. A paused token may not send shocker control messages. + body: PublicSharePasswordSet, +) -> OpenShockProblem | OwnPublicShareResponse | None: + """Set, change or remove the password of a public share + + Setting or changing the password disconnects everyone currently using the share; they have to enter + the + new one. Removing it keeps them connected. Args: - token_id (UUID): - body (SetTokenPausedRequest): + public_share_id (UUID): + body (PublicSharePasswordSet): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - OpenShockProblem | TokenPausedResponse + OpenShockProblem | OwnPublicShareResponse """ return ( await asyncio_detailed( - token_id=token_id, + public_share_id=public_share_id, client=client, body=body, ) diff --git a/openshock/rest/api/sessions/__init__.py b/openshock/rest/api/sessions/__init__.py deleted file mode 100644 index 181fdd9..0000000 --- a/openshock/rest/api/sessions/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/sessions/sessions_delete_session.py b/openshock/rest/api/sessions/sessions_delete_session.py deleted file mode 100644 index f5f1179..0000000 --- a/openshock/rest/api/sessions/sessions_delete_session.py +++ /dev/null @@ -1,157 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - session_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/sessions/{session_id}".format( - session_id=quote(str(session_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: - if response.status_code == 200: - response_200 = cast(Any, None) - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - session_id=session_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return sync_detailed( - session_id=session_id, - client=client, - ).parsed - - -async def asyncio_detailed( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | OpenShockProblem]: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | OpenShockProblem] - """ - - kwargs = _get_kwargs( - session_id=session_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - session_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | OpenShockProblem | None: - """ - Args: - session_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | OpenShockProblem - """ - - return ( - await asyncio_detailed( - session_id=session_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/sessions/sessions_get_self_session.py b/openshock/rest/api/sessions/sessions_get_self_session.py deleted file mode 100644 index 70302aa..0000000 --- a/openshock/rest/api/sessions/sessions_get_self_session.py +++ /dev/null @@ -1,127 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.login_session_response import LoginSessionResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/sessions/self", - } - - return _kwargs - - -def _parse_response(*, client: AuthenticatedClient | Client, response: httpx2.Response) -> LoginSessionResponse | None: - if response.status_code == 200: - response_200 = LoginSessionResponse.from_dict(response.json()) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LoginSessionResponse]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[LoginSessionResponse]: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LoginSessionResponse] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> LoginSessionResponse | None: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LoginSessionResponse - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[LoginSessionResponse]: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LoginSessionResponse] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> LoginSessionResponse | None: - """Gets information about the current token used to access this endpoint - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LoginSessionResponse - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/sessions/sessions_list_sessions.py b/openshock/rest/api/sessions/sessions_list_sessions.py deleted file mode 100644 index 48a8244..0000000 --- a/openshock/rest/api/sessions/sessions_list_sessions.py +++ /dev/null @@ -1,130 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.login_session_response import LoginSessionResponse -from ...types import Response - - -def _get_kwargs() -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "get", - "url": "/1/sessions", - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> list[LoginSessionResponse] | None: - if response.status_code == 200: - response_200 = [] - _response_200 = response.json() - for response_200_item_data in _response_200: - response_200_item = LoginSessionResponse.from_dict(response_200_item_data) - - response_200.append(response_200_item) - - return response_200 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[list[LoginSessionResponse]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[LoginSessionResponse]]: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[LoginSessionResponse]] - """ - - kwargs = _get_kwargs() - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - *, - client: AuthenticatedClient, -) -> list[LoginSessionResponse] | None: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[LoginSessionResponse] - """ - - return sync_detailed( - client=client, - ).parsed - - -async def asyncio_detailed( - *, - client: AuthenticatedClient, -) -> Response[list[LoginSessionResponse]]: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[list[LoginSessionResponse]] - """ - - kwargs = _get_kwargs() - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - *, - client: AuthenticatedClient, -) -> list[LoginSessionResponse] | None: - """ - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - list[LoginSessionResponse] - """ - - return ( - await asyncio_detailed( - client=client, - ) - ).parsed diff --git a/openshock/rest/api/shocker_shares/__init__.py b/openshock/rest/api/shocker_shares/__init__.py deleted file mode 100644 index 181fdd9..0000000 --- a/openshock/rest/api/shocker_shares/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -"""Contains endpoint functions for accessing the API""" diff --git a/openshock/rest/api/shocker_shares/shares_delete_share_code.py b/openshock/rest/api/shocker_shares/shares_delete_share_code.py deleted file mode 100644 index 4f89f58..0000000 --- a/openshock/rest/api/shocker_shares/shares_delete_share_code.py +++ /dev/null @@ -1,163 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_empty_response import LegacyEmptyResponse -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - share_code_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "delete", - "url": "/1/shares/code/{share_code_id}".format( - share_code_id=quote(str(share_code_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> LegacyEmptyResponse | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LegacyEmptyResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyEmptyResponse | OpenShockProblem - """ - - return sync_detailed( - share_code_id=share_code_id, - client=client, - ).parsed - - -async def asyncio_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[LegacyEmptyResponse | OpenShockProblem]: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> LegacyEmptyResponse | OpenShockProblem | None: - """Delete a share code - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - LegacyEmptyResponse | OpenShockProblem - """ - - return ( - await asyncio_detailed( - share_code_id=share_code_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/shocker_shares/shares_link_share_code.py b/openshock/rest/api/shocker_shares/shares_link_share_code.py deleted file mode 100644 index a6463ae..0000000 --- a/openshock/rest/api/shocker_shares/shares_link_share_code.py +++ /dev/null @@ -1,172 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from http import HTTPStatus -from typing import Any, cast -from urllib.parse import quote -from uuid import UUID - -import httpx2 - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.legacy_empty_response import LegacyEmptyResponse -from ...models.open_shock_problem import OpenShockProblem -from ...types import Response - - -def _get_kwargs( - share_code_id: UUID, -) -> dict[str, Any]: - - _kwargs: dict[str, Any] = { - "method": "post", - "url": "/1/shares/code/{share_code_id}".format( - share_code_id=quote(str(share_code_id), safe=""), - ), - } - - return _kwargs - - -def _parse_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | LegacyEmptyResponse | OpenShockProblem | None: - if response.status_code == 200: - response_200 = LegacyEmptyResponse.from_dict(response.json()) - - return response_200 - - if response.status_code == 400: - response_400 = OpenShockProblem.from_dict(response.json()) - - return response_400 - - if response.status_code == 404: - response_404 = OpenShockProblem.from_dict(response.json()) - - return response_404 - - if response.status_code == 500: - response_500 = cast(Any, None) - return response_500 - - if client.raise_on_unexpected_status: - raise errors.UnexpectedStatus(response.status_code, response.content) - else: - return None - - -def _build_response( - *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -def sync_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -def sync( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | LegacyEmptyResponse | OpenShockProblem | None: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyEmptyResponse | OpenShockProblem - """ - - return sync_detailed( - share_code_id=share_code_id, - client=client, - ).parsed - - -async def asyncio_detailed( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Response[Any | LegacyEmptyResponse | OpenShockProblem]: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Response[Any | LegacyEmptyResponse | OpenShockProblem] - """ - - kwargs = _get_kwargs( - share_code_id=share_code_id, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -async def asyncio( - share_code_id: UUID, - *, - client: AuthenticatedClient, -) -> Any | LegacyEmptyResponse | OpenShockProblem | None: - """Link a share code to your account - - Args: - share_code_id (UUID): - - Raises: - errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. - httpx2.TimeoutException: If the request takes longer than Client.timeout. - - Returns: - Any | LegacyEmptyResponse | OpenShockProblem - """ - - return ( - await asyncio_detailed( - share_code_id=share_code_id, - client=client, - ) - ).parsed diff --git a/openshock/rest/api/api_tokens/tokens_edit_token_v2.py b/openshock/rest/api/shockers/shocker_set_shocker_permissions.py similarity index 51% rename from openshock/rest/api/api_tokens/tokens_edit_token_v2.py rename to openshock/rest/api/shockers/shocker_set_shocker_permissions.py index 6c71df2..d3b51b8 100644 --- a/openshock/rest/api/api_tokens/tokens_edit_token_v2.py +++ b/openshock/rest/api/shockers/shocker_set_shocker_permissions.py @@ -1,6 +1,6 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. from http import HTTPStatus -from typing import Any, cast +from typing import Any from urllib.parse import quote from uuid import UUID @@ -8,22 +8,23 @@ from ... import errors from ...client import AuthenticatedClient, Client -from ...models.edit_token_request_v2 import EditTokenRequestV2 +from ...models.legacy_data_response_of_shocker_perm_limit_pair import LegacyDataResponseOfShockerPermLimitPair from ...models.open_shock_problem import OpenShockProblem +from ...models.shocker_perm_limit_pair import ShockerPermLimitPair from ...types import Response def _get_kwargs( - token_id: UUID, + shocker_id: UUID, *, - body: EditTokenRequestV2, + body: ShockerPermLimitPair, ) -> dict[str, Any]: headers: dict[str, Any] = {} _kwargs: dict[str, Any] = { - "method": "patch", - "url": "/2/tokens/{token_id}".format( - token_id=quote(str(token_id), safe=""), + "method": "put", + "url": "/1/shockers/{shocker_id}/permissions".format( + shocker_id=quote(str(shocker_id), safe=""), ), } @@ -37,9 +38,10 @@ def _get_kwargs( def _parse_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Any | OpenShockProblem | None: +) -> LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem | None: if response.status_code == 200: - response_200 = cast(Any, None) + response_200 = LegacyDataResponseOfShockerPermLimitPair.from_dict(response.json()) + return response_200 if response.status_code == 404: @@ -55,7 +57,7 @@ def _parse_response( def _build_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[Any | OpenShockProblem]: +) -> Response[LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, @@ -65,27 +67,31 @@ def _build_response( def sync_detailed( - token_id: UUID, + shocker_id: UUID, *, client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Response[Any | OpenShockProblem]: - """Edit a token + body: ShockerPermLimitPair, +) -> Response[LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem]: + """Set the global permissions and limits of a shocker. They apply to every control of the shocker, + including + the owner's own, on top of any share or token restrictions. A null limit means uncapped. The + duration limit + does not apply to live control; disallow live control to bound it. Args: - token_id (UUID): - body (EditTokenRequestV2): + shocker_id (UUID): + body (ShockerPermLimitPair): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[Any | OpenShockProblem] + Response[LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem] """ kwargs = _get_kwargs( - token_id=token_id, + shocker_id=shocker_id, body=body, ) @@ -97,54 +103,62 @@ def sync_detailed( def sync( - token_id: UUID, + shocker_id: UUID, *, client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Any | OpenShockProblem | None: - """Edit a token + body: ShockerPermLimitPair, +) -> LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem | None: + """Set the global permissions and limits of a shocker. They apply to every control of the shocker, + including + the owner's own, on top of any share or token restrictions. A null limit means uncapped. The + duration limit + does not apply to live control; disallow live control to bound it. Args: - token_id (UUID): - body (EditTokenRequestV2): + shocker_id (UUID): + body (ShockerPermLimitPair): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Any | OpenShockProblem + LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem """ return sync_detailed( - token_id=token_id, + shocker_id=shocker_id, client=client, body=body, ).parsed async def asyncio_detailed( - token_id: UUID, + shocker_id: UUID, *, client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Response[Any | OpenShockProblem]: - """Edit a token + body: ShockerPermLimitPair, +) -> Response[LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem]: + """Set the global permissions and limits of a shocker. They apply to every control of the shocker, + including + the owner's own, on top of any share or token restrictions. A null limit means uncapped. The + duration limit + does not apply to live control; disallow live control to bound it. Args: - token_id (UUID): - body (EditTokenRequestV2): + shocker_id (UUID): + body (ShockerPermLimitPair): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[Any | OpenShockProblem] + Response[LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem] """ kwargs = _get_kwargs( - token_id=token_id, + shocker_id=shocker_id, body=body, ) @@ -154,28 +168,32 @@ async def asyncio_detailed( async def asyncio( - token_id: UUID, + shocker_id: UUID, *, client: AuthenticatedClient, - body: EditTokenRequestV2, -) -> Any | OpenShockProblem | None: - """Edit a token + body: ShockerPermLimitPair, +) -> LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem | None: + """Set the global permissions and limits of a shocker. They apply to every control of the shocker, + including + the owner's own, on top of any share or token restrictions. A null limit means uncapped. The + duration limit + does not apply to live control; disallow live control to bound it. Args: - token_id (UUID): - body (EditTokenRequestV2): + shocker_id (UUID): + body (ShockerPermLimitPair): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Any | OpenShockProblem + LegacyDataResponseOfShockerPermLimitPair | OpenShockProblem """ return ( await asyncio_detailed( - token_id=token_id, + shocker_id=shocker_id, client=client, body=body, ) diff --git a/openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py b/openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py index 0e71870..3e04d0d 100644 --- a/openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py +++ b/openshock/rest/api/user_shocker_shares/user_shares_redeem_invite.py @@ -40,6 +40,11 @@ def _parse_response( return response_404 + if response.status_code == 409: + response_409 = OpenShockProblem.from_dict(response.json()) + + return response_409 + if client.raise_on_unexpected_status: raise errors.UnexpectedStatus(response.status_code, response.content) else: diff --git a/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py b/openshock/rest/api/users/public_get_user_profile.py similarity index 66% rename from openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py rename to openshock/rest/api/users/public_get_user_profile.py index 651c565..e848f1a 100644 --- a/openshock/rest/api/api_tokens/tokens_get_token_by_id_v2.py +++ b/openshock/rest/api/users/public_get_user_profile.py @@ -2,25 +2,24 @@ from http import HTTPStatus from typing import Any from urllib.parse import quote -from uuid import UUID import httpx2 from ... import errors from ...client import AuthenticatedClient, Client from ...models.open_shock_problem import OpenShockProblem -from ...models.token_response_v2 import TokenResponseV2 +from ...models.public_user_profile_response import PublicUserProfileResponse from ...types import Response def _get_kwargs( - token_id: UUID, + username: str, ) -> dict[str, Any]: _kwargs: dict[str, Any] = { "method": "get", - "url": "/2/tokens/{token_id}".format( - token_id=quote(str(token_id), safe=""), + "url": "/1/public/users/{username}".format( + username=quote(str(username), safe=""), ), } @@ -29,9 +28,9 @@ def _get_kwargs( def _parse_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> OpenShockProblem | TokenResponseV2 | None: +) -> OpenShockProblem | PublicUserProfileResponse | None: if response.status_code == 200: - response_200 = TokenResponseV2.from_dict(response.json()) + response_200 = PublicUserProfileResponse.from_dict(response.json()) return response_200 @@ -48,7 +47,7 @@ def _parse_response( def _build_response( *, client: AuthenticatedClient | Client, response: httpx2.Response -) -> Response[OpenShockProblem | TokenResponseV2]: +) -> Response[OpenShockProblem | PublicUserProfileResponse]: return Response( status_code=HTTPStatus(response.status_code), content=response.content, @@ -58,25 +57,25 @@ def _build_response( def sync_detailed( - token_id: UUID, + username: str, *, - client: AuthenticatedClient, -) -> Response[OpenShockProblem | TokenResponseV2]: - """Get a token by id + client: AuthenticatedClient | Client, +) -> Response[OpenShockProblem | PublicUserProfileResponse]: + """Gets a user's public profile. Args: - token_id (UUID): + username (str): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[OpenShockProblem | TokenResponseV2] + Response[OpenShockProblem | PublicUserProfileResponse] """ kwargs = _get_kwargs( - token_id=token_id, + username=username, ) response = client.get_httpx_client().request( @@ -87,49 +86,49 @@ def sync_detailed( def sync( - token_id: UUID, + username: str, *, - client: AuthenticatedClient, -) -> OpenShockProblem | TokenResponseV2 | None: - """Get a token by id + client: AuthenticatedClient | Client, +) -> OpenShockProblem | PublicUserProfileResponse | None: + """Gets a user's public profile. Args: - token_id (UUID): + username (str): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - OpenShockProblem | TokenResponseV2 + OpenShockProblem | PublicUserProfileResponse """ return sync_detailed( - token_id=token_id, + username=username, client=client, ).parsed async def asyncio_detailed( - token_id: UUID, + username: str, *, - client: AuthenticatedClient, -) -> Response[OpenShockProblem | TokenResponseV2]: - """Get a token by id + client: AuthenticatedClient | Client, +) -> Response[OpenShockProblem | PublicUserProfileResponse]: + """Gets a user's public profile. Args: - token_id (UUID): + username (str): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - Response[OpenShockProblem | TokenResponseV2] + Response[OpenShockProblem | PublicUserProfileResponse] """ kwargs = _get_kwargs( - token_id=token_id, + username=username, ) response = await client.get_async_httpx_client().request(**kwargs) @@ -138,26 +137,26 @@ async def asyncio_detailed( async def asyncio( - token_id: UUID, + username: str, *, - client: AuthenticatedClient, -) -> OpenShockProblem | TokenResponseV2 | None: - """Get a token by id + client: AuthenticatedClient | Client, +) -> OpenShockProblem | PublicUserProfileResponse | None: + """Gets a user's public profile. Args: - token_id (UUID): + username (str): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx2.TimeoutException: If the request takes longer than Client.timeout. Returns: - OpenShockProblem | TokenResponseV2 + OpenShockProblem | PublicUserProfileResponse """ return ( await asyncio_detailed( - token_id=token_id, + username=username, client=client, ) ).parsed diff --git a/openshock/rest/models/__init__.py b/openshock/rest/models/__init__.py index ab386b7..6642115 100644 --- a/openshock/rest/models/__init__.py +++ b/openshock/rest/models/__init__.py @@ -1,64 +1,9 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. """Contains all the data models used in inputs/outputs""" -from .add_email_provider_blacklist_dto import AddEmailProviderBlacklistDto -from .add_username_blacklist_dto import AddUsernameBlacklistDto -from .add_webhook_dto import AddWebhookDto -from .admin_online_device_response import AdminOnlineDeviceResponse -from .admin_online_gateway_response import AdminOnlineGatewayResponse -from .admin_user_view import AdminUserView -from .admin_user_view_api_token import AdminUserViewApiToken -from .admin_user_view_email_change import AdminUserViewEmailChange -from .admin_user_view_hub import AdminUserViewHub -from .admin_user_view_name_change import AdminUserViewNameChange -from .admin_user_view_password_reset import AdminUserViewPasswordReset -from .admin_user_view_shocker import AdminUserViewShocker -from .admin_user_view_user_activation_request import AdminUserViewUserActivationRequest -from .admin_user_view_user_deactivation import AdminUserViewUserDeactivation -from .admin_user_view_user_ref import AdminUserViewUserRef -from .admin_users_view import AdminUsersView -from .audit_action import AuditAction -from .audit_log_entry_response import AuditLogEntryResponse -from .audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata -from .audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT -from .audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata -from .audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT -from .audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata -from .audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT -from .audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata -from .audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT -from .audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata -from .audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT -from .audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata -from .audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT -from .audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata -from .audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT -from .audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata -from .audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT -from .audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata -from .audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT -from .audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata -from .audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT -from .audit_metadata_login_metadata import AuditMetadataLoginMetadata -from .audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT -from .audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata -from .audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT -from .audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata -from .audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT -from .audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata -from .audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT -from .automation_token_dto import AutomationTokenDto -from .automation_token_type import AutomationTokenType from .backend_info_response import BackendInfoResponse from .basic_user_info import BasicUserInfo from .bulk_user_share_shockers_update_request import BulkUserShareShockersUpdateRequest -from .change_email_request import ChangeEmailRequest -from .change_password_request import ChangePasswordRequest -from .change_username_request import ChangeUsernameRequest -from .configuration_add_item_request import ConfigurationAddItemRequest -from .configuration_item_dto import ConfigurationItemDto -from .configuration_update_item_request import ConfigurationUpdateItemRequest -from .configuration_value_type import ConfigurationValueType from .control import Control from .control_limit_mode import ControlLimitMode from .control_log_sender_light import ControlLogSenderLight @@ -68,34 +13,19 @@ from .control_stat_totals import ControlStatTotals from .control_stats_response import ControlStatsResponse from .control_type import ControlType -from .create_automation_token_dto import CreateAutomationTokenDto from .create_share_request import CreateShareRequest -from .create_token_request_v2 import CreateTokenRequestV2 -from .created_automation_token_dto import CreatedAutomationTokenDto from .daily_control_stats import DailyControlStats from .device_response import DeviceResponse from .device_self_response import DeviceSelfResponse from .device_with_shockers_response import DeviceWithShockersResponse from .device_with_token_response import DeviceWithTokenResponse from .duration_limit_settings import DurationLimitSettings -from .edit_token_request_v2 import EditTokenRequestV2 -from .email_outbox_bulk_request import EmailOutboxBulkRequest -from .email_outbox_bulk_result_dto import EmailOutboxBulkResultDto -from .email_outbox_message_dto import EmailOutboxMessageDto -from .email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload -from .email_outbox_stats_dto import EmailOutboxStatsDto -from .email_provider_blacklist_dto import EmailProviderBlacklistDto -from .email_status import EmailStatus -from .email_type import EmailType from .given_control_stats import GivenControlStats from .hub_create_request import HubCreateRequest from .hub_edit_request import HubEditRequest from .intensity_limit_settings import IntensityLimitSettings from .lcg_node_response_v2 import LcgNodeResponseV2 from .lcg_response_v2 import LcgResponseV2 -from .legacy_data_response_of_array_of_admin_online_device_response import ( - LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse, -) from .legacy_data_response_of_array_of_device_response import LegacyDataResponseOfArrayOfDeviceResponse from .legacy_data_response_of_array_of_device_with_shockers_response import ( LegacyDataResponseOfArrayOfDeviceWithShockersResponse, @@ -112,10 +42,10 @@ from .legacy_data_response_of_device_self_response import LegacyDataResponseOfDeviceSelfResponse from .legacy_data_response_of_device_with_token_response import LegacyDataResponseOfDeviceWithTokenResponse from .legacy_data_response_of_guid import LegacyDataResponseOfGuid -from .legacy_data_response_of_i_read_only_collection_of_ota_item import LegacyDataResponseOfIReadOnlyCollectionOfOtaItem from .legacy_data_response_of_legacy_user_self_response import LegacyDataResponseOfLegacyUserSelfResponse from .legacy_data_response_of_pause_reason import LegacyDataResponseOfPauseReason from .legacy_data_response_of_public_share_response import LegacyDataResponseOfPublicShareResponse +from .legacy_data_response_of_shocker_perm_limit_pair import LegacyDataResponseOfShockerPermLimitPair from .legacy_data_response_of_shocker_with_device import LegacyDataResponseOfShockerWithDevice from .legacy_data_response_of_stats_response import LegacyDataResponseOfStatsResponse from .legacy_data_response_ofboolean import LegacyDataResponseOfboolean @@ -124,46 +54,34 @@ from .legacy_user_self_response import LegacyUserSelfResponse from .log_entry import LogEntry from .log_entry_with_hub import LogEntryWithHub -from .login_session_response import LoginSessionResponse -from .login_v2 import LoginV2 -from .login_v2_ok_response import LoginV2OkResponse -from .match_type_enum import MatchTypeEnum from .minimal_shocker import MinimalShocker from .new_shocker import NewShocker -from .o_auth_connection_response import OAuthConnectionResponse from .open_shock_problem import OpenShockProblem -from .ota_item import OtaItem -from .ota_update_status import OtaUpdateStatus from .own_public_share_response import OwnPublicShareResponse from .owner_shocker_response import OwnerShockerResponse -from .paged_result_of_audit_log_entry_response import PagedResultOfAuditLogEntryResponse from .paged_result_of_log_entry_with_hub import PagedResultOfLogEntryWithHub -from .paginated_of_admin_users_view import PaginatedOfAdminUsersView -from .paginated_of_email_outbox_message_dto import PaginatedOfEmailOutboxMessageDto -from .password_hashing_algorithm import PasswordHashingAlgorithm -from .password_reset_process_data import PasswordResetProcessData -from .password_reset_request_v2 import PasswordResetRequestV2 -from .patch_automation_token_dto import PatchAutomationTokenDto from .pause_request import PauseRequest from .pause_user_share_shockers_request import PauseUserShareShockersRequest from .pause_user_share_shockers_response import PauseUserShareShockersResponse from .pause_user_share_shockers_response_pause_states import PauseUserShareShockersResponsePauseStates from .permission_type import PermissionType from .problem_details import ProblemDetails +from .public_share_author import PublicShareAuthor from .public_share_create import PublicShareCreate from .public_share_device import PublicShareDevice +from .public_share_edit import PublicShareEdit from .public_share_edit_shocker import PublicShareEditShocker +from .public_share_password_set import PublicSharePasswordSet from .public_share_response import PublicShareResponse from .public_share_shocker import PublicShareShocker +from .public_share_unlock import PublicShareUnlock +from .public_share_unlock_response import PublicShareUnlockResponse +from .public_user_profile_details import PublicUserProfileDetails +from .public_user_profile_public_share import PublicUserProfilePublicShare +from .public_user_profile_response import PublicUserProfileResponse from .received_control_stats import ReceivedControlStats from .remove_user_shares_response import RemoveUserSharesResponse -from .report_tokens_request import ReportTokensRequest from .role_type import RoleType -from .send_test_email_dto import SendTestEmailDto -from .set_token_paused_request import SetTokenPausedRequest -from .set_user_email_request_body import SetUserEmailRequestBody -from .set_user_name_request_body import SetUserNameRequestBody -from .set_user_password_request_body import SetUserPasswordRequestBody from .share_code_info import ShareCodeInfo from .share_info import ShareInfo from .share_invite_base_details import ShareInviteBaseDetails @@ -179,85 +97,22 @@ from .shocker_permissions import ShockerPermissions from .shocker_response import ShockerResponse from .shocker_with_device import ShockerWithDevice -from .sign_up_v2 import SignUpV2 +from .social_platform import SocialPlatform from .sort_direction import SortDirection from .stats_response import StatsResponse -from .token_created_response_v2 import TokenCreatedResponseV2 -from .token_paused_response import TokenPausedResponse from .token_response_v2 import TokenResponseV2 from .user_control_stat_totals import UserControlStatTotals from .user_control_stats import UserControlStats -from .user_name_blacklist_dto import UserNameBlacklistDto -from .user_patch_dto import UserPatchDto +from .user_profile_social import UserProfileSocial from .user_self_response import UserSelfResponse from .user_share_info import UserShareInfo -from .username_availability import UsernameAvailability -from .username_check_response import UsernameCheckResponse -from .username_error import UsernameError -from .username_error_type import UsernameErrorType from .v2_user_shares import V2UserShares from .v2_user_shares_list_item import V2UserSharesListItem -from .webhook_dto import WebhookDto __all__ = ( - "AddEmailProviderBlacklistDto", - "AddUsernameBlacklistDto", - "AddWebhookDto", - "AdminOnlineDeviceResponse", - "AdminOnlineGatewayResponse", - "AdminUsersView", - "AdminUserView", - "AdminUserViewApiToken", - "AdminUserViewEmailChange", - "AdminUserViewHub", - "AdminUserViewNameChange", - "AdminUserViewPasswordReset", - "AdminUserViewShocker", - "AdminUserViewUserActivationRequest", - "AdminUserViewUserDeactivation", - "AdminUserViewUserRef", - "AuditAction", - "AuditLogEntryResponse", - "AuditMetadataAccountDeactivatedMetadata", - "AuditMetadataAccountDeactivatedMetadataT", - "AuditMetadataApiTokenCreatedMetadata", - "AuditMetadataApiTokenCreatedMetadataT", - "AuditMetadataApiTokenDeletedMetadata", - "AuditMetadataApiTokenDeletedMetadataT", - "AuditMetadataAutomationTokenCreatedMetadata", - "AuditMetadataAutomationTokenCreatedMetadataT", - "AuditMetadataAutomationTokenDeletedMetadata", - "AuditMetadataAutomationTokenDeletedMetadataT", - "AuditMetadataAutomationTokenRotatedMetadata", - "AuditMetadataAutomationTokenRotatedMetadataT", - "AuditMetadataAutomationTokenUpdatedMetadata", - "AuditMetadataAutomationTokenUpdatedMetadataT", - "AuditMetadataAutomationTokenUsedMetadata", - "AuditMetadataAutomationTokenUsedMetadataT", - "AuditMetadataEmailChangedMetadata", - "AuditMetadataEmailChangedMetadataT", - "AuditMetadataEmailChangeRequestedMetadata", - "AuditMetadataEmailChangeRequestedMetadataT", - "AuditMetadataLoginMetadata", - "AuditMetadataLoginMetadataT", - "AuditMetadataOAuthConnectedMetadata", - "AuditMetadataOAuthConnectedMetadataT", - "AuditMetadataOAuthDisconnectedMetadata", - "AuditMetadataOAuthDisconnectedMetadataT", - "AuditMetadataUsernameChangedMetadata", - "AuditMetadataUsernameChangedMetadataT", - "AutomationTokenDto", - "AutomationTokenType", "BackendInfoResponse", "BasicUserInfo", "BulkUserShareShockersUpdateRequest", - "ChangeEmailRequest", - "ChangePasswordRequest", - "ChangeUsernameRequest", - "ConfigurationAddItemRequest", - "ConfigurationItemDto", - "ConfigurationUpdateItemRequest", - "ConfigurationValueType", "Control", "ControlLimitMode", "ControlLogSenderLight", @@ -267,32 +122,19 @@ "ControlStatsResponse", "ControlStatTotals", "ControlType", - "CreateAutomationTokenDto", - "CreatedAutomationTokenDto", "CreateShareRequest", - "CreateTokenRequestV2", "DailyControlStats", "DeviceResponse", "DeviceSelfResponse", "DeviceWithShockersResponse", "DeviceWithTokenResponse", "DurationLimitSettings", - "EditTokenRequestV2", - "EmailOutboxBulkRequest", - "EmailOutboxBulkResultDto", - "EmailOutboxMessageDto", - "EmailOutboxMessageDtoPayload", - "EmailOutboxStatsDto", - "EmailProviderBlacklistDto", - "EmailStatus", - "EmailType", "GivenControlStats", "HubCreateRequest", "HubEditRequest", "IntensityLimitSettings", "LcgNodeResponseV2", "LcgResponseV2", - "LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse", "LegacyDataResponseOfArrayOfDeviceResponse", "LegacyDataResponseOfArrayOfDeviceWithShockersResponse", "LegacyDataResponseOfArrayOfLogEntry", @@ -306,10 +148,10 @@ "LegacyDataResponseOfDeviceSelfResponse", "LegacyDataResponseOfDeviceWithTokenResponse", "LegacyDataResponseOfGuid", - "LegacyDataResponseOfIReadOnlyCollectionOfOtaItem", "LegacyDataResponseOfLegacyUserSelfResponse", "LegacyDataResponseOfPauseReason", "LegacyDataResponseOfPublicShareResponse", + "LegacyDataResponseOfShockerPermLimitPair", "LegacyDataResponseOfShockerWithDevice", "LegacyDataResponseOfStatsResponse", "LegacyDataResponseOfstring", @@ -317,46 +159,34 @@ "LegacyUserSelfResponse", "LogEntry", "LogEntryWithHub", - "LoginSessionResponse", - "LoginV2", - "LoginV2OkResponse", - "MatchTypeEnum", "MinimalShocker", "NewShocker", - "OAuthConnectionResponse", "OpenShockProblem", - "OtaItem", - "OtaUpdateStatus", "OwnerShockerResponse", "OwnPublicShareResponse", - "PagedResultOfAuditLogEntryResponse", "PagedResultOfLogEntryWithHub", - "PaginatedOfAdminUsersView", - "PaginatedOfEmailOutboxMessageDto", - "PasswordHashingAlgorithm", - "PasswordResetProcessData", - "PasswordResetRequestV2", - "PatchAutomationTokenDto", "PauseRequest", "PauseUserShareShockersRequest", "PauseUserShareShockersResponse", "PauseUserShareShockersResponsePauseStates", "PermissionType", "ProblemDetails", + "PublicShareAuthor", "PublicShareCreate", "PublicShareDevice", + "PublicShareEdit", "PublicShareEditShocker", + "PublicSharePasswordSet", "PublicShareResponse", "PublicShareShocker", + "PublicShareUnlock", + "PublicShareUnlockResponse", + "PublicUserProfileDetails", + "PublicUserProfilePublicShare", + "PublicUserProfileResponse", "ReceivedControlStats", "RemoveUserSharesResponse", - "ReportTokensRequest", "RoleType", - "SendTestEmailDto", - "SetTokenPausedRequest", - "SetUserEmailRequestBody", - "SetUserNameRequestBody", - "SetUserPasswordRequestBody", "ShareCodeInfo", "SharedDevice", "SharedShocker", @@ -372,23 +202,15 @@ "ShockerPermLimitPairWithIdAndName", "ShockerResponse", "ShockerWithDevice", - "SignUpV2", + "SocialPlatform", "SortDirection", "StatsResponse", - "TokenCreatedResponseV2", - "TokenPausedResponse", "TokenResponseV2", "UserControlStats", "UserControlStatTotals", - "UsernameAvailability", - "UserNameBlacklistDto", - "UsernameCheckResponse", - "UsernameError", - "UsernameErrorType", - "UserPatchDto", + "UserProfileSocial", "UserSelfResponse", "UserShareInfo", "V2UserShares", "V2UserSharesListItem", - "WebhookDto", ) diff --git a/openshock/rest/models/add_email_provider_blacklist_dto.py b/openshock/rest/models/add_email_provider_blacklist_dto.py deleted file mode 100644 index fb17ea7..0000000 --- a/openshock/rest/models/add_email_provider_blacklist_dto.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AddEmailProviderBlacklistDto") - - -@_attrs_define -class AddEmailProviderBlacklistDto: - """ - Attributes: - domains (list[str]): - """ - - domains: list[str] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - domains = self.domains - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "domains": domains, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - domains = cast(list[str], d.pop("domains")) - - add_email_provider_blacklist_dto = cls( - domains=domains, - ) - - add_email_provider_blacklist_dto.additional_properties = d - return add_email_provider_blacklist_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/add_webhook_dto.py b/openshock/rest/models/add_webhook_dto.py deleted file mode 100644 index de3ff55..0000000 --- a/openshock/rest/models/add_webhook_dto.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AddWebhookDto") - - -@_attrs_define -class AddWebhookDto: - """ - Attributes: - name (str): - url (str): - """ - - name: str - url: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - url = self.url - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "url": url, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - url = d.pop("url") - - add_webhook_dto = cls( - name=name, - url=url, - ) - - add_webhook_dto.additional_properties = d - return add_webhook_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_device_response.py b/openshock/rest/models/admin_online_device_response.py deleted file mode 100644 index 5a60cd5..0000000 --- a/openshock/rest/models/admin_online_device_response.py +++ /dev/null @@ -1,216 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.basic_user_info import BasicUserInfo - - -T = TypeVar("T", bound="AdminOnlineDeviceResponse") - - -@_attrs_define -class AdminOnlineDeviceResponse: - """ - Attributes: - id (UUID): - name (str): - owner (BasicUserInfo): - firmware_version (str): - gateway (str): - connected_at (datetime.datetime): - user_agent (None | str): - booted_at (datetime.datetime): - latency_ms (int | None): - rssi (int | None): - country (None | str): - ip (None | str): An IPv4 or IPv6 address in its textual form. - asn (int | None): - asn_org (None | str): - """ - - id: UUID - name: str - owner: BasicUserInfo - firmware_version: str - gateway: str - connected_at: datetime.datetime - user_agent: None | str - booted_at: datetime.datetime - latency_ms: int | None - rssi: int | None - country: None | str - ip: None | str - asn: int | None - asn_org: None | str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - owner = self.owner.to_dict() - - firmware_version = self.firmware_version - - gateway = self.gateway - - connected_at = self.connected_at.isoformat() - - user_agent: None | str - user_agent = self.user_agent - - booted_at = self.booted_at.isoformat() - - latency_ms: int | None - latency_ms = self.latency_ms - - rssi: int | None - rssi = self.rssi - - country: None | str - country = self.country - - ip: None | str - ip = self.ip - - asn: int | None - asn = self.asn - - asn_org: None | str - asn_org = self.asn_org - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "owner": owner, - "firmwareVersion": firmware_version, - "gateway": gateway, - "connectedAt": connected_at, - "userAgent": user_agent, - "bootedAt": booted_at, - "latencyMs": latency_ms, - "rssi": rssi, - "country": country, - "ip": ip, - "asn": asn, - "asnOrg": asn_org, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - owner = BasicUserInfo.from_dict(d.pop("owner")) - - firmware_version = d.pop("firmwareVersion") - - gateway = d.pop("gateway") - - connected_at = datetime.datetime.fromisoformat(d.pop("connectedAt")) - - def _parse_user_agent(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - user_agent = _parse_user_agent(d.pop("userAgent")) - - booted_at = datetime.datetime.fromisoformat(d.pop("bootedAt")) - - def _parse_latency_ms(data: object) -> int | None: - if data is None: - return data - return cast(int | None, data) - - latency_ms = _parse_latency_ms(d.pop("latencyMs")) - - def _parse_rssi(data: object) -> int | None: - if data is None: - return data - return cast(int | None, data) - - rssi = _parse_rssi(d.pop("rssi")) - - def _parse_country(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - country = _parse_country(d.pop("country")) - - def _parse_ip(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - ip = _parse_ip(d.pop("ip")) - - def _parse_asn(data: object) -> int | None: - if data is None: - return data - return cast(int | None, data) - - asn = _parse_asn(d.pop("asn")) - - def _parse_asn_org(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - asn_org = _parse_asn_org(d.pop("asnOrg")) - - admin_online_device_response = cls( - id=id, - name=name, - owner=owner, - firmware_version=firmware_version, - gateway=gateway, - connected_at=connected_at, - user_agent=user_agent, - booted_at=booted_at, - latency_ms=latency_ms, - rssi=rssi, - country=country, - ip=ip, - asn=asn, - asn_org=asn_org, - ) - - admin_online_device_response.additional_properties = d - return admin_online_device_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_online_gateway_response.py b/openshock/rest/models/admin_online_gateway_response.py deleted file mode 100644 index e4452ad..0000000 --- a/openshock/rest/models/admin_online_gateway_response.py +++ /dev/null @@ -1,146 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminOnlineGatewayResponse") - - -@_attrs_define -class AdminOnlineGatewayResponse: - """ - Attributes: - id (str): - host (str): - port (int): - path_prefix (str): - country (str): - latitude (float | None): - longitude (float | None): - load (int): Load the gateway advertises for hub assignment, in percent - environment (str): - connected_hubs (int): - """ - - id: str - host: str - port: int - path_prefix: str - country: str - latitude: float | None - longitude: float | None - load: int - environment: str - connected_hubs: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = self.id - - host = self.host - - port = self.port - - path_prefix = self.path_prefix - - country = self.country - - latitude: float | None - latitude = self.latitude - - longitude: float | None - longitude = self.longitude - - load = self.load - - environment = self.environment - - connected_hubs = self.connected_hubs - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "host": host, - "port": port, - "pathPrefix": path_prefix, - "country": country, - "latitude": latitude, - "longitude": longitude, - "load": load, - "environment": environment, - "connectedHubs": connected_hubs, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = d.pop("id") - - host = d.pop("host") - - port = d.pop("port") - - path_prefix = d.pop("pathPrefix") - - country = d.pop("country") - - def _parse_latitude(data: object) -> float | None: - if data is None: - return data - return cast(float | None, data) - - latitude = _parse_latitude(d.pop("latitude")) - - def _parse_longitude(data: object) -> float | None: - if data is None: - return data - return cast(float | None, data) - - longitude = _parse_longitude(d.pop("longitude")) - - load = d.pop("load") - - environment = d.pop("environment") - - connected_hubs = d.pop("connectedHubs") - - admin_online_gateway_response = cls( - id=id, - host=host, - port=port, - path_prefix=path_prefix, - country=country, - latitude=latitude, - longitude=longitude, - load=load, - environment=environment, - connected_hubs=connected_hubs, - ) - - admin_online_gateway_response.additional_properties = d - return admin_online_gateway_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view.py b/openshock/rest/models/admin_user_view.py deleted file mode 100644 index f173c58..0000000 --- a/openshock/rest/models/admin_user_view.py +++ /dev/null @@ -1,324 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.password_hashing_algorithm import PasswordHashingAlgorithm -from ..models.role_type import RoleType - -if TYPE_CHECKING: - from ..models.admin_user_view_api_token import AdminUserViewApiToken - from ..models.admin_user_view_email_change import AdminUserViewEmailChange - from ..models.admin_user_view_hub import AdminUserViewHub - from ..models.admin_user_view_name_change import AdminUserViewNameChange - from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset - from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest - from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation - - -T = TypeVar("T", bound="AdminUserView") - - -@_attrs_define -class AdminUserView: - """ - Attributes: - id (UUID): - name (str): - email (str): - password_hash_type (PasswordHashingAlgorithm): - roles (list[RoleType]): - created_at (datetime.datetime): - activated_at (datetime.datetime | None): - created_by_automation_token_id (None | UUID): - activation_request (AdminUserViewUserActivationRequest | None): - deactivation (AdminUserViewUserDeactivation | None): - hubs (list[AdminUserViewHub]): - api_tokens (list[AdminUserViewApiToken]): - users_name_changes (list[AdminUserViewNameChange]): - users_email_changes (list[AdminUserViewEmailChange]): - password_resets (list[AdminUserViewPasswordReset]): - shocker_control_logs_count (int): - """ - - id: UUID - name: str - email: str - password_hash_type: PasswordHashingAlgorithm - roles: list[RoleType] - created_at: datetime.datetime - activated_at: datetime.datetime | None - created_by_automation_token_id: None | UUID - activation_request: AdminUserViewUserActivationRequest | None - deactivation: AdminUserViewUserDeactivation | None - hubs: list[AdminUserViewHub] - api_tokens: list[AdminUserViewApiToken] - users_name_changes: list[AdminUserViewNameChange] - users_email_changes: list[AdminUserViewEmailChange] - password_resets: list[AdminUserViewPasswordReset] - shocker_control_logs_count: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 - from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 - - id = str(self.id) - - name = self.name - - email = self.email - - password_hash_type = self.password_hash_type.value - - roles = [] - for roles_item_data in self.roles: - roles_item = roles_item_data.value - roles.append(roles_item) - - created_at = self.created_at.isoformat() - - activated_at: None | str - if isinstance(self.activated_at, datetime.datetime): - activated_at = self.activated_at.isoformat() - else: - activated_at = self.activated_at - - created_by_automation_token_id: None | str - if isinstance(self.created_by_automation_token_id, UUID): - created_by_automation_token_id = str(self.created_by_automation_token_id) - else: - created_by_automation_token_id = self.created_by_automation_token_id - - activation_request: dict[str, Any] | None - if isinstance(self.activation_request, AdminUserViewUserActivationRequest): - activation_request = self.activation_request.to_dict() - else: - activation_request = self.activation_request - - deactivation: dict[str, Any] | None - if isinstance(self.deactivation, AdminUserViewUserDeactivation): - deactivation = self.deactivation.to_dict() - else: - deactivation = self.deactivation - - hubs = [] - for hubs_item_data in self.hubs: - hubs_item = hubs_item_data.to_dict() - hubs.append(hubs_item) - - api_tokens = [] - for api_tokens_item_data in self.api_tokens: - api_tokens_item = api_tokens_item_data.to_dict() - api_tokens.append(api_tokens_item) - - users_name_changes = [] - for users_name_changes_item_data in self.users_name_changes: - users_name_changes_item = users_name_changes_item_data.to_dict() - users_name_changes.append(users_name_changes_item) - - users_email_changes = [] - for users_email_changes_item_data in self.users_email_changes: - users_email_changes_item = users_email_changes_item_data.to_dict() - users_email_changes.append(users_email_changes_item) - - password_resets = [] - for password_resets_item_data in self.password_resets: - password_resets_item = password_resets_item_data.to_dict() - password_resets.append(password_resets_item) - - shocker_control_logs_count = self.shocker_control_logs_count - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "email": email, - "passwordHashType": password_hash_type, - "roles": roles, - "createdAt": created_at, - "activatedAt": activated_at, - "createdByAutomationTokenId": created_by_automation_token_id, - "activationRequest": activation_request, - "deactivation": deactivation, - "hubs": hubs, - "apiTokens": api_tokens, - "usersNameChanges": users_name_changes, - "usersEmailChanges": users_email_changes, - "passwordResets": password_resets, - "shockerControlLogsCount": shocker_control_logs_count, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_user_view_api_token import AdminUserViewApiToken # noqa: PLC0415 - from ..models.admin_user_view_email_change import AdminUserViewEmailChange # noqa: PLC0415 - from ..models.admin_user_view_hub import AdminUserViewHub # noqa: PLC0415 - from ..models.admin_user_view_name_change import AdminUserViewNameChange # noqa: PLC0415 - from ..models.admin_user_view_password_reset import AdminUserViewPasswordReset # noqa: PLC0415 - from ..models.admin_user_view_user_activation_request import AdminUserViewUserActivationRequest # noqa: PLC0415 - from ..models.admin_user_view_user_deactivation import AdminUserViewUserDeactivation # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - email = d.pop("email") - - password_hash_type = PasswordHashingAlgorithm(d.pop("passwordHashType")) - - roles = [] - _roles = d.pop("roles") - for roles_item_data in _roles: - roles_item = RoleType(roles_item_data) - - roles.append(roles_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_activated_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - activated_at_type_1 = datetime.datetime.fromisoformat(data) - - return activated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - activated_at = _parse_activated_at(d.pop("activatedAt")) - - def _parse_created_by_automation_token_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - created_by_automation_token_id_type_1 = UUID(data) - - return created_by_automation_token_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) - - def _parse_activation_request(data: object) -> AdminUserViewUserActivationRequest | None: - if data is None: - return data - try: - if not isinstance(data, dict): - raise TypeError() - activation_request_type_1 = AdminUserViewUserActivationRequest.from_dict(data) - - return activation_request_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(AdminUserViewUserActivationRequest | None, data) - - activation_request = _parse_activation_request(d.pop("activationRequest")) - - def _parse_deactivation(data: object) -> AdminUserViewUserDeactivation | None: - if data is None: - return data - try: - if not isinstance(data, dict): - raise TypeError() - deactivation_type_1 = AdminUserViewUserDeactivation.from_dict(data) - - return deactivation_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(AdminUserViewUserDeactivation | None, data) - - deactivation = _parse_deactivation(d.pop("deactivation")) - - hubs = [] - _hubs = d.pop("hubs") - for hubs_item_data in _hubs: - hubs_item = AdminUserViewHub.from_dict(hubs_item_data) - - hubs.append(hubs_item) - - api_tokens = [] - _api_tokens = d.pop("apiTokens") - for api_tokens_item_data in _api_tokens: - api_tokens_item = AdminUserViewApiToken.from_dict(api_tokens_item_data) - - api_tokens.append(api_tokens_item) - - users_name_changes = [] - _users_name_changes = d.pop("usersNameChanges") - for users_name_changes_item_data in _users_name_changes: - users_name_changes_item = AdminUserViewNameChange.from_dict(users_name_changes_item_data) - - users_name_changes.append(users_name_changes_item) - - users_email_changes = [] - _users_email_changes = d.pop("usersEmailChanges") - for users_email_changes_item_data in _users_email_changes: - users_email_changes_item = AdminUserViewEmailChange.from_dict(users_email_changes_item_data) - - users_email_changes.append(users_email_changes_item) - - password_resets = [] - _password_resets = d.pop("passwordResets") - for password_resets_item_data in _password_resets: - password_resets_item = AdminUserViewPasswordReset.from_dict(password_resets_item_data) - - password_resets.append(password_resets_item) - - shocker_control_logs_count = d.pop("shockerControlLogsCount") - - admin_user_view = cls( - id=id, - name=name, - email=email, - password_hash_type=password_hash_type, - roles=roles, - created_at=created_at, - activated_at=activated_at, - created_by_automation_token_id=created_by_automation_token_id, - activation_request=activation_request, - deactivation=deactivation, - hubs=hubs, - api_tokens=api_tokens, - users_name_changes=users_name_changes, - users_email_changes=users_email_changes, - password_resets=password_resets, - shocker_control_logs_count=shocker_control_logs_count, - ) - - admin_user_view.additional_properties = d - return admin_user_view - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_api_token.py b/openshock/rest/models/admin_user_view_api_token.py deleted file mode 100644 index ca254d6..0000000 --- a/openshock/rest/models/admin_user_view_api_token.py +++ /dev/null @@ -1,156 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType - -T = TypeVar("T", bound="AdminUserViewApiToken") - - -@_attrs_define -class AdminUserViewApiToken: - """ - Attributes: - id (UUID): - name (str): - permissions (list[PermissionType]): - valid_until (datetime.datetime | None): - last_used (datetime.datetime | None): - created_at (datetime.datetime): - created_by_ip (str): An IPv4 or IPv6 address in its textual form. - """ - - id: UUID - name: str - permissions: list[PermissionType] - valid_until: datetime.datetime | None - last_used: datetime.datetime | None - created_at: datetime.datetime - created_by_ip: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - valid_until: None | str - if isinstance(self.valid_until, datetime.datetime): - valid_until = self.valid_until.isoformat() - else: - valid_until = self.valid_until - - last_used: None | str - if isinstance(self.last_used, datetime.datetime): - last_used = self.last_used.isoformat() - else: - last_used = self.last_used - - created_at = self.created_at.isoformat() - - created_by_ip = self.created_by_ip - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "permissions": permissions, - "validUntil": valid_until, - "lastUsed": last_used, - "createdAt": created_at, - "createdByIp": created_by_ip, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - def _parse_valid_until(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - valid_until_type_1 = datetime.datetime.fromisoformat(data) - - return valid_until_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - valid_until = _parse_valid_until(d.pop("validUntil")) - - def _parse_last_used(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - last_used = _parse_last_used(d.pop("lastUsed")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - created_by_ip = d.pop("createdByIp") - - admin_user_view_api_token = cls( - id=id, - name=name, - permissions=permissions, - valid_until=valid_until, - last_used=last_used, - created_at=created_at, - created_by_ip=created_by_ip, - ) - - admin_user_view_api_token.additional_properties = d - return admin_user_view_api_token - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_hub.py b/openshock/rest/models/admin_user_view_hub.py deleted file mode 100644 index e7620b7..0000000 --- a/openshock/rest/models/admin_user_view_hub.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_user_view_shocker import AdminUserViewShocker - - -T = TypeVar("T", bound="AdminUserViewHub") - - -@_attrs_define -class AdminUserViewHub: - """ - Attributes: - id (UUID): - name (str): - created_at (datetime.datetime): - shockers (list[AdminUserViewShocker]): - """ - - id: UUID - name: str - created_at: datetime.datetime - shockers: list[AdminUserViewShocker] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - created_at = self.created_at.isoformat() - - shockers = [] - for shockers_item_data in self.shockers: - shockers_item = shockers_item_data.to_dict() - shockers.append(shockers_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "createdAt": created_at, - "shockers": shockers, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_user_view_shocker import AdminUserViewShocker # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - shockers = [] - _shockers = d.pop("shockers") - for shockers_item_data in _shockers: - shockers_item = AdminUserViewShocker.from_dict(shockers_item_data) - - shockers.append(shockers_item) - - admin_user_view_hub = cls( - id=id, - name=name, - created_at=created_at, - shockers=shockers, - ) - - admin_user_view_hub.additional_properties = d - return admin_user_view_hub - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_shocker.py b/openshock/rest/models/admin_user_view_shocker.py deleted file mode 100644 index 996decd..0000000 --- a/openshock/rest/models/admin_user_view_shocker.py +++ /dev/null @@ -1,80 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewShocker") - - -@_attrs_define -class AdminUserViewShocker: - """ - Attributes: - id (UUID): - name (str): - created_at (datetime.datetime): - """ - - id: UUID - name: str - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - admin_user_view_shocker = cls( - id=id, - name=name, - created_at=created_at, - ) - - admin_user_view_shocker.additional_properties = d - return admin_user_view_shocker - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_activation_request.py b/openshock/rest/models/admin_user_view_user_activation_request.py deleted file mode 100644 index 89a85c8..0000000 --- a/openshock/rest/models/admin_user_view_user_activation_request.py +++ /dev/null @@ -1,71 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewUserActivationRequest") - - -@_attrs_define -class AdminUserViewUserActivationRequest: - """ - Attributes: - email_send_attempts (int): - created_at (datetime.datetime): - """ - - email_send_attempts: int - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - email_send_attempts = self.email_send_attempts - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "emailSendAttempts": email_send_attempts, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - email_send_attempts = d.pop("emailSendAttempts") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - admin_user_view_user_activation_request = cls( - email_send_attempts=email_send_attempts, - created_at=created_at, - ) - - admin_user_view_user_activation_request.additional_properties = d - return admin_user_view_user_activation_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_deactivation.py b/openshock/rest/models/admin_user_view_user_deactivation.py deleted file mode 100644 index a73d1b5..0000000 --- a/openshock/rest/models/admin_user_view_user_deactivation.py +++ /dev/null @@ -1,102 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_user_view_user_ref import AdminUserViewUserRef - - -T = TypeVar("T", bound="AdminUserViewUserDeactivation") - - -@_attrs_define -class AdminUserViewUserDeactivation: - """ - Attributes: - deactivated_by (AdminUserViewUserRef): - scheduled_deletion_time (datetime.datetime | None): - deactivated_at (datetime.datetime): - """ - - deactivated_by: AdminUserViewUserRef - scheduled_deletion_time: datetime.datetime | None - deactivated_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - deactivated_by = self.deactivated_by.to_dict() - - scheduled_deletion_time: None | str - if isinstance(self.scheduled_deletion_time, datetime.datetime): - scheduled_deletion_time = self.scheduled_deletion_time.isoformat() - else: - scheduled_deletion_time = self.scheduled_deletion_time - - deactivated_at = self.deactivated_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "deactivatedBy": deactivated_by, - "scheduledDeletionTime": scheduled_deletion_time, - "deactivatedAt": deactivated_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_user_view_user_ref import AdminUserViewUserRef # noqa: PLC0415 - - d = dict(src_dict) - deactivated_by = AdminUserViewUserRef.from_dict(d.pop("deactivatedBy")) - - def _parse_scheduled_deletion_time(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - scheduled_deletion_time_type_1 = datetime.datetime.fromisoformat(data) - - return scheduled_deletion_time_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - scheduled_deletion_time = _parse_scheduled_deletion_time(d.pop("scheduledDeletionTime")) - - deactivated_at = datetime.datetime.fromisoformat(d.pop("deactivatedAt")) - - admin_user_view_user_deactivation = cls( - deactivated_by=deactivated_by, - scheduled_deletion_time=scheduled_deletion_time, - deactivated_at=deactivated_at, - ) - - admin_user_view_user_deactivation.additional_properties = d - return admin_user_view_user_deactivation - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_user_ref.py b/openshock/rest/models/admin_user_view_user_ref.py deleted file mode 100644 index 0faa90f..0000000 --- a/openshock/rest/models/admin_user_view_user_ref.py +++ /dev/null @@ -1,71 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="AdminUserViewUserRef") - - -@_attrs_define -class AdminUserViewUserRef: - """ - Attributes: - id (UUID): - name (str): - """ - - id: UUID - name: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - admin_user_view_user_ref = cls( - id=id, - name=name, - ) - - admin_user_view_user_ref.additional_properties = d - return admin_user_view_user_ref - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_users_view.py b/openshock/rest/models/admin_users_view.py deleted file mode 100644 index 2dc3109..0000000 --- a/openshock/rest/models/admin_users_view.py +++ /dev/null @@ -1,304 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.password_hashing_algorithm import PasswordHashingAlgorithm -from ..models.role_type import RoleType - -T = TypeVar("T", bound="AdminUsersView") - - -@_attrs_define -class AdminUsersView: - """ - Attributes: - id (UUID): - name (str): - email (str): - password_hash_type (None | PasswordHashingAlgorithm): - roles (list[RoleType]): - created_at (datetime.datetime): - activated_at (datetime.datetime | None): - created_by_automation_token_id (None | UUID): - deactivated_at (datetime.datetime | None): - deactivated_by_user_id (None | UUID): - api_token_count (int): - password_reset_count (int): - shocker_user_share_count (int): - shocker_public_share_count (int): - email_change_request_count (int): - name_change_request_count (int): - device_count (int): - shocker_count (int): - shocker_control_log_count (int): - """ - - id: UUID - name: str - email: str - password_hash_type: None | PasswordHashingAlgorithm - roles: list[RoleType] - created_at: datetime.datetime - activated_at: datetime.datetime | None - created_by_automation_token_id: None | UUID - deactivated_at: datetime.datetime | None - deactivated_by_user_id: None | UUID - api_token_count: int - password_reset_count: int - shocker_user_share_count: int - shocker_public_share_count: int - email_change_request_count: int - name_change_request_count: int - device_count: int - shocker_count: int - shocker_control_log_count: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - email = self.email - - password_hash_type: None | str - if isinstance(self.password_hash_type, PasswordHashingAlgorithm): - password_hash_type = self.password_hash_type.value - else: - password_hash_type = self.password_hash_type - - roles = [] - for roles_item_data in self.roles: - roles_item = roles_item_data.value - roles.append(roles_item) - - created_at = self.created_at.isoformat() - - activated_at: None | str - if isinstance(self.activated_at, datetime.datetime): - activated_at = self.activated_at.isoformat() - else: - activated_at = self.activated_at - - created_by_automation_token_id: None | str - if isinstance(self.created_by_automation_token_id, UUID): - created_by_automation_token_id = str(self.created_by_automation_token_id) - else: - created_by_automation_token_id = self.created_by_automation_token_id - - deactivated_at: None | str - if isinstance(self.deactivated_at, datetime.datetime): - deactivated_at = self.deactivated_at.isoformat() - else: - deactivated_at = self.deactivated_at - - deactivated_by_user_id: None | str - if isinstance(self.deactivated_by_user_id, UUID): - deactivated_by_user_id = str(self.deactivated_by_user_id) - else: - deactivated_by_user_id = self.deactivated_by_user_id - - api_token_count = self.api_token_count - - password_reset_count = self.password_reset_count - - shocker_user_share_count = self.shocker_user_share_count - - shocker_public_share_count = self.shocker_public_share_count - - email_change_request_count = self.email_change_request_count - - name_change_request_count = self.name_change_request_count - - device_count = self.device_count - - shocker_count = self.shocker_count - - shocker_control_log_count = self.shocker_control_log_count - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "email": email, - "passwordHashType": password_hash_type, - "roles": roles, - "createdAt": created_at, - "activatedAt": activated_at, - "createdByAutomationTokenId": created_by_automation_token_id, - "deactivatedAt": deactivated_at, - "deactivatedByUserId": deactivated_by_user_id, - "apiTokenCount": api_token_count, - "passwordResetCount": password_reset_count, - "shockerUserShareCount": shocker_user_share_count, - "shockerPublicShareCount": shocker_public_share_count, - "emailChangeRequestCount": email_change_request_count, - "nameChangeRequestCount": name_change_request_count, - "deviceCount": device_count, - "shockerCount": shocker_count, - "shockerControlLogCount": shocker_control_log_count, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - email = d.pop("email") - - def _parse_password_hash_type(data: object) -> None | PasswordHashingAlgorithm: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - password_hash_type_type_1 = PasswordHashingAlgorithm(data) - - return password_hash_type_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | PasswordHashingAlgorithm, data) - - password_hash_type = _parse_password_hash_type(d.pop("passwordHashType")) - - roles = [] - _roles = d.pop("roles") - for roles_item_data in _roles: - roles_item = RoleType(roles_item_data) - - roles.append(roles_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_activated_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - activated_at_type_1 = datetime.datetime.fromisoformat(data) - - return activated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - activated_at = _parse_activated_at(d.pop("activatedAt")) - - def _parse_created_by_automation_token_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - created_by_automation_token_id_type_1 = UUID(data) - - return created_by_automation_token_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - created_by_automation_token_id = _parse_created_by_automation_token_id(d.pop("createdByAutomationTokenId")) - - def _parse_deactivated_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - deactivated_at_type_1 = datetime.datetime.fromisoformat(data) - - return deactivated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - deactivated_at = _parse_deactivated_at(d.pop("deactivatedAt")) - - def _parse_deactivated_by_user_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - deactivated_by_user_id_type_1 = UUID(data) - - return deactivated_by_user_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - deactivated_by_user_id = _parse_deactivated_by_user_id(d.pop("deactivatedByUserId")) - - api_token_count = d.pop("apiTokenCount") - - password_reset_count = d.pop("passwordResetCount") - - shocker_user_share_count = d.pop("shockerUserShareCount") - - shocker_public_share_count = d.pop("shockerPublicShareCount") - - email_change_request_count = d.pop("emailChangeRequestCount") - - name_change_request_count = d.pop("nameChangeRequestCount") - - device_count = d.pop("deviceCount") - - shocker_count = d.pop("shockerCount") - - shocker_control_log_count = d.pop("shockerControlLogCount") - - admin_users_view = cls( - id=id, - name=name, - email=email, - password_hash_type=password_hash_type, - roles=roles, - created_at=created_at, - activated_at=activated_at, - created_by_automation_token_id=created_by_automation_token_id, - deactivated_at=deactivated_at, - deactivated_by_user_id=deactivated_by_user_id, - api_token_count=api_token_count, - password_reset_count=password_reset_count, - shocker_user_share_count=shocker_user_share_count, - shocker_public_share_count=shocker_public_share_count, - email_change_request_count=email_change_request_count, - name_change_request_count=name_change_request_count, - device_count=device_count, - shocker_count=shocker_count, - shocker_control_log_count=shocker_control_log_count, - ) - - admin_users_view.additional_properties = d - return admin_users_view - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_action.py b/openshock/rest/models/audit_action.py deleted file mode 100644 index e7bcff5..0000000 --- a/openshock/rest/models/audit_action.py +++ /dev/null @@ -1,26 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditAction(StrEnum): - ACCOUNTDEACTIVATED = "AccountDeactivated" - ACCOUNTDELETED = "AccountDeleted" - ACCOUNTREACTIVATED = "AccountReactivated" - APITOKENCREATED = "ApiTokenCreated" - APITOKENDELETED = "ApiTokenDeleted" - AUTOMATIONTOKENCREATED = "AutomationTokenCreated" - AUTOMATIONTOKENDELETED = "AutomationTokenDeleted" - AUTOMATIONTOKENROTATED = "AutomationTokenRotated" - AUTOMATIONTOKENUPDATED = "AutomationTokenUpdated" - AUTOMATIONTOKENUSED = "AutomationTokenUsed" - EMAILCHANGED = "EmailChanged" - EMAILCHANGEREQUESTED = "EmailChangeRequested" - LOGIN = "Login" - LOGOUT = "Logout" - OAUTHCONNECTED = "OAuthConnected" - OAUTHDISCONNECTED = "OAuthDisconnected" - PASSWORDCHANGED = "PasswordChanged" - USERNAMECHANGED = "UsernameChanged" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_log_entry_response.py b/openshock/rest/models/audit_log_entry_response.py deleted file mode 100644 index 382f07a..0000000 --- a/openshock/rest/models/audit_log_entry_response.py +++ /dev/null @@ -1,432 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_action import AuditAction - -if TYPE_CHECKING: - from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata - from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata - from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata - from ..models.audit_metadata_automation_token_created_metadata import AuditMetadataAutomationTokenCreatedMetadata - from ..models.audit_metadata_automation_token_deleted_metadata import AuditMetadataAutomationTokenDeletedMetadata - from ..models.audit_metadata_automation_token_rotated_metadata import AuditMetadataAutomationTokenRotatedMetadata - from ..models.audit_metadata_automation_token_updated_metadata import AuditMetadataAutomationTokenUpdatedMetadata - from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata - from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata - from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata - from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata - from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata - from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata - from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata - - -T = TypeVar("T", bound="AuditLogEntryResponse") - - -@_attrs_define -class AuditLogEntryResponse: - """ - Attributes: - id (UUID): - user_id (UUID): - actor_id (None | UUID): - action (AuditAction): - reason (None | str): - ip_address (None | str): An IPv4 or IPv6 address in its textual form. - user_agent (None | str): - metadata (AuditMetadataAccountDeactivatedMetadata | AuditMetadataApiTokenCreatedMetadata | - AuditMetadataApiTokenDeletedMetadata | AuditMetadataAutomationTokenCreatedMetadata | - AuditMetadataAutomationTokenDeletedMetadata | AuditMetadataAutomationTokenRotatedMetadata | - AuditMetadataAutomationTokenUpdatedMetadata | AuditMetadataAutomationTokenUsedMetadata | - AuditMetadataEmailChangedMetadata | AuditMetadataEmailChangeRequestedMetadata | AuditMetadataLoginMetadata | - AuditMetadataOAuthConnectedMetadata | AuditMetadataOAuthDisconnectedMetadata | - AuditMetadataUsernameChangedMetadata | None): - created_at (datetime.datetime): - """ - - id: UUID - user_id: UUID - actor_id: None | UUID - action: AuditAction - reason: None | str - ip_address: None | str - user_agent: None | str - metadata: ( - AuditMetadataAccountDeactivatedMetadata - | AuditMetadataApiTokenCreatedMetadata - | AuditMetadataApiTokenDeletedMetadata - | AuditMetadataAutomationTokenCreatedMetadata - | AuditMetadataAutomationTokenDeletedMetadata - | AuditMetadataAutomationTokenRotatedMetadata - | AuditMetadataAutomationTokenUpdatedMetadata - | AuditMetadataAutomationTokenUsedMetadata - | AuditMetadataEmailChangedMetadata - | AuditMetadataEmailChangeRequestedMetadata - | AuditMetadataLoginMetadata - | AuditMetadataOAuthConnectedMetadata - | AuditMetadataOAuthDisconnectedMetadata - | AuditMetadataUsernameChangedMetadata - | None - ) - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 - from ..models.audit_metadata_automation_token_created_metadata import ( - AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_deleted_metadata import ( - AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_rotated_metadata import ( - AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_updated_metadata import ( - AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 - from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 - - id = str(self.id) - - user_id = str(self.user_id) - - actor_id: None | str - if isinstance(self.actor_id, UUID): - actor_id = str(self.actor_id) - else: - actor_id = self.actor_id - - action = self.action.value - - reason: None | str - reason = self.reason - - ip_address: None | str - ip_address = self.ip_address - - user_agent: None | str - user_agent = self.user_agent - - metadata: dict[str, Any] | None - if isinstance(self.metadata, AuditMetadataLoginMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataUsernameChangedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataEmailChangeRequestedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataEmailChangedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataApiTokenCreatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataApiTokenDeletedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataOAuthConnectedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataOAuthDisconnectedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAccountDeactivatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenCreatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenUpdatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenRotatedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenDeletedMetadata): - metadata = self.metadata.to_dict() - elif isinstance(self.metadata, AuditMetadataAutomationTokenUsedMetadata): - metadata = self.metadata.to_dict() - else: - metadata = self.metadata - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "userId": user_id, - "actorId": actor_id, - "action": action, - "reason": reason, - "ipAddress": ip_address, - "userAgent": user_agent, - "metadata": metadata, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.audit_metadata_account_deactivated_metadata import AuditMetadataAccountDeactivatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_created_metadata import AuditMetadataApiTokenCreatedMetadata # noqa: PLC0415 - from ..models.audit_metadata_api_token_deleted_metadata import AuditMetadataApiTokenDeletedMetadata # noqa: PLC0415 - from ..models.audit_metadata_automation_token_created_metadata import ( - AuditMetadataAutomationTokenCreatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_deleted_metadata import ( - AuditMetadataAutomationTokenDeletedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_rotated_metadata import ( - AuditMetadataAutomationTokenRotatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_updated_metadata import ( - AuditMetadataAutomationTokenUpdatedMetadata, # noqa: PLC0415 - ) - from ..models.audit_metadata_automation_token_used_metadata import AuditMetadataAutomationTokenUsedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_change_requested_metadata import AuditMetadataEmailChangeRequestedMetadata # noqa: PLC0415 - from ..models.audit_metadata_email_changed_metadata import AuditMetadataEmailChangedMetadata # noqa: PLC0415 - from ..models.audit_metadata_login_metadata import AuditMetadataLoginMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_connected_metadata import AuditMetadataOAuthConnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_o_auth_disconnected_metadata import AuditMetadataOAuthDisconnectedMetadata # noqa: PLC0415 - from ..models.audit_metadata_username_changed_metadata import AuditMetadataUsernameChangedMetadata # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - user_id = UUID(d.pop("userId")) - - def _parse_actor_id(data: object) -> None | UUID: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - actor_id_type_1 = UUID(data) - - return actor_id_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | UUID, data) - - actor_id = _parse_actor_id(d.pop("actorId")) - - action = AuditAction(d.pop("action")) - - def _parse_reason(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - reason = _parse_reason(d.pop("reason")) - - def _parse_ip_address(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - ip_address = _parse_ip_address(d.pop("ipAddress")) - - def _parse_user_agent(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - user_agent = _parse_user_agent(d.pop("userAgent")) - - def _parse_metadata( - data: object, - ) -> ( - AuditMetadataAccountDeactivatedMetadata - | AuditMetadataApiTokenCreatedMetadata - | AuditMetadataApiTokenDeletedMetadata - | AuditMetadataAutomationTokenCreatedMetadata - | AuditMetadataAutomationTokenDeletedMetadata - | AuditMetadataAutomationTokenRotatedMetadata - | AuditMetadataAutomationTokenUpdatedMetadata - | AuditMetadataAutomationTokenUsedMetadata - | AuditMetadataEmailChangedMetadata - | AuditMetadataEmailChangeRequestedMetadata - | AuditMetadataLoginMetadata - | AuditMetadataOAuthConnectedMetadata - | AuditMetadataOAuthDisconnectedMetadata - | AuditMetadataUsernameChangedMetadata - | None - ): - if data is None: - return data - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_0 = AuditMetadataLoginMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_0 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_1 = AuditMetadataUsernameChangedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_2 = AuditMetadataEmailChangeRequestedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_2 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_3 = AuditMetadataEmailChangedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_3 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_4 = AuditMetadataApiTokenCreatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_4 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_5 = AuditMetadataApiTokenDeletedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_5 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_6 = AuditMetadataOAuthConnectedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_6 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_7 = AuditMetadataOAuthDisconnectedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_7 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_8 = AuditMetadataAccountDeactivatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_8 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_9 = AuditMetadataAutomationTokenCreatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_9 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_10 = AuditMetadataAutomationTokenUpdatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_10 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_11 = AuditMetadataAutomationTokenRotatedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_11 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_12 = AuditMetadataAutomationTokenDeletedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_12 - except (TypeError, ValueError, AttributeError, KeyError): - pass - try: - if not isinstance(data, dict): - raise TypeError() - componentsschemas_audit_metadata_type_13 = AuditMetadataAutomationTokenUsedMetadata.from_dict(data) - - return componentsschemas_audit_metadata_type_13 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast( - AuditMetadataAccountDeactivatedMetadata - | AuditMetadataApiTokenCreatedMetadata - | AuditMetadataApiTokenDeletedMetadata - | AuditMetadataAutomationTokenCreatedMetadata - | AuditMetadataAutomationTokenDeletedMetadata - | AuditMetadataAutomationTokenRotatedMetadata - | AuditMetadataAutomationTokenUpdatedMetadata - | AuditMetadataAutomationTokenUsedMetadata - | AuditMetadataEmailChangedMetadata - | AuditMetadataEmailChangeRequestedMetadata - | AuditMetadataLoginMetadata - | AuditMetadataOAuthConnectedMetadata - | AuditMetadataOAuthDisconnectedMetadata - | AuditMetadataUsernameChangedMetadata - | None, - data, - ) - - metadata = _parse_metadata(d.pop("metadata")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - audit_log_entry_response = cls( - id=id, - user_id=user_id, - actor_id=actor_id, - action=action, - reason=reason, - ip_address=ip_address, - user_agent=user_agent, - metadata=metadata, - created_at=created_at, - ) - - audit_log_entry_response.additional_properties = d - return audit_log_entry_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata.py deleted file mode 100644 index 0c04186..0000000 --- a/openshock/rest/models/audit_metadata_account_deactivated_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_account_deactivated_metadata_t import AuditMetadataAccountDeactivatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAccountDeactivatedMetadata") - - -@_attrs_define -class AuditMetadataAccountDeactivatedMetadata: - """ - Attributes: - delete_later (bool): - t (AuditMetadataAccountDeactivatedMetadataT | Unset): - """ - - delete_later: bool - t: AuditMetadataAccountDeactivatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - delete_later = self.delete_later - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "deleteLater": delete_later, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - delete_later = d.pop("deleteLater") - - _t = d.pop("t", UNSET) - t: AuditMetadataAccountDeactivatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAccountDeactivatedMetadataT(_t) - - audit_metadata_account_deactivated_metadata = cls( - delete_later=delete_later, - t=t, - ) - - audit_metadata_account_deactivated_metadata.additional_properties = d - return audit_metadata_account_deactivated_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py b/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py deleted file mode 100644 index f5a287d..0000000 --- a/openshock/rest/models/audit_metadata_account_deactivated_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAccountDeactivatedMetadataT(StrEnum): - ACCOUNTDEACTIVATED = "accountDeactivated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata.py b/openshock/rest/models/audit_metadata_api_token_created_metadata.py deleted file mode 100644 index f813d7f..0000000 --- a/openshock/rest/models/audit_metadata_api_token_created_metadata.py +++ /dev/null @@ -1,98 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_api_token_created_metadata_t import AuditMetadataApiTokenCreatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataApiTokenCreatedMetadata") - - -@_attrs_define -class AuditMetadataApiTokenCreatedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - permissions (list[str]): - t (AuditMetadataApiTokenCreatedMetadataT | Unset): - """ - - token_id: UUID - name: str - permissions: list[str] - t: AuditMetadataApiTokenCreatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - permissions = self.permissions - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "permissions": permissions, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - permissions = cast(list[str], d.pop("permissions")) - - _t = d.pop("t", UNSET) - t: AuditMetadataApiTokenCreatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataApiTokenCreatedMetadataT(_t) - - audit_metadata_api_token_created_metadata = cls( - token_id=token_id, - name=name, - permissions=permissions, - t=t, - ) - - audit_metadata_api_token_created_metadata.additional_properties = d - return audit_metadata_api_token_created_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py deleted file mode 100644 index 59024ee..0000000 --- a/openshock/rest/models/audit_metadata_api_token_created_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataApiTokenCreatedMetadataT(StrEnum): - APITOKENCREATED = "apiTokenCreated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py deleted file mode 100644 index 1087190..0000000 --- a/openshock/rest/models/audit_metadata_api_token_deleted_metadata.py +++ /dev/null @@ -1,90 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_api_token_deleted_metadata_t import AuditMetadataApiTokenDeletedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataApiTokenDeletedMetadata") - - -@_attrs_define -class AuditMetadataApiTokenDeletedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - t (AuditMetadataApiTokenDeletedMetadataT | Unset): - """ - - token_id: UUID - name: str - t: AuditMetadataApiTokenDeletedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - _t = d.pop("t", UNSET) - t: AuditMetadataApiTokenDeletedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataApiTokenDeletedMetadataT(_t) - - audit_metadata_api_token_deleted_metadata = cls( - token_id=token_id, - name=name, - t=t, - ) - - audit_metadata_api_token_deleted_metadata.additional_properties = d - return audit_metadata_api_token_deleted_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py deleted file mode 100644 index de49448..0000000 --- a/openshock/rest/models/audit_metadata_api_token_deleted_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataApiTokenDeletedMetadataT(StrEnum): - APITOKENDELETED = "apiTokenDeleted" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata.py deleted file mode 100644 index 78c3add..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_created_metadata.py +++ /dev/null @@ -1,120 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_created_metadata_t import AuditMetadataAutomationTokenCreatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenCreatedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenCreatedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - types (list[str]): - auto_cleanup_users (bool): - auto_cleanup_after (None | str): - t (AuditMetadataAutomationTokenCreatedMetadataT | Unset): - """ - - token_id: UUID - name: str - types: list[str] - auto_cleanup_users: bool - auto_cleanup_after: None | str - t: AuditMetadataAutomationTokenCreatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - types = self.types - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str - auto_cleanup_after = self.auto_cleanup_after - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "types": types, - "autoCleanupUsers": auto_cleanup_users, - "autoCleanupAfter": auto_cleanup_after, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - types = cast(list[str], d.pop("types")) - - auto_cleanup_users = d.pop("autoCleanupUsers") - - def _parse_auto_cleanup_after(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenCreatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenCreatedMetadataT(_t) - - audit_metadata_automation_token_created_metadata = cls( - token_id=token_id, - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - t=t, - ) - - audit_metadata_automation_token_created_metadata.additional_properties = d - return audit_metadata_automation_token_created_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py deleted file mode 100644 index 71728a5..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_created_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenCreatedMetadataT(StrEnum): - AUTOMATIONTOKENCREATED = "automationTokenCreated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py deleted file mode 100644 index 98e47b2..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata.py +++ /dev/null @@ -1,99 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_deleted_metadata_t import AuditMetadataAutomationTokenDeletedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenDeletedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenDeletedMetadata: - """The token was deleted together with the int AutomationTokenDeletedMetadata.DeletedAccountCount accounts it created. - - Attributes: - token_id (UUID): - name (str): - deleted_account_count (int): - t (AuditMetadataAutomationTokenDeletedMetadataT | Unset): - """ - - token_id: UUID - name: str - deleted_account_count: int - t: AuditMetadataAutomationTokenDeletedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - deleted_account_count = self.deleted_account_count - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "deletedAccountCount": deleted_account_count, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - deleted_account_count = d.pop("deletedAccountCount") - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenDeletedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenDeletedMetadataT(_t) - - audit_metadata_automation_token_deleted_metadata = cls( - token_id=token_id, - name=name, - deleted_account_count=deleted_account_count, - t=t, - ) - - audit_metadata_automation_token_deleted_metadata.additional_properties = d - return audit_metadata_automation_token_deleted_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py deleted file mode 100644 index 6e81913..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_deleted_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenDeletedMetadataT(StrEnum): - AUTOMATIONTOKENDELETED = "automationTokenDeleted" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py deleted file mode 100644 index 86b917e..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata.py +++ /dev/null @@ -1,90 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_rotated_metadata_t import AuditMetadataAutomationTokenRotatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenRotatedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenRotatedMetadata: - """ - Attributes: - token_id (UUID): - name (str): - t (AuditMetadataAutomationTokenRotatedMetadataT | Unset): - """ - - token_id: UUID - name: str - t: AuditMetadataAutomationTokenRotatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenRotatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenRotatedMetadataT(_t) - - audit_metadata_automation_token_rotated_metadata = cls( - token_id=token_id, - name=name, - t=t, - ) - - audit_metadata_automation_token_rotated_metadata.additional_properties = d - return audit_metadata_automation_token_rotated_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py deleted file mode 100644 index b9df839..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_rotated_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenRotatedMetadataT(StrEnum): - AUTOMATIONTOKENROTATED = "automationTokenRotated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py deleted file mode 100644 index 083f9d7..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_updated_metadata.py +++ /dev/null @@ -1,121 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_updated_metadata_t import AuditMetadataAutomationTokenUpdatedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenUpdatedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenUpdatedMetadata: - """The token's settings after the update. - - Attributes: - token_id (UUID): - name (str): - types (list[str]): - auto_cleanup_users (bool): - auto_cleanup_after (None | str): - t (AuditMetadataAutomationTokenUpdatedMetadataT | Unset): - """ - - token_id: UUID - name: str - types: list[str] - auto_cleanup_users: bool - auto_cleanup_after: None | str - t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - types = self.types - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str - auto_cleanup_after = self.auto_cleanup_after - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "types": types, - "autoCleanupUsers": auto_cleanup_users, - "autoCleanupAfter": auto_cleanup_after, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - types = cast(list[str], d.pop("types")) - - auto_cleanup_users = d.pop("autoCleanupUsers") - - def _parse_auto_cleanup_after(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter")) - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenUpdatedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenUpdatedMetadataT(_t) - - audit_metadata_automation_token_updated_metadata = cls( - token_id=token_id, - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - t=t, - ) - - audit_metadata_automation_token_updated_metadata.additional_properties = d - return audit_metadata_automation_token_updated_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py deleted file mode 100644 index e47bd5e..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_updated_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenUpdatedMetadataT(StrEnum): - AUTOMATIONTOKENUPDATED = "automationTokenUpdated" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata.py deleted file mode 100644 index d9bba52..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_used_metadata.py +++ /dev/null @@ -1,100 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_automation_token_used_metadata_t import AuditMetadataAutomationTokenUsedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataAutomationTokenUsedMetadata") - - -@_attrs_define -class AuditMetadataAutomationTokenUsedMetadata: - """An automation token was used on this account. string AutomationTokenUsedMetadata.Flow is a `AutomationTokenFlow` - name. - - Attributes: - token_id (UUID): - name (str): - flow (str): - t (AuditMetadataAutomationTokenUsedMetadataT | Unset): - """ - - token_id: UUID - name: str - flow: str - t: AuditMetadataAutomationTokenUsedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - token_id = str(self.token_id) - - name = self.name - - flow = self.flow - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "tokenId": token_id, - "name": name, - "flow": flow, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - token_id = UUID(d.pop("tokenId")) - - name = d.pop("name") - - flow = d.pop("flow") - - _t = d.pop("t", UNSET) - t: AuditMetadataAutomationTokenUsedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataAutomationTokenUsedMetadataT(_t) - - audit_metadata_automation_token_used_metadata = cls( - token_id=token_id, - name=name, - flow=flow, - t=t, - ) - - audit_metadata_automation_token_used_metadata.additional_properties = d - return audit_metadata_automation_token_used_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py b/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py deleted file mode 100644 index 591cb62..0000000 --- a/openshock/rest/models/audit_metadata_automation_token_used_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataAutomationTokenUsedMetadataT(StrEnum): - AUTOMATIONTOKENUSED = "automationTokenUsed" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata.py deleted file mode 100644 index c1e7b8a..0000000 --- a/openshock/rest/models/audit_metadata_email_change_requested_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_email_change_requested_metadata_t import AuditMetadataEmailChangeRequestedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataEmailChangeRequestedMetadata") - - -@_attrs_define -class AuditMetadataEmailChangeRequestedMetadata: - """ - Attributes: - new_email (str): - t (AuditMetadataEmailChangeRequestedMetadataT | Unset): - """ - - new_email: str - t: AuditMetadataEmailChangeRequestedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - new_email = self.new_email - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "newEmail": new_email, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - new_email = d.pop("newEmail") - - _t = d.pop("t", UNSET) - t: AuditMetadataEmailChangeRequestedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataEmailChangeRequestedMetadataT(_t) - - audit_metadata_email_change_requested_metadata = cls( - new_email=new_email, - t=t, - ) - - audit_metadata_email_change_requested_metadata.additional_properties = d - return audit_metadata_email_change_requested_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py b/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py deleted file mode 100644 index 5cf3cd0..0000000 --- a/openshock/rest/models/audit_metadata_email_change_requested_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataEmailChangeRequestedMetadataT(StrEnum): - EMAILCHANGEREQUESTED = "emailChangeRequested" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata.py b/openshock/rest/models/audit_metadata_email_changed_metadata.py deleted file mode 100644 index 59f2ac4..0000000 --- a/openshock/rest/models/audit_metadata_email_changed_metadata.py +++ /dev/null @@ -1,89 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_email_changed_metadata_t import AuditMetadataEmailChangedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataEmailChangedMetadata") - - -@_attrs_define -class AuditMetadataEmailChangedMetadata: - """ - Attributes: - old (str): - new (str): - t (AuditMetadataEmailChangedMetadataT | Unset): - """ - - old: str - new: str - t: AuditMetadataEmailChangedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - old = self.old - - new = self.new - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "old": old, - "new": new, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - old = d.pop("old") - - new = d.pop("new") - - _t = d.pop("t", UNSET) - t: AuditMetadataEmailChangedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataEmailChangedMetadataT(_t) - - audit_metadata_email_changed_metadata = cls( - old=old, - new=new, - t=t, - ) - - audit_metadata_email_changed_metadata.additional_properties = d - return audit_metadata_email_changed_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_email_changed_metadata_t.py b/openshock/rest/models/audit_metadata_email_changed_metadata_t.py deleted file mode 100644 index 1bcee56..0000000 --- a/openshock/rest/models/audit_metadata_email_changed_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataEmailChangedMetadataT(StrEnum): - EMAILCHANGED = "emailChanged" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_login_metadata.py b/openshock/rest/models/audit_metadata_login_metadata.py deleted file mode 100644 index 56879d2..0000000 --- a/openshock/rest/models/audit_metadata_login_metadata.py +++ /dev/null @@ -1,82 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_login_metadata_t import AuditMetadataLoginMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataLoginMetadata") - - -@_attrs_define -class AuditMetadataLoginMetadata: - """ - Attributes: - session_id (UUID): - t (AuditMetadataLoginMetadataT | Unset): - """ - - session_id: UUID - t: AuditMetadataLoginMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - session_id = str(self.session_id) - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "sessionId": session_id, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - session_id = UUID(d.pop("sessionId")) - - _t = d.pop("t", UNSET) - t: AuditMetadataLoginMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataLoginMetadataT(_t) - - audit_metadata_login_metadata = cls( - session_id=session_id, - t=t, - ) - - audit_metadata_login_metadata.additional_properties = d - return audit_metadata_login_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_login_metadata_t.py b/openshock/rest/models/audit_metadata_login_metadata_t.py deleted file mode 100644 index d98a11a..0000000 --- a/openshock/rest/models/audit_metadata_login_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataLoginMetadataT(StrEnum): - LOGIN = "login" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py deleted file mode 100644 index 96f4469..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_connected_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_o_auth_connected_metadata_t import AuditMetadataOAuthConnectedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataOAuthConnectedMetadata") - - -@_attrs_define -class AuditMetadataOAuthConnectedMetadata: - """ - Attributes: - provider (str): - t (AuditMetadataOAuthConnectedMetadataT | Unset): - """ - - provider: str - t: AuditMetadataOAuthConnectedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - provider = self.provider - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "provider": provider, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - provider = d.pop("provider") - - _t = d.pop("t", UNSET) - t: AuditMetadataOAuthConnectedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataOAuthConnectedMetadataT(_t) - - audit_metadata_o_auth_connected_metadata = cls( - provider=provider, - t=t, - ) - - audit_metadata_o_auth_connected_metadata.additional_properties = d - return audit_metadata_o_auth_connected_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py deleted file mode 100644 index 6d80bfc..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_connected_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataOAuthConnectedMetadataT(StrEnum): - OAUTHCONNECTED = "oauthConnected" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py deleted file mode 100644 index b7ee896..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata.py +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_o_auth_disconnected_metadata_t import AuditMetadataOAuthDisconnectedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataOAuthDisconnectedMetadata") - - -@_attrs_define -class AuditMetadataOAuthDisconnectedMetadata: - """ - Attributes: - provider (str): - t (AuditMetadataOAuthDisconnectedMetadataT | Unset): - """ - - provider: str - t: AuditMetadataOAuthDisconnectedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - provider = self.provider - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "provider": provider, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - provider = d.pop("provider") - - _t = d.pop("t", UNSET) - t: AuditMetadataOAuthDisconnectedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataOAuthDisconnectedMetadataT(_t) - - audit_metadata_o_auth_disconnected_metadata = cls( - provider=provider, - t=t, - ) - - audit_metadata_o_auth_disconnected_metadata.additional_properties = d - return audit_metadata_o_auth_disconnected_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py b/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py deleted file mode 100644 index c528f73..0000000 --- a/openshock/rest/models/audit_metadata_o_auth_disconnected_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataOAuthDisconnectedMetadataT(StrEnum): - OAUTHDISCONNECTED = "oauthDisconnected" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata.py b/openshock/rest/models/audit_metadata_username_changed_metadata.py deleted file mode 100644 index a1ee8ea..0000000 --- a/openshock/rest/models/audit_metadata_username_changed_metadata.py +++ /dev/null @@ -1,89 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.audit_metadata_username_changed_metadata_t import AuditMetadataUsernameChangedMetadataT -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AuditMetadataUsernameChangedMetadata") - - -@_attrs_define -class AuditMetadataUsernameChangedMetadata: - """ - Attributes: - old (str): - new (str): - t (AuditMetadataUsernameChangedMetadataT | Unset): - """ - - old: str - new: str - t: AuditMetadataUsernameChangedMetadataT | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - old = self.old - - new = self.new - - t: str | Unset = UNSET - if not isinstance(self.t, Unset): - t = self.t.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "old": old, - "new": new, - } - ) - if t is not UNSET: - field_dict["t"] = t - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - old = d.pop("old") - - new = d.pop("new") - - _t = d.pop("t", UNSET) - t: AuditMetadataUsernameChangedMetadataT | Unset - if isinstance(_t, Unset): - t = UNSET - else: - t = AuditMetadataUsernameChangedMetadataT(_t) - - audit_metadata_username_changed_metadata = cls( - old=old, - new=new, - t=t, - ) - - audit_metadata_username_changed_metadata.additional_properties = d - return audit_metadata_username_changed_metadata - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/audit_metadata_username_changed_metadata_t.py b/openshock/rest/models/audit_metadata_username_changed_metadata_t.py deleted file mode 100644 index 84465c1..0000000 --- a/openshock/rest/models/audit_metadata_username_changed_metadata_t.py +++ /dev/null @@ -1,9 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AuditMetadataUsernameChangedMetadataT(StrEnum): - USERNAMECHANGED = "usernameChanged" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/automation_token_dto.py b/openshock/rest/models/automation_token_dto.py deleted file mode 100644 index 224cf7a..0000000 --- a/openshock/rest/models/automation_token_dto.py +++ /dev/null @@ -1,197 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="AutomationTokenDto") - - -@_attrs_define -class AutomationTokenDto: - """ - Attributes: - id (UUID): - name (str): - types (list[AutomationTokenType]): - created_at (datetime.datetime): - last_used_at (datetime.datetime | None | Unset): - last_rotated_at (datetime.datetime | None | Unset): - use_count (int | Unset): - auto_cleanup_users (bool | Unset): - auto_cleanup_after (None | str | Unset): - """ - - id: UUID - name: str - types: list[AutomationTokenType] - created_at: datetime.datetime - last_used_at: datetime.datetime | None | Unset = UNSET - last_rotated_at: datetime.datetime | None | Unset = UNSET - use_count: int | Unset = UNSET - auto_cleanup_users: bool | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - types = [] - for types_item_data in self.types: - types_item = types_item_data.value - types.append(types_item) - - created_at = self.created_at.isoformat() - - last_used_at: None | str | Unset - if isinstance(self.last_used_at, Unset): - last_used_at = UNSET - elif isinstance(self.last_used_at, datetime.datetime): - last_used_at = self.last_used_at.isoformat() - else: - last_used_at = self.last_used_at - - last_rotated_at: None | str | Unset - if isinstance(self.last_rotated_at, Unset): - last_rotated_at = UNSET - elif isinstance(self.last_rotated_at, datetime.datetime): - last_rotated_at = self.last_rotated_at.isoformat() - else: - last_rotated_at = self.last_rotated_at - - use_count = self.use_count - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "types": types, - "createdAt": created_at, - } - ) - if last_used_at is not UNSET: - field_dict["lastUsedAt"] = last_used_at - if last_rotated_at is not UNSET: - field_dict["lastRotatedAt"] = last_rotated_at - if use_count is not UNSET: - field_dict["useCount"] = use_count - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - types = [] - _types = d.pop("types") - for types_item_data in _types: - types_item = AutomationTokenType(types_item_data) - - types.append(types_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_last_used_at(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_at_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - last_used_at = _parse_last_used_at(d.pop("lastUsedAt", UNSET)) - - def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) - - return last_rotated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) - - use_count = d.pop("useCount", UNSET) - - auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - automation_token_dto = cls( - id=id, - name=name, - types=types, - created_at=created_at, - last_used_at=last_used_at, - last_rotated_at=last_rotated_at, - use_count=use_count, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - automation_token_dto.additional_properties = d - return automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/automation_token_type.py b/openshock/rest/models/automation_token_type.py deleted file mode 100644 index b270e30..0000000 --- a/openshock/rest/models/automation_token_type.py +++ /dev/null @@ -1,11 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class AutomationTokenType(StrEnum): - CONTROLSTATSREAD = "ControlStatsRead" - RATELIMIT = "RateLimit" - TURNSTILE = "Turnstile" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/change_email_request.py b/openshock/rest/models/change_email_request.py deleted file mode 100644 index 918e9c6..0000000 --- a/openshock/rest/models/change_email_request.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="ChangeEmailRequest") - - -@_attrs_define -class ChangeEmailRequest: - """ - Attributes: - current_password (str): - email (str): - """ - - current_password: str - email: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - current_password = self.current_password - - email = self.email - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "currentPassword": current_password, - "email": email, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - current_password = d.pop("currentPassword") - - email = d.pop("email") - - change_email_request = cls( - current_password=current_password, - email=email, - ) - - change_email_request.additional_properties = d - return change_email_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/change_password_request.py b/openshock/rest/models/change_password_request.py deleted file mode 100644 index 6337c0e..0000000 --- a/openshock/rest/models/change_password_request.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="ChangePasswordRequest") - - -@_attrs_define -class ChangePasswordRequest: - """ - Attributes: - current_password (str): - new_password (str): - """ - - current_password: str - new_password: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - current_password = self.current_password - - new_password = self.new_password - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "currentPassword": current_password, - "newPassword": new_password, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - current_password = d.pop("currentPassword") - - new_password = d.pop("newPassword") - - change_password_request = cls( - current_password=current_password, - new_password=new_password, - ) - - change_password_request.additional_properties = d - return change_password_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/change_username_request.py b/openshock/rest/models/change_username_request.py deleted file mode 100644 index 348e9c1..0000000 --- a/openshock/rest/models/change_username_request.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="ChangeUsernameRequest") - - -@_attrs_define -class ChangeUsernameRequest: - """ - Attributes: - username (str): - """ - - username: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - username = self.username - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "username": username, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - username = d.pop("username") - - change_username_request = cls( - username=username, - ) - - change_username_request.additional_properties = d - return change_username_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_add_item_request.py b/openshock/rest/models/configuration_add_item_request.py deleted file mode 100644 index a2650e7..0000000 --- a/openshock/rest/models/configuration_add_item_request.py +++ /dev/null @@ -1,91 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.configuration_value_type import ConfigurationValueType - -T = TypeVar("T", bound="ConfigurationAddItemRequest") - - -@_attrs_define -class ConfigurationAddItemRequest: - """Request DTO for adding a new configuration item. - - Attributes: - name (str): The unique name of the configuration item. - Must consist of uppercase letters and underscores only. - description (str): A human-readable description of the configuration item’s purpose. - type_ (ConfigurationValueType): - value (str): The initial value for the configuration item, serialized as a string. - Must conform to the format required by ConfigurationValueType ConfigurationAddItemRequest.Type. - """ - - name: str - description: str - type_: ConfigurationValueType - value: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - description = self.description - - type_ = self.type_.value - - value = self.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "description": description, - "type": type_, - "value": value, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - description = d.pop("description") - - type_ = ConfigurationValueType(d.pop("type")) - - value = d.pop("value") - - configuration_add_item_request = cls( - name=name, - description=description, - type_=type_, - value=value, - ) - - configuration_add_item_request.additional_properties = d - return configuration_add_item_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_item_dto.py b/openshock/rest/models/configuration_item_dto.py deleted file mode 100644 index 428129b..0000000 --- a/openshock/rest/models/configuration_item_dto.py +++ /dev/null @@ -1,106 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.configuration_value_type import ConfigurationValueType - -T = TypeVar("T", bound="ConfigurationItemDto") - - -@_attrs_define -class ConfigurationItemDto: - """Data transfer object representing a configuration item. - - Attributes: - name (str): The unique name of the configuration item. - description (str): A human-readable description of what this configuration item controls. - type_ (ConfigurationValueType): - value (str): The current value of the configuration item, serialized as a string. - updated_at (datetime.datetime): The timestamp when the configuration was last updated. - created_at (datetime.datetime): The timestamp when the configuration was originally created. - """ - - name: str - description: str - type_: ConfigurationValueType - value: str - updated_at: datetime.datetime - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - description = self.description - - type_ = self.type_.value - - value = self.value - - updated_at = self.updated_at.isoformat() - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "description": description, - "type": type_, - "value": value, - "updatedAt": updated_at, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - description = d.pop("description") - - type_ = ConfigurationValueType(d.pop("type")) - - value = d.pop("value") - - updated_at = datetime.datetime.fromisoformat(d.pop("updatedAt")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - configuration_item_dto = cls( - name=name, - description=description, - type_=type_, - value=value, - updated_at=updated_at, - created_at=created_at, - ) - - configuration_item_dto.additional_properties = d - return configuration_item_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_update_item_request.py b/openshock/rest/models/configuration_update_item_request.py deleted file mode 100644 index a2bb38b..0000000 --- a/openshock/rest/models/configuration_update_item_request.py +++ /dev/null @@ -1,110 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -T = TypeVar("T", bound="ConfigurationUpdateItemRequest") - - -@_attrs_define -class ConfigurationUpdateItemRequest: - """Request DTO for updating a configuration item. - Either string? ConfigurationUpdateItemRequest.Description or string? ConfigurationUpdateItemRequest.Value (or both) - may be provided. - If both are null, no update action is performed. - - Attributes: - name (str): The name of the configuration item to update. - Must consist only of uppercase letters and underscores. - description (None | str | Unset): (Optional) New description for the configuration item. - value (None | str | Unset): (Optional) New value for the configuration item. - Must match the format expected by its existing ConfigurationValueType. - """ - - name: str - description: None | str | Unset = UNSET - value: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - description: None | str | Unset - if isinstance(self.description, Unset): - description = UNSET - else: - description = self.description - - value: None | str | Unset - if isinstance(self.value, Unset): - value = UNSET - else: - value = self.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - } - ) - if description is not UNSET: - field_dict["description"] = description - if value is not UNSET: - field_dict["value"] = value - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - def _parse_description(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - description = _parse_description(d.pop("description", UNSET)) - - def _parse_value(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - value = _parse_value(d.pop("value", UNSET)) - - configuration_update_item_request = cls( - name=name, - description=description, - value=value, - ) - - configuration_update_item_request.additional_properties = d - return configuration_update_item_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/configuration_value_type.py b/openshock/rest/models/configuration_value_type.py deleted file mode 100644 index b809802..0000000 --- a/openshock/rest/models/configuration_value_type.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class ConfigurationValueType(StrEnum): - BOOL = "Bool" - FLOAT = "Float" - INT = "Int" - JSON = "Json" - STRING = "String" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/create_automation_token_dto.py b/openshock/rest/models/create_automation_token_dto.py deleted file mode 100644 index 00e0bf8..0000000 --- a/openshock/rest/models/create_automation_token_dto.py +++ /dev/null @@ -1,112 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="CreateAutomationTokenDto") - - -@_attrs_define -class CreateAutomationTokenDto: - """ - Attributes: - name (str): - types (list[AutomationTokenType]): - auto_cleanup_users (bool | Unset): Whether the automated accounts this token creates are deleted once TimeSpan? - CreateAutomationTokenDto.AutoCleanupAfter has - passed since they were created. Off by default; accounts the token didn't create are never deleted. - auto_cleanup_after (None | str | Unset): - """ - - name: str - types: list[AutomationTokenType] - auto_cleanup_users: bool | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - types = [] - for types_item_data in self.types: - types_item = types_item_data.value - types.append(types_item) - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "types": types, - } - ) - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - types = [] - _types = d.pop("types") - for types_item_data in _types: - types_item = AutomationTokenType(types_item_data) - - types.append(types_item) - - auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - create_automation_token_dto = cls( - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - create_automation_token_dto.additional_properties = d - return create_automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/create_token_request_v2.py b/openshock/rest/models/create_token_request_v2.py deleted file mode 100644 index 7dfea1a..0000000 --- a/openshock/rest/models/create_token_request_v2.py +++ /dev/null @@ -1,127 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType -from ..types import UNSET, Unset - -if TYPE_CHECKING: - from ..models.shocker_control_settings import ShockerControlSettings - - -T = TypeVar("T", bound="CreateTokenRequestV2") - - -@_attrs_define -class CreateTokenRequestV2: - """ - Attributes: - name (str): - permissions (list[PermissionType]): - shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits - for intensity and duration. - valid_until (datetime.datetime | None | Unset): - """ - - name: str - permissions: list[PermissionType] - shocker_control: ShockerControlSettings - valid_until: datetime.datetime | None | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - shocker_control = self.shocker_control.to_dict() - - valid_until: None | str | Unset - if isinstance(self.valid_until, Unset): - valid_until = UNSET - elif isinstance(self.valid_until, datetime.datetime): - valid_until = self.valid_until.isoformat() - else: - valid_until = self.valid_until - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "permissions": permissions, - "shockerControl": shocker_control, - } - ) - if valid_until is not UNSET: - field_dict["validUntil"] = valid_until - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 - - d = dict(src_dict) - name = d.pop("name") - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) - - def _parse_valid_until(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - valid_until_type_1 = datetime.datetime.fromisoformat(data) - - return valid_until_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - valid_until = _parse_valid_until(d.pop("validUntil", UNSET)) - - create_token_request_v2 = cls( - name=name, - permissions=permissions, - shocker_control=shocker_control, - valid_until=valid_until, - ) - - create_token_request_v2.additional_properties = d - return create_token_request_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/created_automation_token_dto.py b/openshock/rest/models/created_automation_token_dto.py deleted file mode 100644 index 882a7e2..0000000 --- a/openshock/rest/models/created_automation_token_dto.py +++ /dev/null @@ -1,166 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="CreatedAutomationTokenDto") - - -@_attrs_define -class CreatedAutomationTokenDto: - """ - Attributes: - id (UUID): - name (str): - secret (str): - types (list[AutomationTokenType]): - created_at (datetime.datetime): - last_rotated_at (datetime.datetime | None | Unset): - auto_cleanup_users (bool | Unset): - auto_cleanup_after (None | str | Unset): - """ - - id: UUID - name: str - secret: str - types: list[AutomationTokenType] - created_at: datetime.datetime - last_rotated_at: datetime.datetime | None | Unset = UNSET - auto_cleanup_users: bool | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - secret = self.secret - - types = [] - for types_item_data in self.types: - types_item = types_item_data.value - types.append(types_item) - - created_at = self.created_at.isoformat() - - last_rotated_at: None | str | Unset - if isinstance(self.last_rotated_at, Unset): - last_rotated_at = UNSET - elif isinstance(self.last_rotated_at, datetime.datetime): - last_rotated_at = self.last_rotated_at.isoformat() - else: - last_rotated_at = self.last_rotated_at - - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "secret": secret, - "types": types, - "createdAt": created_at, - } - ) - if last_rotated_at is not UNSET: - field_dict["lastRotatedAt"] = last_rotated_at - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - secret = d.pop("secret") - - types = [] - _types = d.pop("types") - for types_item_data in _types: - types_item = AutomationTokenType(types_item_data) - - types.append(types_item) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_last_rotated_at(data: object) -> datetime.datetime | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, str): - raise TypeError() - last_rotated_at_type_1 = datetime.datetime.fromisoformat(data) - - return last_rotated_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None | Unset, data) - - last_rotated_at = _parse_last_rotated_at(d.pop("lastRotatedAt", UNSET)) - - auto_cleanup_users = d.pop("autoCleanupUsers", UNSET) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - created_automation_token_dto = cls( - id=id, - name=name, - secret=secret, - types=types, - created_at=created_at, - last_rotated_at=last_rotated_at, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - created_automation_token_dto.additional_properties = d - return created_automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/edit_token_request_v2.py b/openshock/rest/models/edit_token_request_v2.py deleted file mode 100644 index 3cd7cfa..0000000 --- a/openshock/rest/models/edit_token_request_v2.py +++ /dev/null @@ -1,95 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType - -if TYPE_CHECKING: - from ..models.shocker_control_settings import ShockerControlSettings - - -T = TypeVar("T", bound="EditTokenRequestV2") - - -@_attrs_define -class EditTokenRequestV2: - """ - Attributes: - name (str): - permissions (list[PermissionType]): - shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits - for intensity and duration. - """ - - name: str - permissions: list[PermissionType] - shocker_control: ShockerControlSettings - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - shocker_control = self.shocker_control.to_dict() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - "permissions": permissions, - "shockerControl": shocker_control, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 - - d = dict(src_dict) - name = d.pop("name") - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) - - edit_token_request_v2 = cls( - name=name, - permissions=permissions, - shocker_control=shocker_control, - ) - - edit_token_request_v2.additional_properties = d - return edit_token_request_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_request.py b/openshock/rest/models/email_outbox_bulk_request.py deleted file mode 100644 index fcf889f..0000000 --- a/openshock/rest/models/email_outbox_bulk_request.py +++ /dev/null @@ -1,72 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxBulkRequest") - - -@_attrs_define -class EmailOutboxBulkRequest: - """A set of email outbox message ids to apply a bulk requeue/cancel/delete to. - - Attributes: - ids (list[UUID]): - """ - - ids: list[UUID] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - ids = [] - for ids_item_data in self.ids: - ids_item = str(ids_item_data) - ids.append(ids_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "ids": ids, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - ids = [] - _ids = d.pop("ids") - for ids_item_data in _ids: - ids_item = UUID(ids_item_data) - - ids.append(ids_item) - - email_outbox_bulk_request = cls( - ids=ids, - ) - - email_outbox_bulk_request.additional_properties = d - return email_outbox_bulk_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_bulk_result_dto.py b/openshock/rest/models/email_outbox_bulk_result_dto.py deleted file mode 100644 index 2d7ad4f..0000000 --- a/openshock/rest/models/email_outbox_bulk_result_dto.py +++ /dev/null @@ -1,72 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxBulkResultDto") - - -@_attrs_define -class EmailOutboxBulkResultDto: - """Outcome of a bulk email outbox operation: how many ids were requested and how many rows were - actually affected (rows that were missing or in an ineligible state are silently not counted). - - Attributes: - requested (int): - affected (int): - """ - - requested: int - affected: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - requested = self.requested - - affected = self.affected - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "requested": requested, - "affected": affected, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - requested = d.pop("requested") - - affected = d.pop("affected") - - email_outbox_bulk_result_dto = cls( - requested=requested, - affected=affected, - ) - - email_outbox_bulk_result_dto.additional_properties = d - return email_outbox_bulk_result_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto.py b/openshock/rest/models/email_outbox_message_dto.py deleted file mode 100644 index 80d3e7c..0000000 --- a/openshock/rest/models/email_outbox_message_dto.py +++ /dev/null @@ -1,226 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.email_status import EmailStatus -from ..models.email_type import EmailType - -if TYPE_CHECKING: - from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload - - -T = TypeVar("T", bound="EmailOutboxMessageDto") - - -@_attrs_define -class EmailOutboxMessageDto: - """An EmailOutboxMessage as exposed to admins on the mail-queue page. Mirrors the row - verbatim - the outbox stores no rendered body and no usable secret, so every field is safe to show. - - Attributes: - id (UUID): - type_ (EmailType): The kind of email an outbox message represents. The outbox stores - only the intent to send one of these, never a rendered body or a usable secret, the - consumer maps the type to the matching template and (for token-bearing types) mints a fresh - secret at send time. - recipient (str): - recipient_name (None | str): - payload (EmailOutboxMessageDtoPayload): - coalesce_key (None | str): - status (EmailStatus): Delivery state of an email outbox message. - attempt_count (int): - next_attempt_at (datetime.datetime): - last_error (None | str): - created_at (datetime.datetime): - sent_at (datetime.datetime | None): - failed_at (datetime.datetime | None): - """ - - id: UUID - type_: EmailType - recipient: str - recipient_name: None | str - payload: EmailOutboxMessageDtoPayload - coalesce_key: None | str - status: EmailStatus - attempt_count: int - next_attempt_at: datetime.datetime - last_error: None | str - created_at: datetime.datetime - sent_at: datetime.datetime | None - failed_at: datetime.datetime | None - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - type_ = self.type_.value - - recipient = self.recipient - - recipient_name: None | str - recipient_name = self.recipient_name - - payload = self.payload.to_dict() - - coalesce_key: None | str - coalesce_key = self.coalesce_key - - status = self.status.value - - attempt_count = self.attempt_count - - next_attempt_at = self.next_attempt_at.isoformat() - - last_error: None | str - last_error = self.last_error - - created_at = self.created_at.isoformat() - - sent_at: None | str - if isinstance(self.sent_at, datetime.datetime): - sent_at = self.sent_at.isoformat() - else: - sent_at = self.sent_at - - failed_at: None | str - if isinstance(self.failed_at, datetime.datetime): - failed_at = self.failed_at.isoformat() - else: - failed_at = self.failed_at - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "type": type_, - "recipient": recipient, - "recipientName": recipient_name, - "payload": payload, - "coalesceKey": coalesce_key, - "status": status, - "attemptCount": attempt_count, - "nextAttemptAt": next_attempt_at, - "lastError": last_error, - "createdAt": created_at, - "sentAt": sent_at, - "failedAt": failed_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.email_outbox_message_dto_payload import EmailOutboxMessageDtoPayload # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - type_ = EmailType(d.pop("type")) - - recipient = d.pop("recipient") - - def _parse_recipient_name(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - recipient_name = _parse_recipient_name(d.pop("recipientName")) - - payload = EmailOutboxMessageDtoPayload.from_dict(d.pop("payload")) - - def _parse_coalesce_key(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - coalesce_key = _parse_coalesce_key(d.pop("coalesceKey")) - - status = EmailStatus(d.pop("status")) - - attempt_count = d.pop("attemptCount") - - next_attempt_at = datetime.datetime.fromisoformat(d.pop("nextAttemptAt")) - - def _parse_last_error(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - last_error = _parse_last_error(d.pop("lastError")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_sent_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - sent_at_type_1 = datetime.datetime.fromisoformat(data) - - return sent_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - sent_at = _parse_sent_at(d.pop("sentAt")) - - def _parse_failed_at(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - failed_at_type_1 = datetime.datetime.fromisoformat(data) - - return failed_at_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - failed_at = _parse_failed_at(d.pop("failedAt")) - - email_outbox_message_dto = cls( - id=id, - type_=type_, - recipient=recipient, - recipient_name=recipient_name, - payload=payload, - coalesce_key=coalesce_key, - status=status, - attempt_count=attempt_count, - next_attempt_at=next_attempt_at, - last_error=last_error, - created_at=created_at, - sent_at=sent_at, - failed_at=failed_at, - ) - - email_outbox_message_dto.additional_properties = d - return email_outbox_message_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_message_dto_payload.py b/openshock/rest/models/email_outbox_message_dto_payload.py deleted file mode 100644 index 2db2ad1..0000000 --- a/openshock/rest/models/email_outbox_message_dto_payload.py +++ /dev/null @@ -1,46 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxMessageDtoPayload") - - -@_attrs_define -class EmailOutboxMessageDtoPayload: - additional_properties: dict[str, str] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - email_outbox_message_dto_payload = cls() - - email_outbox_message_dto_payload.additional_properties = d - return email_outbox_message_dto_payload - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> str: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: str) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_outbox_stats_dto.py b/openshock/rest/models/email_outbox_stats_dto.py deleted file mode 100644 index 1cd818c..0000000 --- a/openshock/rest/models/email_outbox_stats_dto.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailOutboxStatsDto") - - -@_attrs_define -class EmailOutboxStatsDto: - """Count of email outbox rows in each delivery state, for the admin mail-queue overview tiles. - - Attributes: - pending (int): - sending (int): - sent (int): - failed (int): - skipped (int): - total (int): - """ - - pending: int - sending: int - sent: int - failed: int - skipped: int - total: int - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - pending = self.pending - - sending = self.sending - - sent = self.sent - - failed = self.failed - - skipped = self.skipped - - total = self.total - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "pending": pending, - "sending": sending, - "sent": sent, - "failed": failed, - "skipped": skipped, - "total": total, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - pending = d.pop("pending") - - sending = d.pop("sending") - - sent = d.pop("sent") - - failed = d.pop("failed") - - skipped = d.pop("skipped") - - total = d.pop("total") - - email_outbox_stats_dto = cls( - pending=pending, - sending=sending, - sent=sent, - failed=failed, - skipped=skipped, - total=total, - ) - - email_outbox_stats_dto.additional_properties = d - return email_outbox_stats_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_provider_blacklist_dto.py b/openshock/rest/models/email_provider_blacklist_dto.py deleted file mode 100644 index 53a85f4..0000000 --- a/openshock/rest/models/email_provider_blacklist_dto.py +++ /dev/null @@ -1,80 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="EmailProviderBlacklistDto") - - -@_attrs_define -class EmailProviderBlacklistDto: - """ - Attributes: - id (UUID): - domain (str): - created_at (datetime.datetime): - """ - - id: UUID - domain: str - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - domain = self.domain - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "domain": domain, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - domain = d.pop("domain") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - email_provider_blacklist_dto = cls( - id=id, - domain=domain, - created_at=created_at, - ) - - email_provider_blacklist_dto.additional_properties = d - return email_provider_blacklist_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/email_status.py b/openshock/rest/models/email_status.py deleted file mode 100644 index 12e74f7..0000000 --- a/openshock/rest/models/email_status.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class EmailStatus(StrEnum): - FAILED = "Failed" - PENDING = "Pending" - SENDING = "Sending" - SENT = "Sent" - SKIPPED = "Skipped" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/email_type.py b/openshock/rest/models/email_type.py deleted file mode 100644 index a778271..0000000 --- a/openshock/rest/models/email_type.py +++ /dev/null @@ -1,12 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class EmailType(StrEnum): - ACCOUNTACTIVATION = "AccountActivation" - EMAILCHANGENOTICE = "EmailChangeNotice" - EMAILVERIFICATION = "EmailVerification" - PASSWORDRESET = "PasswordReset" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py b/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py deleted file mode 100644 index 8aa0cb9..0000000 --- a/openshock/rest/models/legacy_data_response_of_array_of_admin_online_device_response.py +++ /dev/null @@ -1,84 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_online_device_response import AdminOnlineDeviceResponse - - -T = TypeVar("T", bound="LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse") - - -@_attrs_define -class LegacyDataResponseOfArrayOfAdminOnlineDeviceResponse: - """ - Attributes: - message (str): Default: ''. - data (list[AdminOnlineDeviceResponse]): - """ - - data: list[AdminOnlineDeviceResponse] - message: str = "" - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - message = self.message - - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "message": message, - "data": data, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_online_device_response import AdminOnlineDeviceResponse # noqa: PLC0415 - - d = dict(src_dict) - message = d.pop("message") - - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = AdminOnlineDeviceResponse.from_dict(data_item_data) - - data.append(data_item) - - legacy_data_response_of_array_of_admin_online_device_response = cls( - message=message, - data=data, - ) - - legacy_data_response_of_array_of_admin_online_device_response.additional_properties = d - return legacy_data_response_of_array_of_admin_online_device_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py b/openshock/rest/models/legacy_data_response_of_shocker_perm_limit_pair.py similarity index 64% rename from openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py rename to openshock/rest/models/legacy_data_response_of_shocker_perm_limit_pair.py index 757a667..73ccf45 100644 --- a/openshock/rest/models/legacy_data_response_of_i_read_only_collection_of_ota_item.py +++ b/openshock/rest/models/legacy_data_response_of_shocker_perm_limit_pair.py @@ -8,31 +8,28 @@ from attrs import field as _attrs_field if TYPE_CHECKING: - from ..models.ota_item import OtaItem + from ..models.shocker_perm_limit_pair import ShockerPermLimitPair -T = TypeVar("T", bound="LegacyDataResponseOfIReadOnlyCollectionOfOtaItem") +T = TypeVar("T", bound="LegacyDataResponseOfShockerPermLimitPair") @_attrs_define -class LegacyDataResponseOfIReadOnlyCollectionOfOtaItem: +class LegacyDataResponseOfShockerPermLimitPair: """ Attributes: message (str): Default: ''. - data (list[OtaItem]): + data (ShockerPermLimitPair): """ - data: list[OtaItem] + data: ShockerPermLimitPair message: str = "" additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: message = self.message - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) + data = self.data.to_dict() field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) @@ -47,25 +44,20 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.ota_item import OtaItem # noqa: PLC0415 + from ..models.shocker_perm_limit_pair import ShockerPermLimitPair # noqa: PLC0415 d = dict(src_dict) message = d.pop("message") - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = OtaItem.from_dict(data_item_data) + data = ShockerPermLimitPair.from_dict(d.pop("data")) - data.append(data_item) - - legacy_data_response_of_i_read_only_collection_of_ota_item = cls( + legacy_data_response_of_shocker_perm_limit_pair = cls( message=message, data=data, ) - legacy_data_response_of_i_read_only_collection_of_ota_item.additional_properties = d - return legacy_data_response_of_i_read_only_collection_of_ota_item + legacy_data_response_of_shocker_perm_limit_pair.additional_properties = d + return legacy_data_response_of_shocker_perm_limit_pair @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/login_session_response.py b/openshock/rest/models/login_session_response.py deleted file mode 100644 index 47328f3..0000000 --- a/openshock/rest/models/login_session_response.py +++ /dev/null @@ -1,203 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -T = TypeVar("T", bound="LoginSessionResponse") - - -@_attrs_define -class LoginSessionResponse: - """ - Attributes: - id (UUID): - ip (str): An IPv4 or IPv6 address in its textual form. - user_agent (str): - created (datetime.datetime): - expires (datetime.datetime): - last_used (datetime.datetime | None): - asn_org (None | str | Unset): - is_vpn (bool | None | Unset): - country_code (None | str | Unset): - city (None | str | Unset): - """ - - id: UUID - ip: str - user_agent: str - created: datetime.datetime - expires: datetime.datetime - last_used: datetime.datetime | None - asn_org: None | str | Unset = UNSET - is_vpn: bool | None | Unset = UNSET - country_code: None | str | Unset = UNSET - city: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - ip = self.ip - - user_agent = self.user_agent - - created = self.created.isoformat() - - expires = self.expires.isoformat() - - last_used: None | str - if isinstance(self.last_used, datetime.datetime): - last_used = self.last_used.isoformat() - else: - last_used = self.last_used - - asn_org: None | str | Unset - if isinstance(self.asn_org, Unset): - asn_org = UNSET - else: - asn_org = self.asn_org - - is_vpn: bool | None | Unset - if isinstance(self.is_vpn, Unset): - is_vpn = UNSET - else: - is_vpn = self.is_vpn - - country_code: None | str | Unset - if isinstance(self.country_code, Unset): - country_code = UNSET - else: - country_code = self.country_code - - city: None | str | Unset - if isinstance(self.city, Unset): - city = UNSET - else: - city = self.city - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "ip": ip, - "userAgent": user_agent, - "created": created, - "expires": expires, - "lastUsed": last_used, - } - ) - if asn_org is not UNSET: - field_dict["asnOrg"] = asn_org - if is_vpn is not UNSET: - field_dict["isVpn"] = is_vpn - if country_code is not UNSET: - field_dict["countryCode"] = country_code - if city is not UNSET: - field_dict["city"] = city - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - ip = d.pop("ip") - - user_agent = d.pop("userAgent") - - created = datetime.datetime.fromisoformat(d.pop("created")) - - expires = datetime.datetime.fromisoformat(d.pop("expires")) - - def _parse_last_used(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - last_used = _parse_last_used(d.pop("lastUsed")) - - def _parse_asn_org(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - asn_org = _parse_asn_org(d.pop("asnOrg", UNSET)) - - def _parse_is_vpn(data: object) -> bool | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(bool | None | Unset, data) - - is_vpn = _parse_is_vpn(d.pop("isVpn", UNSET)) - - def _parse_country_code(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - country_code = _parse_country_code(d.pop("countryCode", UNSET)) - - def _parse_city(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - city = _parse_city(d.pop("city", UNSET)) - - login_session_response = cls( - id=id, - ip=ip, - user_agent=user_agent, - created=created, - expires=expires, - last_used=last_used, - asn_org=asn_org, - is_vpn=is_vpn, - country_code=country_code, - city=city, - ) - - login_session_response.additional_properties = d - return login_session_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/login_v2.py b/openshock/rest/models/login_v2.py deleted file mode 100644 index 2111d42..0000000 --- a/openshock/rest/models/login_v2.py +++ /dev/null @@ -1,78 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="LoginV2") - - -@_attrs_define -class LoginV2: - """ - Attributes: - password (str): - username_or_email (str): - turnstile_response (str): - """ - - password: str - username_or_email: str - turnstile_response: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - password = self.password - - username_or_email = self.username_or_email - - turnstile_response = self.turnstile_response - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "password": password, - "usernameOrEmail": username_or_email, - "turnstileResponse": turnstile_response, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - password = d.pop("password") - - username_or_email = d.pop("usernameOrEmail") - - turnstile_response = d.pop("turnstileResponse") - - login_v2 = cls( - password=password, - username_or_email=username_or_email, - turnstile_response=turnstile_response, - ) - - login_v2.additional_properties = d - return login_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/login_v2_ok_response.py b/openshock/rest/models/login_v2_ok_response.py deleted file mode 100644 index 27df451..0000000 --- a/openshock/rest/models/login_v2_ok_response.py +++ /dev/null @@ -1,113 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.role_type import RoleType - -T = TypeVar("T", bound="LoginV2OkResponse") - - -@_attrs_define -class LoginV2OkResponse: - """ - Attributes: - account_id (UUID): - account_name (str): - account_email (str): - is_verified (bool): - profile_image (str): - account_roles (list[RoleType]): - """ - - account_id: UUID - account_name: str - account_email: str - is_verified: bool - profile_image: str - account_roles: list[RoleType] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - account_id = str(self.account_id) - - account_name = self.account_name - - account_email = self.account_email - - is_verified = self.is_verified - - profile_image = self.profile_image - - account_roles = [] - for account_roles_item_data in self.account_roles: - account_roles_item = account_roles_item_data.value - account_roles.append(account_roles_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "accountId": account_id, - "accountName": account_name, - "accountEmail": account_email, - "isVerified": is_verified, - "profileImage": profile_image, - "accountRoles": account_roles, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - account_id = UUID(d.pop("accountId")) - - account_name = d.pop("accountName") - - account_email = d.pop("accountEmail") - - is_verified = d.pop("isVerified") - - profile_image = d.pop("profileImage") - - account_roles = [] - _account_roles = d.pop("accountRoles") - for account_roles_item_data in _account_roles: - account_roles_item = RoleType(account_roles_item_data) - - account_roles.append(account_roles_item) - - login_v2_ok_response = cls( - account_id=account_id, - account_name=account_name, - account_email=account_email, - is_verified=is_verified, - profile_image=profile_image, - account_roles=account_roles, - ) - - login_v2_ok_response.additional_properties = d - return login_v2_ok_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/match_type_enum.py b/openshock/rest/models/match_type_enum.py deleted file mode 100644 index f734f77..0000000 --- a/openshock/rest/models/match_type_enum.py +++ /dev/null @@ -1,10 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class MatchTypeEnum(StrEnum): - CONTAINS = "Contains" - EXACT = "Exact" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/o_auth_connection_response.py b/openshock/rest/models/o_auth_connection_response.py deleted file mode 100644 index ce6a08a..0000000 --- a/openshock/rest/models/o_auth_connection_response.py +++ /dev/null @@ -1,93 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="OAuthConnectionResponse") - - -@_attrs_define -class OAuthConnectionResponse: - """ - Attributes: - provider_key (str): - external_id (str): - display_name (None | str): - linked_at (datetime.datetime): - """ - - provider_key: str - external_id: str - display_name: None | str - linked_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - provider_key = self.provider_key - - external_id = self.external_id - - display_name: None | str - display_name = self.display_name - - linked_at = self.linked_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "providerKey": provider_key, - "externalId": external_id, - "displayName": display_name, - "linkedAt": linked_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - provider_key = d.pop("providerKey") - - external_id = d.pop("externalId") - - def _parse_display_name(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - display_name = _parse_display_name(d.pop("displayName")) - - linked_at = datetime.datetime.fromisoformat(d.pop("linkedAt")) - - o_auth_connection_response = cls( - provider_key=provider_key, - external_id=external_id, - display_name=display_name, - linked_at=linked_at, - ) - - o_auth_connection_response.additional_properties = d - return o_auth_connection_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/ota_item.py b/openshock/rest/models/ota_item.py deleted file mode 100644 index 7c9e8fd..0000000 --- a/openshock/rest/models/ota_item.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.ota_update_status import OtaUpdateStatus - -T = TypeVar("T", bound="OtaItem") - - -@_attrs_define -class OtaItem: - """ - Attributes: - id (int): - started_at (datetime.datetime): - status (OtaUpdateStatus): - version (str): - message (None | str): - """ - - id: int - started_at: datetime.datetime - status: OtaUpdateStatus - version: str - message: None | str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = self.id - - started_at = self.started_at.isoformat() - - status = self.status.value - - version = self.version - - message: None | str - message = self.message - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "startedAt": started_at, - "status": status, - "version": version, - "message": message, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = d.pop("id") - - started_at = datetime.datetime.fromisoformat(d.pop("startedAt")) - - status = OtaUpdateStatus(d.pop("status")) - - version = d.pop("version") - - def _parse_message(data: object) -> None | str: - if data is None: - return data - return cast(None | str, data) - - message = _parse_message(d.pop("message")) - - ota_item = cls( - id=id, - started_at=started_at, - status=status, - version=version, - message=message, - ) - - ota_item.additional_properties = d - return ota_item - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/ota_update_status.py b/openshock/rest/models/ota_update_status.py deleted file mode 100644 index 6f8243f..0000000 --- a/openshock/rest/models/ota_update_status.py +++ /dev/null @@ -1,13 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class OtaUpdateStatus(StrEnum): - ERROR = "Error" - FINISHED = "Finished" - RUNNING = "Running" - STARTED = "Started" - TIMEOUT = "Timeout" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/own_public_share_response.py b/openshock/rest/models/own_public_share_response.py index 204e679..106e2df 100644 --- a/openshock/rest/models/own_public_share_response.py +++ b/openshock/rest/models/own_public_share_response.py @@ -20,13 +20,17 @@ class OwnPublicShareResponse: Attributes: id (UUID): name (str): + slug (None | str): created_on (datetime.datetime): + has_password (bool): expires_on (datetime.datetime | None | Unset): """ id: UUID name: str + slug: None | str created_on: datetime.datetime + has_password: bool expires_on: datetime.datetime | None | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) @@ -35,8 +39,13 @@ def to_dict(self) -> dict[str, Any]: name = self.name + slug: None | str + slug = self.slug + created_on = self.created_on.isoformat() + has_password = self.has_password + expires_on: None | str | Unset if isinstance(self.expires_on, Unset): expires_on = UNSET @@ -51,7 +60,9 @@ def to_dict(self) -> dict[str, Any]: { "id": id, "name": name, + "slug": slug, "createdOn": created_on, + "hasPassword": has_password, } ) if expires_on is not UNSET: @@ -66,8 +77,17 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: name = d.pop("name") + def _parse_slug(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + slug = _parse_slug(d.pop("slug")) + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) + has_password = d.pop("hasPassword") + def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: if data is None: return data @@ -88,7 +108,9 @@ def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: own_public_share_response = cls( id=id, name=name, + slug=slug, created_on=created_on, + has_password=has_password, expires_on=expires_on, ) diff --git a/openshock/rest/models/paged_result_of_audit_log_entry_response.py b/openshock/rest/models/paged_result_of_audit_log_entry_response.py deleted file mode 100644 index afb380c..0000000 --- a/openshock/rest/models/paged_result_of_audit_log_entry_response.py +++ /dev/null @@ -1,112 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -if TYPE_CHECKING: - from ..models.audit_log_entry_response import AuditLogEntryResponse - - -T = TypeVar("T", bound="PagedResultOfAuditLogEntryResponse") - - -@_attrs_define -class PagedResultOfAuditLogEntryResponse: - """Page of results for a paginated list endpoint. - - Attributes: - items (list[AuditLogEntryResponse]): Items on the current page. - page (int): 1-based current page index. - page_size (int): Page size used to produce this result. - total_count (int): Total number of items across all pages matching the query. - total_pages (int | Unset): Total number of pages. Always at least 1, even when `TotalCount` is zero. - """ - - items: list[AuditLogEntryResponse] - page: int - page_size: int - total_count: int - total_pages: int | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - items = [] - for items_item_data in self.items: - items_item = items_item_data.to_dict() - items.append(items_item) - - page = self.page - - page_size = self.page_size - - total_count = self.total_count - - total_pages = self.total_pages - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "items": items, - "page": page, - "pageSize": page_size, - "totalCount": total_count, - } - ) - if total_pages is not UNSET: - field_dict["totalPages"] = total_pages - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.audit_log_entry_response import AuditLogEntryResponse # noqa: PLC0415 - - d = dict(src_dict) - items = [] - _items = d.pop("items") - for items_item_data in _items: - items_item = AuditLogEntryResponse.from_dict(items_item_data) - - items.append(items_item) - - page = d.pop("page") - - page_size = d.pop("pageSize") - - total_count = d.pop("totalCount") - - total_pages = d.pop("totalPages", UNSET) - - paged_result_of_audit_log_entry_response = cls( - items=items, - page=page, - page_size=page_size, - total_count=total_count, - total_pages=total_pages, - ) - - paged_result_of_audit_log_entry_response.additional_properties = d - return paged_result_of_audit_log_entry_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_admin_users_view.py b/openshock/rest/models/paginated_of_admin_users_view.py deleted file mode 100644 index fa4499d..0000000 --- a/openshock/rest/models/paginated_of_admin_users_view.py +++ /dev/null @@ -1,100 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.admin_users_view import AdminUsersView - - -T = TypeVar("T", bound="PaginatedOfAdminUsersView") - - -@_attrs_define -class PaginatedOfAdminUsersView: - """ - Attributes: - offset (int): - limit (int): - total (int): - data (list[AdminUsersView]): - """ - - offset: int - limit: int - total: int - data: list[AdminUsersView] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - offset = self.offset - - limit = self.limit - - total = self.total - - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "offset": offset, - "limit": limit, - "total": total, - "data": data, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.admin_users_view import AdminUsersView # noqa: PLC0415 - - d = dict(src_dict) - offset = d.pop("offset") - - limit = d.pop("limit") - - total = d.pop("total") - - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = AdminUsersView.from_dict(data_item_data) - - data.append(data_item) - - paginated_of_admin_users_view = cls( - offset=offset, - limit=limit, - total=total, - data=data, - ) - - paginated_of_admin_users_view.additional_properties = d - return paginated_of_admin_users_view - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/paginated_of_email_outbox_message_dto.py b/openshock/rest/models/paginated_of_email_outbox_message_dto.py deleted file mode 100644 index dffe554..0000000 --- a/openshock/rest/models/paginated_of_email_outbox_message_dto.py +++ /dev/null @@ -1,100 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -if TYPE_CHECKING: - from ..models.email_outbox_message_dto import EmailOutboxMessageDto - - -T = TypeVar("T", bound="PaginatedOfEmailOutboxMessageDto") - - -@_attrs_define -class PaginatedOfEmailOutboxMessageDto: - """ - Attributes: - offset (int): - limit (int): - total (int): - data (list[EmailOutboxMessageDto]): - """ - - offset: int - limit: int - total: int - data: list[EmailOutboxMessageDto] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - offset = self.offset - - limit = self.limit - - total = self.total - - data = [] - for data_item_data in self.data: - data_item = data_item_data.to_dict() - data.append(data_item) - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "offset": offset, - "limit": limit, - "total": total, - "data": data, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.email_outbox_message_dto import EmailOutboxMessageDto # noqa: PLC0415 - - d = dict(src_dict) - offset = d.pop("offset") - - limit = d.pop("limit") - - total = d.pop("total") - - data = [] - _data = d.pop("data") - for data_item_data in _data: - data_item = EmailOutboxMessageDto.from_dict(data_item_data) - - data.append(data_item) - - paginated_of_email_outbox_message_dto = cls( - offset=offset, - limit=limit, - total=total, - data=data, - ) - - paginated_of_email_outbox_message_dto.additional_properties = d - return paginated_of_email_outbox_message_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/password_hashing_algorithm.py b/openshock/rest/models/password_hashing_algorithm.py deleted file mode 100644 index 13a3409..0000000 --- a/openshock/rest/models/password_hashing_algorithm.py +++ /dev/null @@ -1,11 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class PasswordHashingAlgorithm(StrEnum): - BCRYPT = "BCrypt" - PBKDF2 = "PBKDF2" - UNKNOWN = "Unknown" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/password_reset_request_v2.py b/openshock/rest/models/password_reset_request_v2.py deleted file mode 100644 index b108dbe..0000000 --- a/openshock/rest/models/password_reset_request_v2.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="PasswordResetRequestV2") - - -@_attrs_define -class PasswordResetRequestV2: - """ - Attributes: - email (str): - turnstile_response (str): - """ - - email: str - turnstile_response: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - email = self.email - - turnstile_response = self.turnstile_response - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "email": email, - "turnstileResponse": turnstile_response, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - email = d.pop("email") - - turnstile_response = d.pop("turnstileResponse") - - password_reset_request_v2 = cls( - email=email, - turnstile_response=turnstile_response, - ) - - password_reset_request_v2.additional_properties = d - return password_reset_request_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/patch_automation_token_dto.py b/openshock/rest/models/patch_automation_token_dto.py deleted file mode 100644 index ac287bc..0000000 --- a/openshock/rest/models/patch_automation_token_dto.py +++ /dev/null @@ -1,154 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.automation_token_type import AutomationTokenType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="PatchAutomationTokenDto") - - -@_attrs_define -class PatchAutomationTokenDto: - """ - Attributes: - name (None | str | Unset): - types (list[AutomationTokenType] | None | Unset): - auto_cleanup_users (bool | None | Unset): - auto_cleanup_after (None | str | Unset): - """ - - name: None | str | Unset = UNSET - types: list[AutomationTokenType] | None | Unset = UNSET - auto_cleanup_users: bool | None | Unset = UNSET - auto_cleanup_after: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name: None | str | Unset - if isinstance(self.name, Unset): - name = UNSET - else: - name = self.name - - types: list[str] | None | Unset - if isinstance(self.types, Unset): - types = UNSET - elif isinstance(self.types, list): - types = [] - for types_type_1_item_data in self.types: - types_type_1_item = types_type_1_item_data.value - types.append(types_type_1_item) - - else: - types = self.types - - auto_cleanup_users: bool | None | Unset - if isinstance(self.auto_cleanup_users, Unset): - auto_cleanup_users = UNSET - else: - auto_cleanup_users = self.auto_cleanup_users - - auto_cleanup_after: None | str | Unset - if isinstance(self.auto_cleanup_after, Unset): - auto_cleanup_after = UNSET - else: - auto_cleanup_after = self.auto_cleanup_after - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update({}) - if name is not UNSET: - field_dict["name"] = name - if types is not UNSET: - field_dict["types"] = types - if auto_cleanup_users is not UNSET: - field_dict["autoCleanupUsers"] = auto_cleanup_users - if auto_cleanup_after is not UNSET: - field_dict["autoCleanupAfter"] = auto_cleanup_after - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - - def _parse_name(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - name = _parse_name(d.pop("name", UNSET)) - - def _parse_types(data: object) -> list[AutomationTokenType] | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, list): - raise TypeError() - types_type_1 = [] - _types_type_1 = data - for types_type_1_item_data in _types_type_1: - types_type_1_item = AutomationTokenType(types_type_1_item_data) - - types_type_1.append(types_type_1_item) - - return types_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(list[AutomationTokenType] | None | Unset, data) - - types = _parse_types(d.pop("types", UNSET)) - - def _parse_auto_cleanup_users(data: object) -> bool | None | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(bool | None | Unset, data) - - auto_cleanup_users = _parse_auto_cleanup_users(d.pop("autoCleanupUsers", UNSET)) - - def _parse_auto_cleanup_after(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - auto_cleanup_after = _parse_auto_cleanup_after(d.pop("autoCleanupAfter", UNSET)) - - patch_automation_token_dto = cls( - name=name, - types=types, - auto_cleanup_users=auto_cleanup_users, - auto_cleanup_after=auto_cleanup_after, - ) - - patch_automation_token_dto.additional_properties = d - return patch_automation_token_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/admin_user_view_email_change.py b/openshock/rest/models/public_share_author.py similarity index 51% rename from openshock/rest/models/admin_user_view_email_change.py rename to openshock/rest/models/public_share_author.py index a43a754..c3310a3 100644 --- a/openshock/rest/models/admin_user_view_email_change.py +++ b/openshock/rest/models/public_share_author.py @@ -1,54 +1,59 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. from __future__ import annotations -import datetime from collections.abc import Mapping -from typing import Any, TypeVar, cast +from typing import TYPE_CHECKING, Any, TypeVar, cast from uuid import UUID from attrs import define as _attrs_define from attrs import field as _attrs_field -T = TypeVar("T", bound="AdminUserViewEmailChange") +if TYPE_CHECKING: + from ..models.public_user_profile_details import PublicUserProfileDetails + + +T = TypeVar("T", bound="PublicShareAuthor") @_attrs_define -class AdminUserViewEmailChange: +class PublicShareAuthor: """ Attributes: id (UUID): - email (str): - created_at (datetime.datetime): - used_at (datetime.datetime | None): + name (str): + image (str): + profile (None | PublicUserProfileDetails): """ id: UUID - email: str - created_at: datetime.datetime - used_at: datetime.datetime | None + name: str + image: str + profile: None | PublicUserProfileDetails additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: + from ..models.public_user_profile_details import PublicUserProfileDetails # noqa: PLC0415 + id = str(self.id) - email = self.email + name = self.name - created_at = self.created_at.isoformat() + image = self.image - used_at: None | str - if isinstance(self.used_at, datetime.datetime): - used_at = self.used_at.isoformat() + profile: dict[str, Any] | None + if isinstance(self.profile, PublicUserProfileDetails): + profile = self.profile.to_dict() else: - used_at = self.used_at + profile = self.profile field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( { "id": id, - "email": email, - "createdAt": created_at, - "usedAt": used_at, + "name": name, + "image": image, + "profile": profile, } ) @@ -56,37 +61,39 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.public_user_profile_details import PublicUserProfileDetails # noqa: PLC0415 + d = dict(src_dict) id = UUID(d.pop("id")) - email = d.pop("email") + name = d.pop("name") - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + image = d.pop("image") - def _parse_used_at(data: object) -> datetime.datetime | None: + def _parse_profile(data: object) -> None | PublicUserProfileDetails: if data is None: return data try: - if not isinstance(data, str): + if not isinstance(data, dict): raise TypeError() - used_at_type_1 = datetime.datetime.fromisoformat(data) + profile_type_1 = PublicUserProfileDetails.from_dict(data) - return used_at_type_1 + return profile_type_1 except (TypeError, ValueError, AttributeError, KeyError): pass - return cast(datetime.datetime | None, data) + return cast(None | PublicUserProfileDetails, data) - used_at = _parse_used_at(d.pop("usedAt")) + profile = _parse_profile(d.pop("profile")) - admin_user_view_email_change = cls( + public_share_author = cls( id=id, - email=email, - created_at=created_at, - used_at=used_at, + name=name, + image=image, + profile=profile, ) - admin_user_view_email_change.additional_properties = d - return admin_user_view_email_change + public_share_author.additional_properties = d + return public_share_author @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/public_share_create.py b/openshock/rest/models/public_share_create.py index f8de2a1..ca43de8 100644 --- a/openshock/rest/models/public_share_create.py +++ b/openshock/rest/models/public_share_create.py @@ -19,10 +19,15 @@ class PublicShareCreate: Attributes: name (str): expires_on (datetime.datetime | None | Unset): + slug (None | str | Unset): Custom URL segment, reachable at /u/{username}/{slug}. Unique per owner. + password (None | str | Unset): Optional password visitors must enter before they can see or control the + shockers. """ name: str expires_on: datetime.datetime | None | Unset = UNSET + slug: None | str | Unset = UNSET + password: None | str | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -36,6 +41,18 @@ def to_dict(self) -> dict[str, Any]: else: expires_on = self.expires_on + slug: None | str | Unset + if isinstance(self.slug, Unset): + slug = UNSET + else: + slug = self.slug + + password: None | str | Unset + if isinstance(self.password, Unset): + password = UNSET + else: + password = self.password + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -45,6 +62,10 @@ def to_dict(self) -> dict[str, Any]: ) if expires_on is not UNSET: field_dict["expiresOn"] = expires_on + if slug is not UNSET: + field_dict["slug"] = slug + if password is not UNSET: + field_dict["password"] = password return field_dict @@ -70,9 +91,29 @@ def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: expires_on = _parse_expires_on(d.pop("expiresOn", UNSET)) + def _parse_slug(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + slug = _parse_slug(d.pop("slug", UNSET)) + + def _parse_password(data: object) -> None | str | Unset: + if data is None: + return data + if isinstance(data, Unset): + return data + return cast(None | str | Unset, data) + + password = _parse_password(d.pop("password", UNSET)) + public_share_create = cls( name=name, expires_on=expires_on, + slug=slug, + password=password, ) public_share_create.additional_properties = d diff --git a/openshock/rest/models/admin_user_view_password_reset.py b/openshock/rest/models/public_share_edit.py similarity index 54% rename from openshock/rest/models/admin_user_view_password_reset.py rename to openshock/rest/models/public_share_edit.py index 4f0cc60..9a45896 100644 --- a/openshock/rest/models/admin_user_view_password_reset.py +++ b/openshock/rest/models/public_share_edit.py @@ -4,46 +4,47 @@ import datetime from collections.abc import Mapping from typing import Any, TypeVar, cast -from uuid import UUID from attrs import define as _attrs_define from attrs import field as _attrs_field -T = TypeVar("T", bound="AdminUserViewPasswordReset") +T = TypeVar("T", bound="PublicShareEdit") @_attrs_define -class AdminUserViewPasswordReset: - """ +class PublicShareEdit: + """Replaces all editable fields of a public share, null clears the expiry or slug. + Attributes: - id (UUID): - created_at (datetime.datetime): - used_at (datetime.datetime | None): + name (str): + expires_on (datetime.datetime | None): + slug (None | str): """ - id: UUID - created_at: datetime.datetime - used_at: datetime.datetime | None + name: str + expires_on: datetime.datetime | None + slug: None | str additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - created_at = self.created_at.isoformat() + name = self.name - used_at: None | str - if isinstance(self.used_at, datetime.datetime): - used_at = self.used_at.isoformat() + expires_on: None | str + if isinstance(self.expires_on, datetime.datetime): + expires_on = self.expires_on.isoformat() else: - used_at = self.used_at + expires_on = self.expires_on + + slug: None | str + slug = self.slug field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( { - "id": id, - "createdAt": created_at, - "usedAt": used_at, + "name": name, + "expiresOn": expires_on, + "slug": slug, } ) @@ -52,33 +53,38 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: d = dict(src_dict) - id = UUID(d.pop("id")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + name = d.pop("name") - def _parse_used_at(data: object) -> datetime.datetime | None: + def _parse_expires_on(data: object) -> datetime.datetime | None: if data is None: return data try: if not isinstance(data, str): raise TypeError() - used_at_type_1 = datetime.datetime.fromisoformat(data) + expires_on_type_1 = datetime.datetime.fromisoformat(data) - return used_at_type_1 + return expires_on_type_1 except (TypeError, ValueError, AttributeError, KeyError): pass return cast(datetime.datetime | None, data) - used_at = _parse_used_at(d.pop("usedAt")) + expires_on = _parse_expires_on(d.pop("expiresOn")) + + def _parse_slug(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + slug = _parse_slug(d.pop("slug")) - admin_user_view_password_reset = cls( - id=id, - created_at=created_at, - used_at=used_at, + public_share_edit = cls( + name=name, + expires_on=expires_on, + slug=slug, ) - admin_user_view_password_reset.additional_properties = d - return admin_user_view_password_reset + public_share_edit.additional_properties = d + return public_share_edit @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/set_user_password_request_body.py b/openshock/rest/models/public_share_password_set.py similarity index 66% rename from openshock/rest/models/set_user_password_request_body.py rename to openshock/rest/models/public_share_password_set.py index 2eba296..ffa20fe 100644 --- a/openshock/rest/models/set_user_password_request_body.py +++ b/openshock/rest/models/public_share_password_set.py @@ -2,25 +2,27 @@ from __future__ import annotations from collections.abc import Mapping -from typing import Any, TypeVar +from typing import Any, TypeVar, cast from attrs import define as _attrs_define from attrs import field as _attrs_field -T = TypeVar("T", bound="SetUserPasswordRequestBody") +T = TypeVar("T", bound="PublicSharePasswordSet") @_attrs_define -class SetUserPasswordRequestBody: +class PublicSharePasswordSet: """ Attributes: - password (str): + password (None | str): The new password, or null to remove it. Setting or changing it disconnects everyone + currently using the share. """ - password: str + password: None | str additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: + password: None | str password = self.password field_dict: dict[str, Any] = {} @@ -36,14 +38,20 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: d = dict(src_dict) - password = d.pop("password") - set_user_password_request_body = cls( + def _parse_password(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + password = _parse_password(d.pop("password")) + + public_share_password_set = cls( password=password, ) - set_user_password_request_body.additional_properties = d - return set_user_password_request_body + public_share_password_set.additional_properties = d + return public_share_password_set @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/public_share_response.py b/openshock/rest/models/public_share_response.py index 5b121db..fa4dc77 100644 --- a/openshock/rest/models/public_share_response.py +++ b/openshock/rest/models/public_share_response.py @@ -12,7 +12,7 @@ from ..types import UNSET, Unset if TYPE_CHECKING: - from ..models.basic_user_info import BasicUserInfo + from ..models.public_share_author import PublicShareAuthor from ..models.public_share_device import PublicShareDevice @@ -25,16 +25,23 @@ class PublicShareResponse: Attributes: id (UUID): name (str): + slug (None | str): created_on (datetime.datetime): - author (BasicUserInfo): + author (PublicShareAuthor): + password_protected (bool): Visitors have to enter a password before they can see or control the shockers. + password_required (bool): The share is password protected and this request did not unlock it: + IList<PublicShareDevice> PublicShareResponse.Devices is empty. expires_on (datetime.datetime | None | Unset): devices (list[PublicShareDevice] | Unset): """ id: UUID name: str + slug: None | str created_on: datetime.datetime - author: BasicUserInfo + author: PublicShareAuthor + password_protected: bool + password_required: bool expires_on: datetime.datetime | None | Unset = UNSET devices: list[PublicShareDevice] | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) @@ -44,10 +51,17 @@ def to_dict(self) -> dict[str, Any]: name = self.name + slug: None | str + slug = self.slug + created_on = self.created_on.isoformat() author = self.author.to_dict() + password_protected = self.password_protected + + password_required = self.password_required + expires_on: None | str | Unset if isinstance(self.expires_on, Unset): expires_on = UNSET @@ -69,8 +83,11 @@ def to_dict(self) -> dict[str, Any]: { "id": id, "name": name, + "slug": slug, "createdOn": created_on, "author": author, + "passwordProtected": password_protected, + "passwordRequired": password_required, } ) if expires_on is not UNSET: @@ -82,7 +99,7 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + from ..models.public_share_author import PublicShareAuthor # noqa: PLC0415 from ..models.public_share_device import PublicShareDevice # noqa: PLC0415 d = dict(src_dict) @@ -90,9 +107,20 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: name = d.pop("name") + def _parse_slug(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + slug = _parse_slug(d.pop("slug")) + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) - author = BasicUserInfo.from_dict(d.pop("author")) + author = PublicShareAuthor.from_dict(d.pop("author")) + + password_protected = d.pop("passwordProtected") + + password_required = d.pop("passwordRequired") def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: if data is None: @@ -123,8 +151,11 @@ def _parse_expires_on(data: object) -> datetime.datetime | None | Unset: public_share_response = cls( id=id, name=name, + slug=slug, created_on=created_on, author=author, + password_protected=password_protected, + password_required=password_required, expires_on=expires_on, devices=devices, ) diff --git a/openshock/rest/models/password_reset_process_data.py b/openshock/rest/models/public_share_unlock.py similarity index 86% rename from openshock/rest/models/password_reset_process_data.py rename to openshock/rest/models/public_share_unlock.py index 4595ac2..ee1f37f 100644 --- a/openshock/rest/models/password_reset_process_data.py +++ b/openshock/rest/models/public_share_unlock.py @@ -7,11 +7,11 @@ from attrs import define as _attrs_define from attrs import field as _attrs_field -T = TypeVar("T", bound="PasswordResetProcessData") +T = TypeVar("T", bound="PublicShareUnlock") @_attrs_define -class PasswordResetProcessData: +class PublicShareUnlock: """ Attributes: password (str): @@ -38,12 +38,12 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: d = dict(src_dict) password = d.pop("password") - password_reset_process_data = cls( + public_share_unlock = cls( password=password, ) - password_reset_process_data.additional_properties = d - return password_reset_process_data + public_share_unlock.additional_properties = d + return public_share_unlock @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/admin_user_view_name_change.py b/openshock/rest/models/public_share_unlock_response.py similarity index 59% rename from openshock/rest/models/admin_user_view_name_change.py rename to openshock/rest/models/public_share_unlock_response.py index 00eb2fb..0ff9b93 100644 --- a/openshock/rest/models/admin_user_view_name_change.py +++ b/openshock/rest/models/public_share_unlock_response.py @@ -8,37 +8,34 @@ from attrs import define as _attrs_define from attrs import field as _attrs_field -T = TypeVar("T", bound="AdminUserViewNameChange") +T = TypeVar("T", bound="PublicShareUnlockResponse") @_attrs_define -class AdminUserViewNameChange: +class PublicShareUnlockResponse: """ Attributes: - id (int): - old_name (str): - created_at (datetime.datetime): + token (str): Send it in the OpenShockPublicShareUnlock header when loading the share, and as the unlockToken + query + parameter when connecting to its hub. Invalid once the password is changed. + expires_on (datetime.datetime): """ - id: int - old_name: str - created_at: datetime.datetime + token: str + expires_on: datetime.datetime additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: - id = self.id + token = self.token - old_name = self.old_name - - created_at = self.created_at.isoformat() + expires_on = self.expires_on.isoformat() field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( { - "id": id, - "oldName": old_name, - "createdAt": created_at, + "token": token, + "expiresOn": expires_on, } ) @@ -47,20 +44,17 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: d = dict(src_dict) - id = d.pop("id") - - old_name = d.pop("oldName") + token = d.pop("token") - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + expires_on = datetime.datetime.fromisoformat(d.pop("expiresOn")) - admin_user_view_name_change = cls( - id=id, - old_name=old_name, - created_at=created_at, + public_share_unlock_response = cls( + token=token, + expires_on=expires_on, ) - admin_user_view_name_change.additional_properties = d - return admin_user_view_name_change + public_share_unlock_response.additional_properties = d + return public_share_unlock_response @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/public_user_profile_details.py b/openshock/rest/models/public_user_profile_details.py new file mode 100644 index 0000000..326d333 --- /dev/null +++ b/openshock/rest/models/public_user_profile_details.py @@ -0,0 +1,105 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.user_profile_social import UserProfileSocial + + +T = TypeVar("T", bound="PublicUserProfileDetails") + + +@_attrs_define +class PublicUserProfileDetails: + """ + Attributes: + pronouns (None | str): + bio (None | str): + socials (list[UserProfileSocial]): + """ + + pronouns: None | str + bio: None | str + socials: list[UserProfileSocial] + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + pronouns: None | str + pronouns = self.pronouns + + bio: None | str + bio = self.bio + + socials = [] + for socials_item_data in self.socials: + socials_item = socials_item_data.to_dict() + socials.append(socials_item) + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "pronouns": pronouns, + "bio": bio, + "socials": socials, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.user_profile_social import UserProfileSocial # noqa: PLC0415 + + d = dict(src_dict) + + def _parse_pronouns(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + pronouns = _parse_pronouns(d.pop("pronouns")) + + def _parse_bio(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) + + bio = _parse_bio(d.pop("bio")) + + socials = [] + _socials = d.pop("socials") + for socials_item_data in _socials: + socials_item = UserProfileSocial.from_dict(socials_item_data) + + socials.append(socials_item) + + public_user_profile_details = cls( + pronouns=pronouns, + bio=bio, + socials=socials, + ) + + public_user_profile_details.additional_properties = d + return public_user_profile_details + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/webhook_dto.py b/openshock/rest/models/public_user_profile_public_share.py similarity index 62% rename from openshock/rest/models/webhook_dto.py rename to openshock/rest/models/public_user_profile_public_share.py index ba0eb10..fe49147 100644 --- a/openshock/rest/models/webhook_dto.py +++ b/openshock/rest/models/public_user_profile_public_share.py @@ -1,31 +1,30 @@ # Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. from __future__ import annotations -import datetime from collections.abc import Mapping -from typing import Any, TypeVar +from typing import Any, TypeVar, cast from uuid import UUID from attrs import define as _attrs_define from attrs import field as _attrs_field -T = TypeVar("T", bound="WebhookDto") +T = TypeVar("T", bound="PublicUserProfilePublicShare") @_attrs_define -class WebhookDto: +class PublicUserProfilePublicShare: """ Attributes: id (UUID): name (str): - url (str): - created_at (datetime.datetime): + slug (None | str): + password_protected (bool): """ id: UUID name: str - url: str - created_at: datetime.datetime + slug: None | str + password_protected: bool additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -33,9 +32,10 @@ def to_dict(self) -> dict[str, Any]: name = self.name - url = self.url + slug: None | str + slug = self.slug - created_at = self.created_at.isoformat() + password_protected = self.password_protected field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) @@ -43,8 +43,8 @@ def to_dict(self) -> dict[str, Any]: { "id": id, "name": name, - "url": url, - "createdAt": created_at, + "slug": slug, + "passwordProtected": password_protected, } ) @@ -57,19 +57,24 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: name = d.pop("name") - url = d.pop("url") + def _parse_slug(data: object) -> None | str: + if data is None: + return data + return cast(None | str, data) - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + slug = _parse_slug(d.pop("slug")) - webhook_dto = cls( + password_protected = d.pop("passwordProtected") + + public_user_profile_public_share = cls( id=id, name=name, - url=url, - created_at=created_at, + slug=slug, + password_protected=password_protected, ) - webhook_dto.additional_properties = d - return webhook_dto + public_user_profile_public_share.additional_properties = d + return public_user_profile_public_share @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/public_user_profile_response.py b/openshock/rest/models/public_user_profile_response.py new file mode 100644 index 0000000..3ad74a1 --- /dev/null +++ b/openshock/rest/models/public_user_profile_response.py @@ -0,0 +1,107 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +if TYPE_CHECKING: + from ..models.basic_user_info import BasicUserInfo + from ..models.public_user_profile_details import PublicUserProfileDetails + from ..models.public_user_profile_public_share import PublicUserProfilePublicShare + + +T = TypeVar("T", bound="PublicUserProfileResponse") + + +@_attrs_define +class PublicUserProfileResponse: + """ + Attributes: + user (BasicUserInfo): + profile (PublicUserProfileDetails): + default_public_share (None | PublicUserProfilePublicShare): + """ + + user: BasicUserInfo + profile: PublicUserProfileDetails + default_public_share: None | PublicUserProfilePublicShare + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + from ..models.public_user_profile_public_share import PublicUserProfilePublicShare # noqa: PLC0415 + + user = self.user.to_dict() + + profile = self.profile.to_dict() + + default_public_share: dict[str, Any] | None + if isinstance(self.default_public_share, PublicUserProfilePublicShare): + default_public_share = self.default_public_share.to_dict() + else: + default_public_share = self.default_public_share + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "user": user, + "profile": profile, + "defaultPublicShare": default_public_share, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.basic_user_info import BasicUserInfo # noqa: PLC0415 + from ..models.public_user_profile_details import PublicUserProfileDetails # noqa: PLC0415 + from ..models.public_user_profile_public_share import PublicUserProfilePublicShare # noqa: PLC0415 + + d = dict(src_dict) + user = BasicUserInfo.from_dict(d.pop("user")) + + profile = PublicUserProfileDetails.from_dict(d.pop("profile")) + + def _parse_default_public_share(data: object) -> None | PublicUserProfilePublicShare: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + default_public_share_type_1 = PublicUserProfilePublicShare.from_dict(data) + + return default_public_share_type_1 + except (TypeError, ValueError, AttributeError, KeyError): + pass + return cast(None | PublicUserProfilePublicShare, data) + + default_public_share = _parse_default_public_share(d.pop("defaultPublicShare")) + + public_user_profile_response = cls( + user=user, + profile=profile, + default_public_share=default_public_share, + ) + + public_user_profile_response.additional_properties = d + return public_user_profile_response + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/openshock/rest/models/report_tokens_request.py b/openshock/rest/models/report_tokens_request.py deleted file mode 100644 index 8c6cafb..0000000 --- a/openshock/rest/models/report_tokens_request.py +++ /dev/null @@ -1,70 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="ReportTokensRequest") - - -@_attrs_define -class ReportTokensRequest: - """ - Attributes: - turnstile_response (str): - secrets (list[str]): - """ - - turnstile_response: str - secrets: list[str] - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - turnstile_response = self.turnstile_response - - secrets = self.secrets - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "turnstileResponse": turnstile_response, - "secrets": secrets, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - turnstile_response = d.pop("turnstileResponse") - - secrets = cast(list[str], d.pop("secrets")) - - report_tokens_request = cls( - turnstile_response=turnstile_response, - secrets=secrets, - ) - - report_tokens_request.additional_properties = d - return report_tokens_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/send_test_email_dto.py b/openshock/rest/models/send_test_email_dto.py deleted file mode 100644 index e3fd2d6..0000000 --- a/openshock/rest/models/send_test_email_dto.py +++ /dev/null @@ -1,98 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.email_type import EmailType -from ..types import UNSET, Unset - -T = TypeVar("T", bound="SendTestEmailDto") - - -@_attrs_define -class SendTestEmailDto: - """Request to enqueue a preview/test email of a chosen type to a chosen address. The message is - delivered by the Cron pipeline with placeholder data and a dummy link (no token, no request row). - - Attributes: - type_ (EmailType): The kind of email an outbox message represents. The outbox stores - only the intent to send one of these, never a rendered body or a usable secret, the - consumer maps the type to the matching template and (for token-bearing types) mints a fresh - secret at send time. - recipient (str): Destination address for the test email. - recipient_name (None | str | Unset): Optional display name for the recipient. - """ - - type_: EmailType - recipient: str - recipient_name: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - type_ = self.type_.value - - recipient = self.recipient - - recipient_name: None | str | Unset - if isinstance(self.recipient_name, Unset): - recipient_name = UNSET - else: - recipient_name = self.recipient_name - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "type": type_, - "recipient": recipient, - } - ) - if recipient_name is not UNSET: - field_dict["recipientName"] = recipient_name - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - type_ = EmailType(d.pop("type")) - - recipient = d.pop("recipient") - - def _parse_recipient_name(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - recipient_name = _parse_recipient_name(d.pop("recipientName", UNSET)) - - send_test_email_dto = cls( - type_=type_, - recipient=recipient, - recipient_name=recipient_name, - ) - - send_test_email_dto.additional_properties = d - return send_test_email_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/set_token_paused_request.py b/openshock/rest/models/set_token_paused_request.py deleted file mode 100644 index 4a6507c..0000000 --- a/openshock/rest/models/set_token_paused_request.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SetTokenPausedRequest") - - -@_attrs_define -class SetTokenPausedRequest: - """ - Attributes: - paused (bool): When true, the token is paused and may not send shocker control messages. - """ - - paused: bool - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - paused = self.paused - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "paused": paused, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - paused = d.pop("paused") - - set_token_paused_request = cls( - paused=paused, - ) - - set_token_paused_request.additional_properties = d - return set_token_paused_request - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/set_user_email_request_body.py b/openshock/rest/models/set_user_email_request_body.py deleted file mode 100644 index 6d555e5..0000000 --- a/openshock/rest/models/set_user_email_request_body.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SetUserEmailRequestBody") - - -@_attrs_define -class SetUserEmailRequestBody: - """ - Attributes: - email (str): - """ - - email: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - email = self.email - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "email": email, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - email = d.pop("email") - - set_user_email_request_body = cls( - email=email, - ) - - set_user_email_request_body.additional_properties = d - return set_user_email_request_body - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/set_user_name_request_body.py b/openshock/rest/models/set_user_name_request_body.py deleted file mode 100644 index 178e806..0000000 --- a/openshock/rest/models/set_user_name_request_body.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SetUserNameRequestBody") - - -@_attrs_define -class SetUserNameRequestBody: - """ - Attributes: - name (str): - """ - - name: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name = self.name - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "name": name, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - name = d.pop("name") - - set_user_name_request_body = cls( - name=name, - ) - - set_user_name_request_body.additional_properties = d - return set_user_name_request_body - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/shocker_limits.py b/openshock/rest/models/shocker_limits.py index 0429085..299d82a 100644 --- a/openshock/rest/models/shocker_limits.py +++ b/openshock/rest/models/shocker_limits.py @@ -15,7 +15,8 @@ class ShockerLimits: """ Attributes: intensity (int | None): - duration (int | None): + duration (int | None): Maximum duration in milliseconds. Does not apply to live control, which has no fixed + duration. """ intensity: int | None diff --git a/openshock/rest/models/shocker_response.py b/openshock/rest/models/shocker_response.py index 67b4bc9..5102c91 100644 --- a/openshock/rest/models/shocker_response.py +++ b/openshock/rest/models/shocker_response.py @@ -3,7 +3,7 @@ import datetime from collections.abc import Mapping -from typing import Any, TypeVar +from typing import TYPE_CHECKING, Any, TypeVar from uuid import UUID from attrs import define as _attrs_define @@ -11,6 +11,11 @@ from ..models.shocker_model_type import ShockerModelType +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + T = TypeVar("T", bound="ShockerResponse") @@ -20,6 +25,8 @@ class ShockerResponse: Attributes: name (str): is_paused (bool): + permissions (ShockerPermissions): + limits (ShockerLimits): created_on (datetime.datetime): id (UUID): rf_id (int): @@ -28,6 +35,8 @@ class ShockerResponse: name: str is_paused: bool + permissions: ShockerPermissions + limits: ShockerLimits created_on: datetime.datetime id: UUID rf_id: int @@ -39,6 +48,10 @@ def to_dict(self) -> dict[str, Any]: is_paused = self.is_paused + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + created_on = self.created_on.isoformat() id = str(self.id) @@ -53,6 +66,8 @@ def to_dict(self) -> dict[str, Any]: { "name": name, "isPaused": is_paused, + "permissions": permissions, + "limits": limits, "createdOn": created_on, "id": id, "rfId": rf_id, @@ -64,11 +79,18 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + d = dict(src_dict) name = d.pop("name") is_paused = d.pop("isPaused") + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) id = UUID(d.pop("id")) @@ -80,6 +102,8 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: shocker_response = cls( name=name, is_paused=is_paused, + permissions=permissions, + limits=limits, created_on=created_on, id=id, rf_id=rf_id, diff --git a/openshock/rest/models/shocker_with_device.py b/openshock/rest/models/shocker_with_device.py index 27b6f85..88ece53 100644 --- a/openshock/rest/models/shocker_with_device.py +++ b/openshock/rest/models/shocker_with_device.py @@ -3,7 +3,7 @@ import datetime from collections.abc import Mapping -from typing import Any, TypeVar +from typing import TYPE_CHECKING, Any, TypeVar from uuid import UUID from attrs import define as _attrs_define @@ -11,6 +11,11 @@ from ..models.shocker_model_type import ShockerModelType +if TYPE_CHECKING: + from ..models.shocker_limits import ShockerLimits + from ..models.shocker_permissions import ShockerPermissions + + T = TypeVar("T", bound="ShockerWithDevice") @@ -21,6 +26,8 @@ class ShockerWithDevice: device (UUID): name (str): is_paused (bool): + permissions (ShockerPermissions): + limits (ShockerLimits): created_on (datetime.datetime): id (UUID): rf_id (int): @@ -30,6 +37,8 @@ class ShockerWithDevice: device: UUID name: str is_paused: bool + permissions: ShockerPermissions + limits: ShockerLimits created_on: datetime.datetime id: UUID rf_id: int @@ -43,6 +52,10 @@ def to_dict(self) -> dict[str, Any]: is_paused = self.is_paused + permissions = self.permissions.to_dict() + + limits = self.limits.to_dict() + created_on = self.created_on.isoformat() id = str(self.id) @@ -58,6 +71,8 @@ def to_dict(self) -> dict[str, Any]: "device": device, "name": name, "isPaused": is_paused, + "permissions": permissions, + "limits": limits, "createdOn": created_on, "id": id, "rfId": rf_id, @@ -69,6 +84,9 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.shocker_limits import ShockerLimits # noqa: PLC0415 + from ..models.shocker_permissions import ShockerPermissions # noqa: PLC0415 + d = dict(src_dict) device = UUID(d.pop("device")) @@ -76,6 +94,10 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: is_paused = d.pop("isPaused") + permissions = ShockerPermissions.from_dict(d.pop("permissions")) + + limits = ShockerLimits.from_dict(d.pop("limits")) + created_on = datetime.datetime.fromisoformat(d.pop("createdOn")) id = UUID(d.pop("id")) @@ -88,6 +110,8 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: device=device, name=name, is_paused=is_paused, + permissions=permissions, + limits=limits, created_on=created_on, id=id, rf_id=rf_id, diff --git a/openshock/rest/models/sign_up_v2.py b/openshock/rest/models/sign_up_v2.py deleted file mode 100644 index 07329a8..0000000 --- a/openshock/rest/models/sign_up_v2.py +++ /dev/null @@ -1,86 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="SignUpV2") - - -@_attrs_define -class SignUpV2: - """ - Attributes: - username (str): - password (str): - email (str): - turnstile_response (str): - """ - - username: str - password: str - email: str - turnstile_response: str - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - username = self.username - - password = self.password - - email = self.email - - turnstile_response = self.turnstile_response - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "username": username, - "password": password, - "email": email, - "turnstileResponse": turnstile_response, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - username = d.pop("username") - - password = d.pop("password") - - email = d.pop("email") - - turnstile_response = d.pop("turnstileResponse") - - sign_up_v2 = cls( - username=username, - password=password, - email=email, - turnstile_response=turnstile_response, - ) - - sign_up_v2.additional_properties = d - return sign_up_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/social_platform.py b/openshock/rest/models/social_platform.py new file mode 100644 index 0000000..9bb07b7 --- /dev/null +++ b/openshock/rest/models/social_platform.py @@ -0,0 +1,22 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +from enum import StrEnum + + +class SocialPlatform(StrEnum): + BLUESKY = "Bluesky" + DISCORD = "Discord" + FETLIFE = "FetLife" + GITHUB = "GitHub" + INSTAGRAM = "Instagram" + KICK = "Kick" + MASTODON = "Mastodon" + REDDIT = "Reddit" + TELEGRAM = "Telegram" + TIKTOK = "TikTok" + TWITCH = "Twitch" + WEBSITE = "Website" + X = "X" + YOUTUBE = "YouTube" + + def __str__(self) -> str: + return str(self.value) diff --git a/openshock/rest/models/token_created_response_v2.py b/openshock/rest/models/token_created_response_v2.py deleted file mode 100644 index 0ff2f4b..0000000 --- a/openshock/rest/models/token_created_response_v2.py +++ /dev/null @@ -1,171 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.permission_type import PermissionType - -if TYPE_CHECKING: - from ..models.shocker_control_settings import ShockerControlSettings - - -T = TypeVar("T", bound="TokenCreatedResponseV2") - - -@_attrs_define -class TokenCreatedResponseV2: - """ - Attributes: - id (UUID): - name (str): - token (str): - created_at (datetime.datetime): - valid_until (datetime.datetime | None): - last_used (datetime.datetime | None): - permissions (list[PermissionType]): - shocker_control (ShockerControlSettings): Per-token shocker control configuration: a toggle plus min/max limits - for intensity and duration. - """ - - id: UUID - name: str - token: str - created_at: datetime.datetime - valid_until: datetime.datetime | None - last_used: datetime.datetime | None - permissions: list[PermissionType] - shocker_control: ShockerControlSettings - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - name = self.name - - token = self.token - - created_at = self.created_at.isoformat() - - valid_until: None | str - if isinstance(self.valid_until, datetime.datetime): - valid_until = self.valid_until.isoformat() - else: - valid_until = self.valid_until - - last_used: None | str - if isinstance(self.last_used, datetime.datetime): - last_used = self.last_used.isoformat() - else: - last_used = self.last_used - - permissions = [] - for permissions_item_data in self.permissions: - permissions_item = permissions_item_data.value - permissions.append(permissions_item) - - shocker_control = self.shocker_control.to_dict() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "name": name, - "token": token, - "createdAt": created_at, - "validUntil": valid_until, - "lastUsed": last_used, - "permissions": permissions, - "shockerControl": shocker_control, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.shocker_control_settings import ShockerControlSettings # noqa: PLC0415 - - d = dict(src_dict) - id = UUID(d.pop("id")) - - name = d.pop("name") - - token = d.pop("token") - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - def _parse_valid_until(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - valid_until_type_1 = datetime.datetime.fromisoformat(data) - - return valid_until_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - valid_until = _parse_valid_until(d.pop("validUntil")) - - def _parse_last_used(data: object) -> datetime.datetime | None: - if data is None: - return data - try: - if not isinstance(data, str): - raise TypeError() - last_used_type_1 = datetime.datetime.fromisoformat(data) - - return last_used_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(datetime.datetime | None, data) - - last_used = _parse_last_used(d.pop("lastUsed")) - - permissions = [] - _permissions = d.pop("permissions") - for permissions_item_data in _permissions: - permissions_item = PermissionType(permissions_item_data) - - permissions.append(permissions_item) - - shocker_control = ShockerControlSettings.from_dict(d.pop("shockerControl")) - - token_created_response_v2 = cls( - id=id, - name=name, - token=token, - created_at=created_at, - valid_until=valid_until, - last_used=last_used, - permissions=permissions, - shocker_control=shocker_control, - ) - - token_created_response_v2.additional_properties = d - return token_created_response_v2 - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/token_paused_response.py b/openshock/rest/models/token_paused_response.py deleted file mode 100644 index dbce49a..0000000 --- a/openshock/rest/models/token_paused_response.py +++ /dev/null @@ -1,62 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -T = TypeVar("T", bound="TokenPausedResponse") - - -@_attrs_define -class TokenPausedResponse: - """ - Attributes: - paused (bool): The now-set paused state of the token. - """ - - paused: bool - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - paused = self.paused - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "paused": paused, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - paused = d.pop("paused") - - token_paused_response = cls( - paused=paused, - ) - - token_paused_response.additional_properties = d - return token_paused_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/user_name_blacklist_dto.py b/openshock/rest/models/user_name_blacklist_dto.py deleted file mode 100644 index 3f1a8e9..0000000 --- a/openshock/rest/models/user_name_blacklist_dto.py +++ /dev/null @@ -1,90 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -import datetime -from collections.abc import Mapping -from typing import Any, TypeVar -from uuid import UUID - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.match_type_enum import MatchTypeEnum - -T = TypeVar("T", bound="UserNameBlacklistDto") - - -@_attrs_define -class UserNameBlacklistDto: - """ - Attributes: - id (UUID): - value (str): - match_type (MatchTypeEnum): - created_at (datetime.datetime): - """ - - id: UUID - value: str - match_type: MatchTypeEnum - created_at: datetime.datetime - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - id = str(self.id) - - value = self.value - - match_type = self.match_type.value - - created_at = self.created_at.isoformat() - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "id": id, - "value": value, - "matchType": match_type, - "createdAt": created_at, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - id = UUID(d.pop("id")) - - value = d.pop("value") - - match_type = MatchTypeEnum(d.pop("matchType")) - - created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) - - user_name_blacklist_dto = cls( - id=id, - value=value, - match_type=match_type, - created_at=created_at, - ) - - user_name_blacklist_dto.additional_properties = d - return user_name_blacklist_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/user_patch_dto.py b/openshock/rest/models/user_patch_dto.py deleted file mode 100644 index b4432b7..0000000 --- a/openshock/rest/models/user_patch_dto.py +++ /dev/null @@ -1,94 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..types import UNSET, Unset - -T = TypeVar("T", bound="UserPatchDto") - - -@_attrs_define -class UserPatchDto: - """ - Attributes: - name (None | str | Unset): - email (None | str | Unset): - """ - - name: None | str | Unset = UNSET - email: None | str | Unset = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - name: None | str | Unset - if isinstance(self.name, Unset): - name = UNSET - else: - name = self.name - - email: None | str | Unset - if isinstance(self.email, Unset): - email = UNSET - else: - email = self.email - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update({}) - if name is not UNSET: - field_dict["name"] = name - if email is not UNSET: - field_dict["email"] = email - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - - def _parse_name(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - name = _parse_name(d.pop("name", UNSET)) - - def _parse_email(data: object) -> None | str | Unset: - if data is None: - return data - if isinstance(data, Unset): - return data - return cast(None | str | Unset, data) - - email = _parse_email(d.pop("email", UNSET)) - - user_patch_dto = cls( - name=name, - email=email, - ) - - user_patch_dto.additional_properties = d - return user_patch_dto - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/add_username_blacklist_dto.py b/openshock/rest/models/user_profile_social.py similarity index 70% rename from openshock/rest/models/add_username_blacklist_dto.py rename to openshock/rest/models/user_profile_social.py index e962cb9..1798225 100644 --- a/openshock/rest/models/add_username_blacklist_dto.py +++ b/openshock/rest/models/user_profile_social.py @@ -7,34 +7,34 @@ from attrs import define as _attrs_define from attrs import field as _attrs_field -from ..models.match_type_enum import MatchTypeEnum +from ..models.social_platform import SocialPlatform -T = TypeVar("T", bound="AddUsernameBlacklistDto") +T = TypeVar("T", bound="UserProfileSocial") @_attrs_define -class AddUsernameBlacklistDto: +class UserProfileSocial: """ Attributes: - value (str): - match_type (MatchTypeEnum): + platform (SocialPlatform): + value (str): An absolute http(s) URL for SocialPlatform.Website, otherwise the handle on that platform. """ + platform: SocialPlatform value: str - match_type: MatchTypeEnum additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: - value = self.value + platform = self.platform.value - match_type = self.match_type.value + value = self.value field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( { + "platform": platform, "value": value, - "matchType": match_type, } ) @@ -43,17 +43,17 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: d = dict(src_dict) - value = d.pop("value") + platform = SocialPlatform(d.pop("platform")) - match_type = MatchTypeEnum(d.pop("matchType")) + value = d.pop("value") - add_username_blacklist_dto = cls( + user_profile_social = cls( + platform=platform, value=value, - match_type=match_type, ) - add_username_blacklist_dto.additional_properties = d - return add_username_blacklist_dto + user_profile_social.additional_properties = d + return user_profile_social @property def additional_keys(self) -> list[str]: diff --git a/openshock/rest/models/username_availability.py b/openshock/rest/models/username_availability.py deleted file mode 100644 index 844c793..0000000 --- a/openshock/rest/models/username_availability.py +++ /dev/null @@ -1,11 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class UsernameAvailability(StrEnum): - AVAILABLE = "Available" - INVALID = "Invalid" - TAKEN = "Taken" - - def __str__(self) -> str: - return str(self.value) diff --git a/openshock/rest/models/username_check_response.py b/openshock/rest/models/username_check_response.py deleted file mode 100644 index 6152a2a..0000000 --- a/openshock/rest/models/username_check_response.py +++ /dev/null @@ -1,103 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, TypeVar, cast - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.username_availability import UsernameAvailability -from ..types import UNSET, Unset - -if TYPE_CHECKING: - from ..models.username_error import UsernameError - - -T = TypeVar("T", bound="UsernameCheckResponse") - - -@_attrs_define -class UsernameCheckResponse: - """ - Attributes: - availability (UsernameAvailability): - error (None | Unset | UsernameError): - """ - - availability: UsernameAvailability - error: None | Unset | UsernameError = UNSET - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - from ..models.username_error import UsernameError # noqa: PLC0415 - - availability = self.availability.value - - error: dict[str, Any] | None | Unset - if isinstance(self.error, Unset): - error = UNSET - elif isinstance(self.error, UsernameError): - error = self.error.to_dict() - else: - error = self.error - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "availability": availability, - } - ) - if error is not UNSET: - field_dict["error"] = error - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - from ..models.username_error import UsernameError # noqa: PLC0415 - - d = dict(src_dict) - availability = UsernameAvailability(d.pop("availability")) - - def _parse_error(data: object) -> None | Unset | UsernameError: - if data is None: - return data - if isinstance(data, Unset): - return data - try: - if not isinstance(data, dict): - raise TypeError() - error_type_1 = UsernameError.from_dict(data) - - return error_type_1 - except (TypeError, ValueError, AttributeError, KeyError): - pass - return cast(None | Unset | UsernameError, data) - - error = _parse_error(d.pop("error", UNSET)) - - username_check_response = cls( - availability=availability, - error=error, - ) - - username_check_response.additional_properties = d - return username_check_response - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/username_error.py b/openshock/rest/models/username_error.py deleted file mode 100644 index 8917868..0000000 --- a/openshock/rest/models/username_error.py +++ /dev/null @@ -1,72 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from __future__ import annotations - -from collections.abc import Mapping -from typing import Any, TypeVar - -from attrs import define as _attrs_define -from attrs import field as _attrs_field - -from ..models.username_error_type import UsernameErrorType - -T = TypeVar("T", bound="UsernameError") - - -@_attrs_define -class UsernameError: - """ - Attributes: - message (str): - type_ (UsernameErrorType): - """ - - message: str - type_: UsernameErrorType - additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) - - def to_dict(self) -> dict[str, Any]: - message = self.message - - type_ = self.type_.value - - field_dict: dict[str, Any] = {} - field_dict.update(self.additional_properties) - field_dict.update( - { - "message": message, - "type": type_, - } - ) - - return field_dict - - @classmethod - def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: - d = dict(src_dict) - message = d.pop("message") - - type_ = UsernameErrorType(d.pop("type")) - - username_error = cls( - message=message, - type_=type_, - ) - - username_error.additional_properties = d - return username_error - - @property - def additional_keys(self) -> list[str]: - return list(self.additional_properties.keys()) - - def __getitem__(self, key: str) -> Any: - return self.additional_properties[key] - - def __setitem__(self, key: str, value: Any) -> None: - self.additional_properties[key] = value - - def __delitem__(self, key: str) -> None: - del self.additional_properties[key] - - def __contains__(self, key: str) -> bool: - return key in self.additional_properties diff --git a/openshock/rest/models/username_error_type.py b/openshock/rest/models/username_error_type.py deleted file mode 100644 index 360998a..0000000 --- a/openshock/rest/models/username_error_type.py +++ /dev/null @@ -1,14 +0,0 @@ -# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. -from enum import StrEnum - - -class UsernameErrorType(StrEnum): - BLACKLISTED = "Blacklisted" - OBNOXIOUSCHARACTERS = "ObnoxiousCharacters" - RESEMBLEEMAIL = "ResembleEmail" - STARTORENDWITHWHITESPACE = "StartOrEndWithWhitespace" - TOOLONG = "TooLong" - TOOSHORT = "TooShort" - - def __str__(self) -> str: - return str(self.value) From 1bda8df7f71560da542823ffbaf72013e39eb60f Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 18:28:14 +0100 Subject: [PATCH 8/9] Fix CI OpenAPI spec source --- .github/workflows/ci.yml | 4 +++- scripts/generate.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aaf892f..2f80862 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: - run: ruff format --check . - run: ruff check . - name: Check that the generated REST client is up to date - run: python scripts/generate.py --check + run: python scripts/generate.py --update --check typecheck: runs-on: ubuntu-latest @@ -40,4 +40,6 @@ jobs: with: python-version: ${{ matrix.python-version }} - run: pip install -e ".[dev]" + - name: Download the OpenAPI spec for generated-client tests + run: curl --fail --silent --show-error https://api.openshock.dev/openapi.json --output openapi/openapi.json - run: pytest --cov=openshock --cov-report=term-missing diff --git a/scripts/generate.py b/scripts/generate.py index 87820ff..e7f115a 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -30,7 +30,7 @@ SPEC = ROOT / "openapi" / "openapi.json" CONFIG = ROOT / "openapi" / "generator-config.yaml" TARGET = ROOT / "openshock" / "rest" -DEFAULT_SPEC_URL = "https://api.openshock.app/openapi.json" +DEFAULT_SPEC_URL = "https://api.openshock.dev/openapi.json" JSON = "application/json" HEADER = "# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand.\n" From 4fd74a3d1e597e2e58ef56edfb3cbdd7e5937109 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 18:38:45 +0100 Subject: [PATCH 9/9] test: update fixtures for current API schema --- tests/test_client.py | 8 +++++++- tests/test_generated.py | 3 ++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 888765f..c7a2b46 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -45,6 +45,8 @@ "model": "CaiXianlin", "name": "Leg", "isPaused": False, + "permissions": {"vibrate": True, "sound": True, "shock": True}, + "limits": {"intensity": None, "duration": None}, "createdOn": "2024-06-01T12:00:00Z", "somethingNewer": {"than": "the spec"}, } @@ -87,7 +89,11 @@ def test_api_token_header_and_user_agent(self): def test_hub_client_uses_device_token(self): body = { "message": "", - "data": {"id": HUB, "name": "d", "shockers": [{"id": SHOCKER, "rfId": 1, "model": "CaiXianlin"}]}, + "data": { + "id": HUB, + "name": "d", + "shockers": [{"id": SHOCKER, "rfId": 1, "model": "CaiXianlin"}], + }, } client, seen = client_for(httpx2.Response(200, json=body), cls=OpenShockHubClient) with client: diff --git a/tests/test_generated.py b/tests/test_generated.py index d960601..caff290 100644 --- a/tests/test_generated.py +++ b/tests/test_generated.py @@ -24,7 +24,8 @@ def operation_modules(): def test_every_operation_has_a_module_with_sync_and_async_variants(): operations = [op for item in SPEC["paths"].values() for method, op in item.items() if method in METHODS] modules = list(operation_modules()) - assert len(modules) == len(operations) > 100 + assert len(operations) > 0 + assert len(modules) == len(operations) for module in modules: # Operations without a response body only get the *_detailed pair. for variant in ("sync_detailed", "asyncio_detailed"):