diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 112dd8a..aaf892f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,9 +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 REST client is up to date + run: python scripts/generate.py --check typecheck: runs-on: ubuntu-latest @@ -31,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 d899aad..7e80f02 100644 --- a/README.md +++ b/README.md @@ -5,100 +5,286 @@ [![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** — 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+ ## Install ```bash -pip install openshock +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-cache-dir --no-binary websockets "openshock[realtime]" +``` + +On Windows PowerShell: + +```powershell +$env:BUILD_EXTENSION = "no" +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 -from openshock import OpenShockClient +from uuid import UUID + +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 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 + shocker_send_control.sync( + client=client, + body=ControlRequest( + shocks=[Control(id=UUID("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() +## The REST client -# Send a vibrate command -from openshock import Control +`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. -client.shockers.control([ - Control(id="shocker-uuid", type="Vibrate", intensity=50, duration=1000) -]) +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. -client.close() -``` +- **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=`. -Or use as a context manager: +| 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` | 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) | +| `meta` | Backend version and public stats | +| `hub_endpoints` | What a hub device itself calls (see below) | +| `integrations` | Integrations | + +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` | + +Endpoints without a response body only have the `_detailed` pair. + +The same client serves both styles: ```python -with OpenShockClient(api_token="your-api-token") as client: - stats = client.meta.online_stats() +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`. + +### 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"]`. -| 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()` | +## Errors -For hub/device endpoints, use `OpenShockHubClient`: +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 OpenShockHubClient +from openshock import OpenShockApiError, ShockerNoPermission, ShockerNotFoundOrNoAccess, ShockerPaused + +try: + shocker_send_control.sync(client=client, body=request) +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. 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. -hub = OpenShockHubClient(hub_token="device-token") -lcg = hub.hub.assign_lcg() -print(f"Connect to {lcg.host}:{lcg.port}") +## Realtime: user hub + +`UserHubClient` connects to the SignalR user hub. It needs `openshock[realtime]` and asyncio. + +```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` | + +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. + +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. + +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`. + +## Realtime: live control + +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. -Two client types for two auth schemes: +```python +import asyncio +from openshock.realtime import LiveControlClient +from openshock.rest.models import ControlType -- **`OpenShockClient(api_token=...)`** — User API token (`OpenShockToken` header) -- **`OpenShockHubClient(hub_token=...)`** — Device token (`DeviceToken` header) -Create API tokens at [openshock.app](https://openshock.app) under Settings > API Tokens. +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()) +``` -## Typed models +- `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 `OpenShockClient`, or `gateway=` to skip the lookup. -All responses are parsed into typed dataclasses: +The shockers need the *live* permission for your account. + +## Hub (device) endpoints + +For the endpoints a hub itself calls, use `OpenShockHubClient` with a device token: ```python -from openshock import ( - BackendInfo, Stats, User, Token, Device, Shocker, - ShockerPermissions, ShockerLimits, ShockerLog, Control, - Session, PublicShare, UserShares, ShareInvite, PauseReason, -) +from openshock import OpenShockHubClient, unwrap +from openshock.rest.api.hub_endpoints import device_get_self + +with OpenShockHubClient("device-token") as hub: + me = unwrap(device_get_self.sync(client=hub)).data + print(me.name, len(me.shockers), "shockers") ``` ## Self-hosting -To connect to a self-hosted instance: - ```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") ``` +## Examples + +Standalone example programs live in [`examples/`](examples), one folder each: + +| Folder | Shows | +|--------|-------| +| [`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 | + +They read `OPENSHOCK_API_TOKEN` (and `OPENSHOCK_API_URL` for self-hosted instances) from the environment. + ## Development ```bash @@ -106,19 +292,31 @@ git clone https://github.com/OpenShock/SDK.Python.git cd SDK.Python pip install -e ".[dev]" -# Format -ruff format . +ruff format . # format +ruff check . # lint +mypy openshock/ # type check +pytest # test +``` -# Lint -ruff check . +### Regenerating the REST client -# Type check -mypy openshock/ +Everything under `openshock/rest/` is generated from `openapi/openapi.json`, a snapshot of +the backend's OpenAPI document. Never edit it by hand. -# Test -pytest +```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 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 +clients (`openshock/client.py`), the error mapping (`openshock/exceptions.py`) and the +realtime clients (`openshock/realtime/`). + ## License [MIT](LICENSE) diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..3e2183e --- /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) | 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]` | + +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..4eb3ced --- /dev/null +++ b/examples/async_control/README.md @@ -0,0 +1,11 @@ +# Async control + +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 +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..5a76084 --- /dev/null +++ b/examples/async_control/main.py @@ -0,0 +1,51 @@ +""" +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 uuid import UUID + +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" +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 = 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 + + 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 shocker_send_control.asyncio(client=client, body=request) + 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..444664f --- /dev/null +++ b/examples/async_control/requirements.txt @@ -0,0 +1 @@ +openshock>=0.2.0b1 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..2386be7 --- /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 uuid import UUID + +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" +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 = UUID(sys.argv[1]) + + 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 = 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")) + 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..db9ee67 --- /dev/null +++ b/examples/live_control/requirements.txt @@ -0,0 +1 @@ +openshock[realtime]>=0.2.0b1 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..db9ee67 --- /dev/null +++ b/examples/realtime_events/requirements.txt @@ -0,0 +1 @@ +openshock[realtime]>=0.2.0b1 diff --git a/examples/rest_quickstart/README.md b/examples/rest_quickstart/README.md new file mode 100644 index 0000000..4984284 --- /dev/null +++ b/examples/rest_quickstart/README.md @@ -0,0 +1,11 @@ +# REST quickstart + +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 +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..ea6254a --- /dev/null +++ b/examples/rest_quickstart/main.py @@ -0,0 +1,37 @@ +"""List your hubs and shockers, and the shockers other people shared with you.""" + +import os +import sys + +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" +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, 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 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 unwrap(shocker_list_shared_shockers.sync(client=client)).data: + for shared_hub in owner.devices: + for shared in shared_hub.shockers: + 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/examples/rest_quickstart/requirements.txt b/examples/rest_quickstart/requirements.txt new file mode 100644 index 0000000..444664f --- /dev/null +++ b/examples/rest_quickstart/requirements.txt @@ -0,0 +1 @@ +openshock>=0.2.0b1 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 a803286..0084d73 100644 --- a/openshock/__init__.py +++ b/openshock/__init__.py @@ -1,45 +1,27 @@ +""" +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 .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 .models import BackendInfo as BackendInfo -from .models import BasicUserInfo as BasicUserInfo -from .models import Control as Control -from .models import ControlLogSender as ControlLogSender -from .models import ControlType as ControlType -from .models import Device as Device -from .models import DeviceSelf as DeviceSelf -from .models import DeviceWithToken as DeviceWithToken -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 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 -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 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 ShockerModelType as ShockerModelType -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 parse_dt as parse_dt -from .models import parse_uuid as parse_uuid +from .exceptions import OpenShockRateLimited as OpenShockRateLimited +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 .exceptions import unwrap as unwrap diff --git a/openshock/_core.py b/openshock/_core.py new file mode 100644 index 0000000..94f7a1a --- /dev/null +++ b/openshock/_core.py @@ -0,0 +1,53 @@ +"""Small helpers shared by the REST client wrapper and the realtime clients.""" + +from __future__ import annotations + +import platform +import re +from importlib.metadata import PackageNotFoundError, version + +from ._version import __version__ + +DEFAULT_BASE_URL = "https://api.openshock.app" +DEFAULT_TIMEOUT = 10.0 + +# ASCII only: HTTP header values cannot carry anything else. +_UA_UNSAFE = re.compile(r"[^\w.\-+ ]", re.ASCII) + + +def _os_name() -> str: + system = platform.system() + 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: tuple[str, ...] = (), +) -> str: + """ + Build the SDK User-Agent, e.g.:: + + 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()] + 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)})" 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/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 15bf2da..30b0b2b 100644 --- a/openshock/client.py +++ b/openshock/client.py @@ -1,192 +1,155 @@ +""" +Preconfigured clients for the generated REST API (:mod:`openshock.rest`). + +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 -from collections.abc import Callable -from types import TracebackType -from typing import Any, TypeVar +import contextlib +from typing import Any -import httpx +import httpx2 -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 +from ._core import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, build_user_agent +from .exceptions import OpenShockApiError, error_from_response +from .rest.client import AuthenticatedClient -T = TypeVar("T") -_SelfT = TypeVar("_SelfT", bound="_BaseClient") +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 _BaseClient: - """ - Internal base client that handles HTTP, auth and error mapping. - Concrete clients subclass this and attach resources. - """ + +class _PresetClient(AuthenticatedClient): + _header_name = "" def __init__( self, + credential: str | None = None, *, - auth: Auth, - base_url: str = "https://api.openshock.app", - timeout: float = 10.0, + 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: - self._auth = auth - self._client = httpx.Client( - base_url=base_url, + 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 - # --- lifecycle --------------------------------------------------------- + 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 close(self) -> None: - self._client.close() + 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 - def __enter__(self: _SelfT) -> _SelfT: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - self.close() + @property + def base_url(self) -> str: + return self._base_url - # --- internal helpers -------------------------------------------------- + @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} - 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): +class OpenShockClient(_PresetClient): """ - 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.") + Client for the user-facing REST API, authenticated with an API token. - if auth is None and api_token is None: - raise ValueError("You must provide either `auth` or `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:: - if auth is None: - auth = ApiTokenAuth(api_token) # type: ignore[arg-type] + from openshock import OpenShockClient, unwrap + from openshock.rest.api.shockers import shocker_list_shockers - super().__init__(auth=auth, base_url=base_url, timeout=timeout) + with OpenShockClient("your-api-token", app_name="MyApp", app_version="1.0") as client: + hubs = unwrap(shocker_list_shockers.sync(client=client)).data - 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) + 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. -class OpenShockHubClient(_BaseClient): - """ - High-level client for the *hub/device* OpenShock REST API (HubToken-based). + 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. """ - 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.") + _header_name = "OpenShockToken" + + def __init__(self, api_token: str | None = None, **kwargs: Any) -> None: + super().__init__(api_token, **kwargs) - 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] +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. + """ - super().__init__(auth=auth, base_url=base_url, timeout=timeout) + _header_name = "DeviceToken" - self.hub = HubResource(self) - self.meta = MetaResource(self) + 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 a380e22..cde1426 100644 --- a/openshock/exceptions.py +++ b/openshock/exceptions.py @@ -1,14 +1,277 @@ +from __future__ import annotations + +import contextlib +import json +import re +from dataclasses import dataclass, field +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") + + +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.""" + + 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) -> 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=_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}, + ) + + class OpenShockError(Exception): - """Base error for OpenShock client.""" + """Base error for everything raised by the OpenShock SDK.""" -class OpenShockAuthError(OpenShockError): +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: Problem | 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(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: Problem | 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: Problem | None = None + text: str | None = None + if isinstance(body_json, dict): + if "type" in body_json or "title" in body_json: + 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}" + + 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} + + 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) + + +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 ab6e93d..0000000 --- a/openshock/models/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -from .account import Token as Token -from .account import User as User -from .common import ControlType as ControlType -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 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 DeviceWithToken as DeviceWithToken -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 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 ShareInfo as ShareInfo -from .shocker import Shocker as Shocker -from .shocker import ShockerLimits as ShockerLimits -from .shocker import ShockerLog as ShockerLog -from .shocker import ShockerPermissions as ShockerPermissions diff --git a/openshock/models/account.py b/openshock/models/account.py deleted file mode 100644 index 3ff30e5..0000000 --- a/openshock/models/account.py +++ /dev/null @@ -1,51 +0,0 @@ -# openshock/models/account.py -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 - - @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=list(data.get("roles", [])), - rank=data["rank"], - ) - - -@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=list(data.get("permissions", [])), - ) diff --git a/openshock/models/common.py b/openshock/models/common.py deleted file mode 100644 index 8f847f6..0000000 --- a/openshock/models/common.py +++ /dev/null @@ -1,45 +0,0 @@ -from __future__ import annotations - -from datetime import datetime -from enum import IntFlag -from uuid import UUID - - -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) - - -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 datetime string (never None).""" - return datetime.fromisoformat(value.replace("Z", "+00:00")) - - -def require_uuid(value: str) -> UUID: - """Parse a required UUID string (never None).""" - 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 PauseReason(IntFlag): - """Bitfield for pause reasons. Values can be OR'd together.""" - - NONE = 0 - SHOCKER = 1 - USER_SHARE = 2 - PUBLIC_SHARE = 4 diff --git a/openshock/models/device.py b/openshock/models/device.py deleted file mode 100644 index 7f62bd0..0000000 --- a/openshock/models/device.py +++ /dev/null @@ -1,140 +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 require_dt, require_uuid - - -@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 DeviceWithToken: - """Response from creating a new device.""" - - id: UUID - name: str - created_on: datetime - token: str - - @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["token"], - ) - - -@dataclass -class PairCode: - id: str - created_on: datetime - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> PairCode: - return cls( - id=data["id"], - created_on=require_dt(data["createdOn"]), - ) - - -@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 OtaUpdate: - id: int - started_at: datetime - status: str - 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=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[Any] - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> DeviceSelf: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - shockers=data.get("shockers", []), - ) 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 7496296..0000000 --- a/openshock/models/session.py +++ /dev/null @@ -1,29 +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 - - @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")), - ) diff --git a/openshock/models/share.py b/openshock/models/share.py deleted file mode 100644 index 53a5e7f..0000000 --- a/openshock/models/share.py +++ /dev/null @@ -1,198 +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 PauseReason, parse_dt, 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 - 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=PauseReason(data.get("paused", 0)), - ) - - -@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=PauseReason(data.get("paused", 0)), - ) - - -@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", [])], - ) diff --git a/openshock/models/shocker.py b/openshock/models/shocker.py deleted file mode 100644 index 7ba5429..0000000 --- a/openshock/models/shocker.py +++ /dev/null @@ -1,178 +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 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 - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> Shocker: - return cls( - id=require_uuid(data["id"]), - name=data["name"], - rf_id=data["rfId"], - model=data["model"], - created_on=require_dt(data["createdOn"]), - is_paused=data.get("isPaused", False), - ) - - -@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=data["model"], - ) - - -@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 - - @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"], - controlled_by=ControlLogSender.from_dict(data["controlledBy"]), - intensity=data["intensity"], - duration=data["duration"], - ) - - -@dataclass -class Control: - """A single control command for POST /2/shockers/control.""" - - id: str | UUID - type: ControlType - intensity: int - duration: int - exclusive: bool = False - - def to_dict(self) -> dict[str, Any]: - return { - "id": str(self.id), - "type": self.type, - "intensity": self.intensity, - "duration": self.duration, - "exclusive": self.exclusive, - } - - -@dataclass -class ShareInfo: - shared_with: dict[str, Any] # BasicUserInfo - created_on: datetime - permissions: ShockerPermissions - limits: ShockerLimits - paused: bool - - @classmethod - def from_dict(cls, data: dict[str, Any]) -> ShareInfo: - return cls( - shared_with=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 new file mode 100644 index 0000000..a4fa1d8 --- /dev/null +++ b/openshock/realtime/__init__.py @@ -0,0 +1,32 @@ +""" +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 .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 +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..c126c7d --- /dev/null +++ b/openshock/realtime/_transport.py @@ -0,0 +1,462 @@ +"""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 StrEnum +from types import TracebackType +from typing import Any, Protocol, TypeVar + +import httpx2 +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") + + +class ConnectionState(StrEnum): + 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 httpx2.AsyncClient(timeout=10) as client: + resp = await client.get(http_url, headers={**headers, "User-Agent": user_agent}) + 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): + 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" + #: 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 + 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 + self._starting = False + self._abort_start = False + self._startup: asyncio.Future[ClientConnection] | None = None + + # --- 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._starting or (self._runner is not None and not self._runner.done()): + raise RuntimeError(f"{type(self).__name__} is already started") + + # 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: + self._closed.clear() + self._close_error = None + self._state = ConnectionState.CONNECTING + + 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() + 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(): + # 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: + """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 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, queue: asyncio.Queue[Any]) -> None: + while True: + item = await 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: + 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() + 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/_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 new file mode 100644 index 0000000..8c9292f --- /dev/null +++ b/openshock/realtime/live_control.py @@ -0,0 +1,364 @@ +from __future__ import annotations + +import asyncio +import json +import logging +import math +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 .._core import DEFAULT_BASE_URL, build_user_agent +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 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. +DEFAULT_TPS = 10 +#: A frame given to ``intake_frame`` stays active for this many ticks. +FRAME_HOLD_TICKS = 2.5 + +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: + """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: OpenShockClient | None = None, + base_url: str = DEFAULT_BASE_URL, + gateway: LcgResponseV2 | 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: OpenShockClient | None = client + + if client is not None: + self._headers = {**client.auth_headers, **self._headers} + elif api_token is not None: + 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 + 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",), + ) + + self._gateway: LcgResponseV2 | 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 + 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") + #: ``()`` — 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) -> LcgResponseV2 | 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 = _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, + 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)), _control_type(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.get_async_httpx_client().aclose() + + 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}" + if self._requested_tps is not None: + url += f"?tps={self._requested_tps}" + return url + + 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 = 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() + 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())) + self._ticks += 1 + + 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..c633193 --- /dev/null +++ b/openshock/realtime/models.py @@ -0,0 +1,161 @@ +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 ..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: + """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 + #: 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 + live_control: bool = False + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> ControlLog: + return cls( + shocker=BasicShockerInfo.from_dict(_get(data, "shocker")), + 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")), + 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..f351f2b --- /dev/null +++ b/openshock/realtime/user_hub.py @@ -0,0 +1,214 @@ +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 ..rest.models import Control +from ._events import Event +from ._signalr import SignalRConnection +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. +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 + + +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``). + + 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",), + ), + 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 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 = [_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: + """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 deleted file mode 100644 index e69de29..0000000 diff --git a/openshock/resources/account.py b/openshock/resources/account.py deleted file mode 100644 index cdf7072..0000000 --- a/openshock/resources/account.py +++ /dev/null @@ -1,66 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..models import Token, User - -if TYPE_CHECKING: - from ..client import _BaseClient - - -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(resp.get("data", 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)) - - 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 [])] - - 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} - if valid_until is not None: - body["validUntil"] = valid_until - resp = self._client._request("POST", "/1/tokens", json=body) - return Token.from_dict(resp.get("data", 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)) - - def edit_token( - self, - token_id: str | UUID, - *, - name: str | None = None, - permissions: list[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 - 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/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/openshock/resources/hub.py b/openshock/resources/hub.py deleted file mode 100644 index cb38ec3..0000000 --- a/openshock/resources/hub.py +++ /dev/null @@ -1,35 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -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(resp.get("data", 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(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) diff --git a/openshock/resources/meta.py b/openshock/resources/meta.py deleted file mode 100644 index 031c6a0..0000000 --- a/openshock/resources/meta.py +++ /dev/null @@ -1,23 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING - -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(resp.get("data", 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)) diff --git a/openshock/resources/sessions.py b/openshock/resources/sessions.py deleted file mode 100644 index 90b5748..0000000 --- a/openshock/resources/sessions.py +++ /dev/null @@ -1,29 +0,0 @@ -from __future__ import annotations - -import builtins -from typing import TYPE_CHECKING -from uuid import UUID - -from ..models import Session - -if TYPE_CHECKING: - from ..client import _BaseClient - - -class SessionsResource: - def __init__(self, client: _BaseClient) -> None: - self._client = client - - def list(self) -> builtins.list[Session]: - """GET /1/sessions — List all active login sessions.""" - resp = self._client._request("GET", "/1/sessions") - return [Session.from_dict(s) for s in (resp.get("data") or [])] - - def get_current(self) -> Session: - """GET /1/sessions/self — Get info about the current session.""" - resp = self._client._request("GET", "/1/sessions/self") - return Session.from_dict(resp.get("data", resp)) - - def delete(self, session_id: str | UUID) -> None: - """DELETE /1/sessions/{sessionId} — Revoke a session.""" - self._client._request("DELETE", f"/1/sessions/{session_id}") diff --git a/openshock/resources/shares.py b/openshock/resources/shares.py deleted file mode 100644 index f263f43..0000000 --- a/openshock/resources/shares.py +++ /dev/null @@ -1,113 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..models import ( - OwnPublicShare, - PublicShare, - ShockerLimits, - ShockerPermissions, -) - -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 (resp.get("data") or [])] - - def create_public( - self, - name: str, - *, - expires_on: str | None = None, - ) -> str: - """POST /1/shares/links — Create a new public share. Returns 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) - - 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(resp.get("data", 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}""" - 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}""" - 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}""" - 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, - ) -> Any: - """POST /1/shares/links/{publicShareId}/{shockerId}/pause""" - return self._client._request( - "POST", - f"/1/shares/links/{public_share_id}/{shocker_id}/pause", - json={"pause": pause}, - ) - - # --- 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/resources/shockers.py b/openshock/resources/shockers.py deleted file mode 100644 index 8bc88f3..0000000 --- a/openshock/resources/shockers.py +++ /dev/null @@ -1,212 +0,0 @@ -from __future__ import annotations - -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..models import ( - Control, - ShareCode, - ShareInfo, - ShockerLimits, - ShockerLog, - 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[dict[str, Any]]: - """GET /1/shockers/own — List all shockers belonging to the authenticated user.""" - resp = self._client._request("GET", "/1/shockers/own") - return resp.get("data") or [] - - def list_shared(self) -> list[dict[str, Any]]: - """GET /1/shockers/shared — List all shockers shared with the authenticated user.""" - resp = self._client._request("GET", "/1/shockers/shared") - return resp.get("data") or [] - - def get(self, shocker_id: str | UUID) -> dict[str, Any]: - """GET /1/shockers/{shockerId} — Get shocker info with device details.""" - resp = self._client._request("GET", f"/1/shockers/{shocker_id}") - return resp.get("data") or {} - - # --- CRUD --- - - def register( - self, - *, - name: str, - rf_id: int, - device: str | UUID, - model: str, - ) -> str: - """POST /1/shockers — Register a new shocker. Returns the new shocker ID.""" - body = { - "name": name, - "rfId": rf_id, - "device": str(device), - "model": model, - } - resp: Any = self._client._request("POST", "/1/shockers", json=body) - if isinstance(resp, dict): - return str(resp.get("data", "")) - return str(resp) - - def edit( - self, - shocker_id: str | UUID, - *, - name: str | None = None, - rf_id: int | None = None, - device: str | UUID | None = None, - model: 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"] = model - 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.""" - self._client._request("DELETE", f"/1/shockers/{shocker_id}") - - # --- control & pause --- - - def control( - self, - controls: Sequence[Control | dict[str, Any]], - *, - custom_name: str | None = None, - ) -> Any: - """POST /2/shockers/control — Send control commands to shockers (V2).""" - 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} - if custom_name is not None: - body["customName"] = custom_name - - return 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}) - - # --- 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 (resp.get("data") or [])] - - def all_logs( - self, - *, - offset: int = 0, - limit: int = 100, - ) -> list[dict[str, Any]]: - """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 [] - - # --- 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 [])] - - def create_share_code( - self, - shocker_id: str | UUID, - *, - permissions: ShockerPermissions, - limits: ShockerLimits, - ) -> str: - """POST /1/shockers/{shockerId}/shares — Create a share code. Returns 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) - - 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 [])] - - 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}""" - 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}""" - 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, - ) -> Any: - """POST /1/shockers/{shockerId}/shares/{sharedWithUserId}/pause""" - return self._client._request( - "POST", - f"/1/shockers/{shocker_id}/shares/{shared_with_user_id}/pause", - json={"pause": pause}, - ) diff --git a/openshock/resources/user_shares.py b/openshock/resources/user_shares.py deleted file mode 100644 index 82c456c..0000000 --- a/openshock/resources/user_shares.py +++ /dev/null @@ -1,116 +0,0 @@ -from __future__ import annotations - -from collections.abc import Sequence -from typing import TYPE_CHECKING, Any -from uuid import UUID - -from ..models import ( - 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(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.""" - 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) - if isinstance(resp, str): - return resp - return str(resp) - - 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 [])] - - 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 [])] - - 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) - - 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, - ) -> dict[str, Any]: - """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) - - 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( - "DELETE", - f"/2/shares/user/{user_id}/shockers", - json=[str(s) for s in shockers], - ) - - 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/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_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/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_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/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_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/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..6f13201 --- /dev/null +++ b/openshock/rest/models/__init__.py @@ -0,0 +1,214 @@ +# Generated by scripts/generate.py from openapi/openapi.json. Do not edit by hand. +"""Contains all the data models used in inputs/outputs""" + +from .backend_info_response import BackendInfoResponse +from .basic_user_info import BasicUserInfo +from .bulk_user_share_shockers_update_request import BulkUserShareShockersUpdateRequest +from .change_username_request import ChangeUsernameRequest +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_share_request import CreateShareRequest +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 .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_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_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_v2 import LoginV2 +from .login_v2_ok_response import LoginV2OkResponse +from .minimal_shocker import MinimalShocker +from .new_shocker import NewShocker +from .open_shock_problem import OpenShockProblem +from .own_public_share_response import OwnPublicShareResponse +from .owner_shocker_response import OwnerShockerResponse +from .paged_result_of_log_entry_with_hub import PagedResultOfLogEntryWithHub +from .password_reset_process_data import PasswordResetProcessData +from .password_reset_request_v2 import PasswordResetRequestV2 +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 .role_type import RoleType +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_response_v2 import TokenResponseV2 +from .user_control_stat_totals import UserControlStatTotals +from .user_control_stats import UserControlStats +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 + +__all__ = ( + "BackendInfoResponse", + "BasicUserInfo", + "BulkUserShareShockersUpdateRequest", + "ChangeUsernameRequest", + "Control", + "ControlLimitMode", + "ControlLogSenderLight", + "ControlRequest", + "ControlStatChangesRequest", + "ControlStatChangesResponse", + "ControlStatsResponse", + "ControlStatTotals", + "ControlType", + "CreateShareRequest", + "DailyControlStats", + "DeviceResponse", + "DeviceSelfResponse", + "DeviceWithShockersResponse", + "DeviceWithTokenResponse", + "DurationLimitSettings", + "GivenControlStats", + "HubCreateRequest", + "HubEditRequest", + "IntensityLimitSettings", + "LcgNodeResponseV2", + "LcgResponseV2", + "LegacyDataResponseOfArrayOfDeviceResponse", + "LegacyDataResponseOfArrayOfDeviceWithShockersResponse", + "LegacyDataResponseOfArrayOfLogEntry", + "LegacyDataResponseOfArrayOfOwnerShockerResponse", + "LegacyDataResponseOfArrayOfOwnPublicShareResponse", + "LegacyDataResponseOfArrayOfShareCodeInfo", + "LegacyDataResponseOfArrayOfShareInfo", + "LegacyDataResponseOfArrayOfShockerResponse", + "LegacyDataResponseOfBackendInfoResponse", + "LegacyDataResponseOfboolean", + "LegacyDataResponseOfDeviceSelfResponse", + "LegacyDataResponseOfDeviceWithTokenResponse", + "LegacyDataResponseOfGuid", + "LegacyDataResponseOfLegacyUserSelfResponse", + "LegacyDataResponseOfPauseReason", + "LegacyDataResponseOfPublicShareResponse", + "LegacyDataResponseOfShockerWithDevice", + "LegacyDataResponseOfStatsResponse", + "LegacyDataResponseOfstring", + "LegacyEmptyResponse", + "LegacyUserSelfResponse", + "LogEntry", + "LogEntryWithHub", + "LoginV2", + "LoginV2OkResponse", + "MinimalShocker", + "NewShocker", + "OpenShockProblem", + "OwnerShockerResponse", + "OwnPublicShareResponse", + "PagedResultOfLogEntryWithHub", + "PasswordResetProcessData", + "PasswordResetRequestV2", + "PauseRequest", + "PauseUserShareShockersRequest", + "PauseUserShareShockersResponse", + "PauseUserShareShockersResponsePauseStates", + "PermissionType", + "ProblemDetails", + "PublicShareCreate", + "PublicShareDevice", + "PublicShareEditShocker", + "PublicShareResponse", + "PublicShareShocker", + "ReceivedControlStats", + "RemoveUserSharesResponse", + "RoleType", + "ShareCodeInfo", + "SharedDevice", + "SharedShocker", + "ShareInfo", + "ShareInviteBaseDetails", + "ShockerControlSettings", + "ShockerControlStats", + "ShockerLimits", + "ShockerModelType", + "ShockerPermissions", + "ShockerPermLimitPair", + "ShockerPermLimitPairWithId", + "ShockerPermLimitPairWithIdAndName", + "ShockerResponse", + "ShockerWithDevice", + "SignUpV2", + "SortDirection", + "StatsResponse", + "TokenResponseV2", + "UserControlStats", + "UserControlStatTotals", + "UsernameAvailability", + "UsernameCheckResponse", + "UsernameError", + "UsernameErrorType", + "UserSelfResponse", + "UserShareInfo", + "V2UserShares", + "V2UserSharesListItem", +) 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_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/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_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/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/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_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_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_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/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/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/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_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/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/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/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/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_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_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/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 40da7f4..df79edd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,25 +4,27 @@ 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" +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"] +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", "Typing :: Typed", @@ -35,17 +37,31 @@ 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", +] +# 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,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 by scripts/generate.py, which formats it itself. +extend-exclude = ["openshock/rest"] [tool.ruff.lint] select = ["E", "F", "W", "I", "UP", "B", "SIM"] @@ -55,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 @@ -68,3 +84,10 @@ disallow_untyped_defs = false # --- pytest --- [tool.pytest.ini_options] 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..ab1dfdc --- /dev/null +++ b/scripts/generate.py @@ -0,0 +1,190 @@ +#!/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" +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" + + +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" + + 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. + 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/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..c366f30 --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,195 @@ +"""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 + #: 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: + 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 + 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}"]}) + 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..888765f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,59 +1,282 @@ -"""Tests for client construction and error handling.""" +"""The preconfigured clients driving generated operations: headers, sync/async, error mapping.""" +import json +from uuid import UUID + +import httpx2 import pytest -from openshock import OpenShockClient, OpenShockHubClient -from openshock.exceptions import OpenShockApiError, OpenShockAuthError, OpenShockError, OpenShockNotFound +from openshock import ( + HubOffline, + OpenShockApiError, + OpenShockAuthError, + OpenShockClient, + OpenShockHubClient, + OpenShockNotFound, + OpenShockRateLimited, + ShockerNoPermission, + ShockerNotFoundOrNoAccess, + ShockerPaused, + TokenPermissionMissing, + unwrap, +) +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 +from openshock.rest.models import Control, ControlRequest, ControlType, OpenShockProblem, ShockerModelType +HUB = "11111111-1111-1111-1111-111111111111" +SHOCKER = "22222222-2222-2222-2222-222222222222" -class TestClientConstruction: - def test_api_token(self): - client = OpenShockClient(api_token="test-token") - assert client._auth is not None - client.close() +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 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 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 test_both_auth_raises(self): - from openshock.auth import ApiTokenAuth +def client_for(response: httpx2.Response, cls=OpenShockClient, **kwargs): + seen: list[httpx2.Request] = [] - with pytest.raises(ValueError, match="not both"): - OpenShockClient(auth=ApiTokenAuth("x"), api_token="y") + def handler(request: httpx2.Request) -> httpx2.Response: + seen.append(request) + return response - 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") + return cls("tok", httpx_args={"transport": httpx2.MockTransport(handler)}, **kwargs), seen - def test_hub_context_manager(self): - with OpenShockHubClient(hub_token="test") as client: - assert hasattr(client, "hub") - assert hasattr(client, "meta") + +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() + 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) + + 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)) + +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 -class TestExceptionHierarchy: - def test_auth_error_is_openshock_error(self): - assert issubclass(OpenShockAuthError, OpenShockError) + 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) - def test_not_found_is_openshock_error(self): - assert issubclass(OpenShockNotFound, OpenShockError) + @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_api_error_is_openshock_error(self): - assert issubclass(OpenShockApiError, OpenShockError) + 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_generated.py b/tests/test_generated.py new file mode 100644 index 0000000..ed2f1b3 --- /dev/null +++ b/tests/test_generated.py @@ -0,0 +1,130 @@ +"""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 +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}") + 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) > 50 + 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(): + 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}} + + +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"} diff --git a/tests/test_live_control.py b/tests/test_live_control.py new file mode 100644 index 0000000..0aa7241 --- /dev/null +++ b/tests/test_live_control.py @@ -0,0 +1,276 @@ +"""LiveControlClient against a fake gateway: gateway lookup, ticking, ping/pong, retries.""" + +import asyncio +from uuid import UUID + +import httpx2 +import pytest + +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 + +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 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.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() + assert frames[0] == [ + {"shocker": SHOCKER, "intensity": 40, "type": "Vibrate"}, + {"shocker": OTHER, "intensity": 5, "type": "Shock"}, + ] + # Nothing more is sent once the frames expired. + await ticks(live, 2) + count = len(server.frames()) + await ticks(live, 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 ticks(live, 2) + count = len(server.frames()) + await ticks(live, 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[httpx2.Request] = [] + + def handler(request: httpx2.Request) -> httpx2.Response: + lookups.append(request) + return httpx2.Response(200, json=gateway) + + client = OpenShockClient(TOKEN, httpx_args={"transport": httpx2.MockTransport(handler)}) + live = LiveControlClient(HUB, client=client) + resolved = await live._resolve_gateway() + 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.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: httpx2.Request) -> httpx2.Response: + if next(answers) == 404: + return httpx2.Response( + 404, json={"type": "Device.NotOnline", "title": "Hub is not online", "status": 404} + ) + return httpx2.Response(200, json={"host": "unused", "port": 443, "pathPrefix": "", "country": "DE"}) + + 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.get_async_httpx_client().aclose() + + +def test_argument_validation(): + with pytest.raises(ValueError, match="not both"): + 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): + 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) + + +@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_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_user_hub.py b/tests/test_user_hub.py new file mode 100644 index 0000000..8577ac4 --- /dev/null +++ b/tests/test_user_hub.py @@ -0,0 +1,387 @@ +"""UserHubClient against a fake SignalR hub: handshake, events, invocations, reconnects.""" + +import asyncio +from uuid import UUID + +import pytest + +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 + +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=UUID(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=UUID(SHOCKER), type_=ControlType.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_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) + + @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()