From aaa287d7536c4225512d993cfd0ad0907c30d7b5 Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Thu, 5 Nov 2026 09:37:45 -0700 Subject: [PATCH] Add the watch cog: preload media through media-preload `[p]watch ` asks the home lab's media-preload service to cache a movie, a season, some episodes or the next N unwatched episodes, and keeps a progress message (with a Cancel button) updated until done. `link`/`unlink` store a Jellyfin user name for "next"; `status` and `cancel` work on request ids. The API client in clients/media-preload-client is generated from the service's OpenAPI spec with openapi-python-client (`mise run generate-client`); the cog installs it from this repo via info.json. Also: ruff target py311 (Red 3.5's Python), a dev group with the client, pytest, ruff and ty, and mise tasks. Lint and type checks cover the new cog; doge_alignment is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GUebqhE8dK19vyn4Ct5g1L --- README.md | 54 +- clients/media-preload-client/.gitignore | 23 + clients/media-preload-client/README.md | 122 ++++ .../media_preload_client/__init__.py | 8 + .../media_preload_client/api/__init__.py | 1 + .../api/agent/__init__.py | 1 + .../api/agent/claim_file.py | 175 +++++ .../api/agent/report_file.py | 186 +++++ .../api/default/__init__.py | 1 + .../api/default/get_health.py | 124 ++++ .../api/library/__init__.py | 1 + .../api/library/search_library.py | 211 ++++++ .../api/requests/__init__.py | 1 + .../api/requests/cancel_request.py | 166 +++++ .../api/requests/create_request.py | 200 ++++++ .../api/requests/get_request.py | 166 +++++ .../api/requests/list_requests.py | 191 ++++++ .../media_preload_client/client.py | 268 ++++++++ .../media_preload_client/errors.py | 16 + .../media_preload_client/models/__init__.py | 31 + .../media_preload_client/models/agent_job.py | 77 +++ .../models/claim_request.py | 61 ++ .../models/create_request.py | 118 ++++ .../models/file_report.py | 82 +++ .../models/file_report_result.py | 10 + .../models/file_status.py | 13 + .../media_preload_client/models/health.py | 69 ++ .../media_preload_client/models/media_item.py | 115 ++++ .../media_preload_client/models/media_type.py | 9 + .../models/preload_file.py | 131 ++++ .../models/preload_request.py | 136 ++++ .../media_preload_client/models/problem.py | 61 ++ .../models/request_status.py | 13 + .../media_preload_client/py.typed | 1 + .../media_preload_client/types.py | 54 ++ clients/media-preload-client/pyproject.toml | 25 + clients/media-preload.openapi.json | 647 ++++++++++++++++++ clients/openapi-python-client.yaml | 6 + mise.toml | 32 + pyproject.toml | 30 +- tests/conftest.py | 6 + tests/test_watch_spec.py | 184 +++++ uv.lock | 202 +++++- watch/__init__.py | 15 + watch/info.json | 15 + watch/spec.py | 228 ++++++ watch/watch.py | 620 +++++++++++++++++ 47 files changed, 4902 insertions(+), 4 deletions(-) create mode 100644 clients/media-preload-client/.gitignore create mode 100644 clients/media-preload-client/README.md create mode 100644 clients/media-preload-client/media_preload_client/__init__.py create mode 100644 clients/media-preload-client/media_preload_client/api/__init__.py create mode 100644 clients/media-preload-client/media_preload_client/api/agent/__init__.py create mode 100644 clients/media-preload-client/media_preload_client/api/agent/claim_file.py create mode 100644 clients/media-preload-client/media_preload_client/api/agent/report_file.py create mode 100644 clients/media-preload-client/media_preload_client/api/default/__init__.py create mode 100644 clients/media-preload-client/media_preload_client/api/default/get_health.py create mode 100644 clients/media-preload-client/media_preload_client/api/library/__init__.py create mode 100644 clients/media-preload-client/media_preload_client/api/library/search_library.py create mode 100644 clients/media-preload-client/media_preload_client/api/requests/__init__.py create mode 100644 clients/media-preload-client/media_preload_client/api/requests/cancel_request.py create mode 100644 clients/media-preload-client/media_preload_client/api/requests/create_request.py create mode 100644 clients/media-preload-client/media_preload_client/api/requests/get_request.py create mode 100644 clients/media-preload-client/media_preload_client/api/requests/list_requests.py create mode 100644 clients/media-preload-client/media_preload_client/client.py create mode 100644 clients/media-preload-client/media_preload_client/errors.py create mode 100644 clients/media-preload-client/media_preload_client/models/__init__.py create mode 100644 clients/media-preload-client/media_preload_client/models/agent_job.py create mode 100644 clients/media-preload-client/media_preload_client/models/claim_request.py create mode 100644 clients/media-preload-client/media_preload_client/models/create_request.py create mode 100644 clients/media-preload-client/media_preload_client/models/file_report.py create mode 100644 clients/media-preload-client/media_preload_client/models/file_report_result.py create mode 100644 clients/media-preload-client/media_preload_client/models/file_status.py create mode 100644 clients/media-preload-client/media_preload_client/models/health.py create mode 100644 clients/media-preload-client/media_preload_client/models/media_item.py create mode 100644 clients/media-preload-client/media_preload_client/models/media_type.py create mode 100644 clients/media-preload-client/media_preload_client/models/preload_file.py create mode 100644 clients/media-preload-client/media_preload_client/models/preload_request.py create mode 100644 clients/media-preload-client/media_preload_client/models/problem.py create mode 100644 clients/media-preload-client/media_preload_client/models/request_status.py create mode 100644 clients/media-preload-client/media_preload_client/py.typed create mode 100644 clients/media-preload-client/media_preload_client/types.py create mode 100644 clients/media-preload-client/pyproject.toml create mode 100644 clients/media-preload.openapi.json create mode 100644 clients/openapi-python-client.yaml create mode 100644 mise.toml create mode 100644 tests/conftest.py create mode 100644 tests/test_watch_spec.py create mode 100644 watch/__init__.py create mode 100644 watch/info.json create mode 100644 watch/spec.py create mode 100644 watch/watch.py diff --git a/README.md b/README.md index ef7f4b7..df578a6 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,55 @@ # doge_cogs - * [ ] RedBot Discord Bot cogs for dogebot +Red-DiscordBot cogs for dogebot. + +## Cogs + +| Cog | What it does | +|---|---| +| `doge_alignment` | Alignment chart manager | +| `watch` | Preload a movie or episodes into the home lab's media cache before you watch | + +## watch + +`[p]watch <title>` asks the home lab's media-preload service to fetch a movie or episodes into the VPS media +cache, so they stream quickly from webdav, and keeps a progress message updated until it's done. + +| Command | | +|---|---| +| `[p]watch The Matrix` | a movie | +| `[p]watch Dark Matter s2e8-10` | episodes 8 to 10 of season 2 (`s2e8`, `s2e1,3,5` work too) | +| `[p]watch Dark Matter s2` | a whole season | +| `[p]watch Dark Matter next 4` | your next 4 unwatched episodes (needs `link`) | +| `[p]watch Dark Matter` | a series without episodes: buttons for "next 3" or a season/episodes form | +| `[p]watch link <jellyfin name>` / `unlink` | link your Jellyfin user, for "next" | +| `[p]watch status [id]` | the latest requests, or one request's progress | +| `[p]watch cancel <id>` | cancel the files that haven't started (requester or moderators) | + +When several titles match, a menu asks which one. The progress message has a Cancel button. + +Configuration, read when each command runs: +- token: the `PRELOAD_BOT_TOKEN` environment variable, or `[p]set api media_preload token,<token>`; +- URL: `PRELOAD_API_URL`, or the `url` key of the same API tokens, defaulting to + `http://host.containers.internal:8125`. That is the host as seen from a rootless podman container. Inside + such a container the host's LAN address points back at the container itself. + +### The client library + +`clients/media-preload-client` is generated from media-preload's OpenAPI spec with +[openapi-python-client](https://github.com/openapi-generators/openapi-python-client), so don't edit it by hand. +The cog's `info.json` installs it from this repo with pip. To regenerate it after the API changes: + +```sh +mise run generate-client # fetches the live spec into clients/media-preload.openapi.json and regenerates +mise run check # ruff, ty and pytest for the watch cog +``` + +## Development + +mise installs uv, and uv installs Python 3.11 (what Red 3.5 needs) and the dependencies, including the +generated client in editable mode. Lint and type checks cover the `watch` cog and its tests. + +```sh +mise install && mise run sync +mise run fmt && mise run check +``` diff --git a/clients/media-preload-client/.gitignore b/clients/media-preload-client/.gitignore new file mode 100644 index 0000000..79a2c3d --- /dev/null +++ b/clients/media-preload-client/.gitignore @@ -0,0 +1,23 @@ +__pycache__/ +build/ +dist/ +*.egg-info/ +.pytest_cache/ + +# pyenv +.python-version + +# Environments +.env +.venv + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# JetBrains +.idea/ + +/coverage.xml +/.coverage diff --git a/clients/media-preload-client/README.md b/clients/media-preload-client/README.md new file mode 100644 index 0000000..7572192 --- /dev/null +++ b/clients/media-preload-client/README.md @@ -0,0 +1,122 @@ +# media-preload-client +A client library for accessing media-preload + +## Usage +First, create a client: + +```python +from media_preload_client import Client + +client = Client(base_url="https://api.example.com") +``` + +If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead: + +```python +from media_preload_client import AuthenticatedClient + +client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken") +``` + +Now call your endpoint and use your models: + +```python +from media_preload_client.models import MyDataModel +from media_preload_client.api.my_tag import get_my_data_model +from media_preload_client.types import Response + +with client as client: + my_data: MyDataModel = get_my_data_model.sync(client=client) + # or if you need more info (e.g. status_code) + response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client) +``` + +Or do the same thing with an async version: + +```python +from media_preload_client.models import MyDataModel +from media_preload_client.api.my_tag import get_my_data_model +from media_preload_client.types import Response + +async with client as client: + my_data: MyDataModel = await get_my_data_model.asyncio(client=client) + response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client) +``` + +By default, when you're calling an HTTPS API it will attempt to verify that SSL is working correctly. Using certificate verification is highly recommended most of the time, but sometimes you may need to authenticate to a server (especially an internal server) using a custom certificate bundle. + +```python +client = AuthenticatedClient( + base_url="https://internal_api.example.com", + token="SuperSecretToken", + verify_ssl="/path/to/certificate_bundle.pem", +) +``` + +You can also disable certificate validation altogether, but beware that **this is a security risk**. + +```python +client = AuthenticatedClient(base_url="https://internal_api.example.com", token="SuperSecretToken", verify_ssl=False) +``` + +Things to know: +1. Every path/method combo becomes a Python module with four functions: + 1. `sync`: Blocking request that returns parsed data (if successful) or `None` + 1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful. + 1. `asyncio`: Like `sync` but async instead of blocking + 1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking + +1. All path/query params, and bodies become method arguments. +1. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above) +1. Any endpoint which did not have a tag will be in `media_preload_client.api.default` + +## Advanced customizations + +There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case): + +```python +from media_preload_client import Client + + +def log_request(request): + print(f"Request event hook: {request.method} {request.url} - Waiting for response") + + +def log_response(response): + request = response.request + print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}") + + +client = Client( + base_url="https://api.example.com", + httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}}, +) + +# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client() +``` + +You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url): + +```python +import httpx +from media_preload_client import Client + +client = Client( + base_url="https://api.example.com", +) +# Note that base_url needs to be re-set, as would any shared cookies, headers, etc. +client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030")) +``` + +## Building / publishing this package +This project uses [uv](https://github.com/astral-sh/uv) to manage dependencies and packaging. Here are the basics: +1. Update the metadata in `pyproject.toml` (e.g. authors, version). +2. If you're using a private repository: https://docs.astral.sh/uv/guides/integration/alternative-indexes/ +3. Build a distribution with `uv build`, builds `sdist` and `wheel` by default. +1. Publish the client with `uv publish`, see documentation for publishing to private indexes. + +If you want to install this client into another project without publishing it (e.g. for development) then: +1. If that project **is using uv**, you can simply do `uv add <path-to-this-client>` from that project +1. If that project is not using uv: + 1. Build a wheel with `uv build --wheel`. + 1. Install that wheel from the other project `pip install <path-to-wheel>`. diff --git a/clients/media-preload-client/media_preload_client/__init__.py b/clients/media-preload-client/media_preload_client/__init__.py new file mode 100644 index 0000000..89d88b4 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/__init__.py @@ -0,0 +1,8 @@ +"""A client library for accessing media-preload""" + +from .client import AuthenticatedClient, Client + +__all__ = ( + "AuthenticatedClient", + "Client", +) diff --git a/clients/media-preload-client/media_preload_client/api/__init__.py b/clients/media-preload-client/media_preload_client/api/__init__.py new file mode 100644 index 0000000..81f9fa2 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/__init__.py @@ -0,0 +1 @@ +"""Contains methods for accessing the API""" diff --git a/clients/media-preload-client/media_preload_client/api/agent/__init__.py b/clients/media-preload-client/media_preload_client/api/agent/__init__.py new file mode 100644 index 0000000..2d7c0b2 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/agent/__init__.py @@ -0,0 +1 @@ +"""Contains endpoint functions for accessing the API""" diff --git a/clients/media-preload-client/media_preload_client/api/agent/claim_file.py b/clients/media-preload-client/media_preload_client/api/agent/claim_file.py new file mode 100644 index 0000000..18cb8dd --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/agent/claim_file.py @@ -0,0 +1,175 @@ +from http import HTTPStatus +from typing import Any, cast + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.agent_job import AgentJob +from ...models.claim_request import ClaimRequest +from ...models.problem import Problem +from ...types import Response + + +def _get_kwargs( + *, + body: ClaimRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/v1/agent/claim", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> AgentJob | Any | Problem | None: + if response.status_code == 200: + response_200 = AgentJob.from_dict(response.json()) + + return response_200 + + if response.status_code == 204: + response_204 = cast(Any, None) + return response_204 + + if response.status_code == 401: + response_401 = Problem.from_dict(response.json()) + + return response_401 + + if response.status_code == 403: + response_403 = Problem.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: httpx.Response +) -> Response[AgentJob | Any | Problem]: + 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: ClaimRequest, +) -> Response[AgentJob | Any | Problem]: + """Agent takes the next queued file + + Args: + body (ClaimRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AgentJob | Any | Problem] + """ + + 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: ClaimRequest, +) -> AgentJob | Any | Problem | None: + """Agent takes the next queued file + + Args: + body (ClaimRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AgentJob | Any | Problem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: ClaimRequest, +) -> Response[AgentJob | Any | Problem]: + """Agent takes the next queued file + + Args: + body (ClaimRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[AgentJob | Any | Problem] + """ + + 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: ClaimRequest, +) -> AgentJob | Any | Problem | None: + """Agent takes the next queued file + + Args: + body (ClaimRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + AgentJob | Any | Problem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/api/agent/report_file.py b/clients/media-preload-client/media_preload_client/api/agent/report_file.py new file mode 100644 index 0000000..def158b --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/agent/report_file.py @@ -0,0 +1,186 @@ +from http import HTTPStatus +from typing import Any, cast +from urllib.parse import quote + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.file_report import FileReport +from ...models.problem import Problem +from ...types import Response + + +def _get_kwargs( + file_id: int, + *, + body: FileReport, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/v1/agent/files/{file_id}".format( + file_id=quote(str(file_id), safe=""), + ), + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Any | Problem | None: + if response.status_code == 204: + response_204 = cast(Any, None) + return response_204 + + if response.status_code == 401: + response_401 = Problem.from_dict(response.json()) + + return response_401 + + if response.status_code == 403: + response_403 = Problem.from_dict(response.json()) + + return response_403 + + if response.status_code == 404: + response_404 = Problem.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: httpx.Response) -> Response[Any | Problem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + file_id: int, + *, + client: AuthenticatedClient | Client, + body: FileReport, +) -> Response[Any | Problem]: + """Agent reports the result for a claimed file + + Args: + file_id (int): + body (FileReport): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | Problem] + """ + + kwargs = _get_kwargs( + file_id=file_id, + body=body, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + file_id: int, + *, + client: AuthenticatedClient | Client, + body: FileReport, +) -> Any | Problem | None: + """Agent reports the result for a claimed file + + Args: + file_id (int): + body (FileReport): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | Problem + """ + + return sync_detailed( + file_id=file_id, + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + file_id: int, + *, + client: AuthenticatedClient | Client, + body: FileReport, +) -> Response[Any | Problem]: + """Agent reports the result for a claimed file + + Args: + file_id (int): + body (FileReport): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Any | Problem] + """ + + kwargs = _get_kwargs( + file_id=file_id, + body=body, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + file_id: int, + *, + client: AuthenticatedClient | Client, + body: FileReport, +) -> Any | Problem | None: + """Agent reports the result for a claimed file + + Args: + file_id (int): + body (FileReport): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Any | Problem + """ + + return ( + await asyncio_detailed( + file_id=file_id, + client=client, + body=body, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/api/default/__init__.py b/clients/media-preload-client/media_preload_client/api/default/__init__.py new file mode 100644 index 0000000..2d7c0b2 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/default/__init__.py @@ -0,0 +1 @@ +"""Contains endpoint functions for accessing the API""" diff --git a/clients/media-preload-client/media_preload_client/api/default/get_health.py b/clients/media-preload-client/media_preload_client/api/default/get_health.py new file mode 100644 index 0000000..6a653d2 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/default/get_health.py @@ -0,0 +1,124 @@ +from http import HTTPStatus +from typing import Any + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.health import Health +from ...types import Response + + +def _get_kwargs() -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/v1/health", + } + + return _kwargs + + +def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Health | None: + if response.status_code == 200: + response_200 = Health.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: httpx.Response) -> Response[Health]: + 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[Health]: + """Liveness and version + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Health] + """ + + kwargs = _get_kwargs() + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, +) -> Health | None: + """Liveness and version + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Health + """ + + return sync_detailed( + client=client, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, +) -> Response[Health]: + """Liveness and version + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Health] + """ + + 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, +) -> Health | None: + """Liveness and version + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Health + """ + + return ( + await asyncio_detailed( + client=client, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/api/library/__init__.py b/clients/media-preload-client/media_preload_client/api/library/__init__.py new file mode 100644 index 0000000..2d7c0b2 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/library/__init__.py @@ -0,0 +1 @@ +"""Contains endpoint functions for accessing the API""" diff --git a/clients/media-preload-client/media_preload_client/api/library/search_library.py b/clients/media-preload-client/media_preload_client/api/library/search_library.py new file mode 100644 index 0000000..8315267 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/library/search_library.py @@ -0,0 +1,211 @@ +from http import HTTPStatus +from typing import Any + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.media_item import MediaItem +from ...models.media_type import MediaType +from ...models.problem import Problem +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + q: str, + type_: MediaType | Unset = UNSET, + limit: int | Unset = 10, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + params["q"] = q + + json_type_: str | Unset = UNSET + if not isinstance(type_, Unset): + json_type_ = type_.value + + params["type"] = json_type_ + + 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": "/v1/search", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Problem | list[MediaItem] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = MediaItem.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 400: + response_400 = Problem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = Problem.from_dict(response.json()) + + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[Problem | list[MediaItem]]: + 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, + q: str, + type_: MediaType | Unset = UNSET, + limit: int | Unset = 10, +) -> Response[Problem | list[MediaItem]]: + """Search movies and series in Jellyfin + + Args: + q (str): + type_ (MediaType | Unset): + limit (int | Unset): Default: 10. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Problem | list[MediaItem]] + """ + + kwargs = _get_kwargs( + q=q, + type_=type_, + limit=limit, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + q: str, + type_: MediaType | Unset = UNSET, + limit: int | Unset = 10, +) -> Problem | list[MediaItem] | None: + """Search movies and series in Jellyfin + + Args: + q (str): + type_ (MediaType | Unset): + limit (int | Unset): Default: 10. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Problem | list[MediaItem] + """ + + return sync_detailed( + client=client, + q=q, + type_=type_, + limit=limit, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + q: str, + type_: MediaType | Unset = UNSET, + limit: int | Unset = 10, +) -> Response[Problem | list[MediaItem]]: + """Search movies and series in Jellyfin + + Args: + q (str): + type_ (MediaType | Unset): + limit (int | Unset): Default: 10. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Problem | list[MediaItem]] + """ + + kwargs = _get_kwargs( + q=q, + type_=type_, + limit=limit, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + q: str, + type_: MediaType | Unset = UNSET, + limit: int | Unset = 10, +) -> Problem | list[MediaItem] | None: + """Search movies and series in Jellyfin + + Args: + q (str): + type_ (MediaType | Unset): + limit (int | Unset): Default: 10. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Problem | list[MediaItem] + """ + + return ( + await asyncio_detailed( + client=client, + q=q, + type_=type_, + limit=limit, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/api/requests/__init__.py b/clients/media-preload-client/media_preload_client/api/requests/__init__.py new file mode 100644 index 0000000..2d7c0b2 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/requests/__init__.py @@ -0,0 +1 @@ +"""Contains endpoint functions for accessing the API""" diff --git a/clients/media-preload-client/media_preload_client/api/requests/cancel_request.py b/clients/media-preload-client/media_preload_client/api/requests/cancel_request.py new file mode 100644 index 0000000..97cab9e --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/requests/cancel_request.py @@ -0,0 +1,166 @@ +from http import HTTPStatus +from typing import Any +from urllib.parse import quote + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.preload_request import PreloadRequest +from ...models.problem import Problem +from ...types import Response + + +def _get_kwargs( + id: int, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "delete", + "url": "/v1/requests/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> PreloadRequest | Problem | None: + if response.status_code == 200: + response_200 = PreloadRequest.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = Problem.from_dict(response.json()) + + return response_401 + + if response.status_code == 404: + response_404 = Problem.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: httpx.Response +) -> Response[PreloadRequest | Problem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: int, + *, + client: AuthenticatedClient | Client, +) -> Response[PreloadRequest | Problem]: + """Cancel the files of a request that are still queued + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PreloadRequest | Problem] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: int, + *, + client: AuthenticatedClient | Client, +) -> PreloadRequest | Problem | None: + """Cancel the files of a request that are still queued + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PreloadRequest | Problem + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: int, + *, + client: AuthenticatedClient | Client, +) -> Response[PreloadRequest | Problem]: + """Cancel the files of a request that are still queued + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PreloadRequest | Problem] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: int, + *, + client: AuthenticatedClient | Client, +) -> PreloadRequest | Problem | None: + """Cancel the files of a request that are still queued + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PreloadRequest | Problem + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/api/requests/create_request.py b/clients/media-preload-client/media_preload_client/api/requests/create_request.py new file mode 100644 index 0000000..24bc2ef --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/requests/create_request.py @@ -0,0 +1,200 @@ +from http import HTTPStatus +from typing import Any + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.create_request import CreateRequest +from ...models.preload_request import PreloadRequest +from ...models.problem import Problem +from ...types import Response + + +def _get_kwargs( + *, + body: CreateRequest, +) -> dict[str, Any]: + headers: dict[str, Any] = {} + + _kwargs: dict[str, Any] = { + "method": "post", + "url": "/v1/requests", + } + + _kwargs["json"] = body.to_dict() + + headers["Content-Type"] = "application/json" + + _kwargs["headers"] = headers + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> PreloadRequest | Problem | None: + if response.status_code == 201: + response_201 = PreloadRequest.from_dict(response.json()) + + return response_201 + + if response.status_code == 400: + response_400 = Problem.from_dict(response.json()) + + return response_400 + + if response.status_code == 401: + response_401 = Problem.from_dict(response.json()) + + return response_401 + + if response.status_code == 404: + response_404 = Problem.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: httpx.Response +) -> Response[PreloadRequest | Problem]: + 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: CreateRequest, +) -> Response[PreloadRequest | Problem]: + """Ask for a movie or episodes to be cached + + For a movie, `season`, `episodes` and `next` are ignored. + For a series, give exactly one of: + - `season` (whole season), optionally with `episodes` (those episode numbers of that season); + - `next` (the next N unwatched episodes for `jellyfinUser`). + With none of them, a series defaults to `next: 3` and then needs `jellyfinUser`. + + Args: + body (CreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PreloadRequest | Problem] + """ + + 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: CreateRequest, +) -> PreloadRequest | Problem | None: + """Ask for a movie or episodes to be cached + + For a movie, `season`, `episodes` and `next` are ignored. + For a series, give exactly one of: + - `season` (whole season), optionally with `episodes` (those episode numbers of that season); + - `next` (the next N unwatched episodes for `jellyfinUser`). + With none of them, a series defaults to `next: 3` and then needs `jellyfinUser`. + + Args: + body (CreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PreloadRequest | Problem + """ + + return sync_detailed( + client=client, + body=body, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + body: CreateRequest, +) -> Response[PreloadRequest | Problem]: + """Ask for a movie or episodes to be cached + + For a movie, `season`, `episodes` and `next` are ignored. + For a series, give exactly one of: + - `season` (whole season), optionally with `episodes` (those episode numbers of that season); + - `next` (the next N unwatched episodes for `jellyfinUser`). + With none of them, a series defaults to `next: 3` and then needs `jellyfinUser`. + + Args: + body (CreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PreloadRequest | Problem] + """ + + 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: CreateRequest, +) -> PreloadRequest | Problem | None: + """Ask for a movie or episodes to be cached + + For a movie, `season`, `episodes` and `next` are ignored. + For a series, give exactly one of: + - `season` (whole season), optionally with `episodes` (those episode numbers of that season); + - `next` (the next N unwatched episodes for `jellyfinUser`). + With none of them, a series defaults to `next: 3` and then needs `jellyfinUser`. + + Args: + body (CreateRequest): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PreloadRequest | Problem + """ + + return ( + await asyncio_detailed( + client=client, + body=body, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/api/requests/get_request.py b/clients/media-preload-client/media_preload_client/api/requests/get_request.py new file mode 100644 index 0000000..d41dffa --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/requests/get_request.py @@ -0,0 +1,166 @@ +from http import HTTPStatus +from typing import Any +from urllib.parse import quote + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.preload_request import PreloadRequest +from ...models.problem import Problem +from ...types import Response + + +def _get_kwargs( + id: int, +) -> dict[str, Any]: + + _kwargs: dict[str, Any] = { + "method": "get", + "url": "/v1/requests/{id}".format( + id=quote(str(id), safe=""), + ), + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> PreloadRequest | Problem | None: + if response.status_code == 200: + response_200 = PreloadRequest.from_dict(response.json()) + + return response_200 + + if response.status_code == 401: + response_401 = Problem.from_dict(response.json()) + + return response_401 + + if response.status_code == 404: + response_404 = Problem.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: httpx.Response +) -> Response[PreloadRequest | Problem]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + id: int, + *, + client: AuthenticatedClient | Client, +) -> Response[PreloadRequest | Problem]: + """One request with per-file progress + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PreloadRequest | Problem] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + id: int, + *, + client: AuthenticatedClient | Client, +) -> PreloadRequest | Problem | None: + """One request with per-file progress + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PreloadRequest | Problem + """ + + return sync_detailed( + id=id, + client=client, + ).parsed + + +async def asyncio_detailed( + id: int, + *, + client: AuthenticatedClient | Client, +) -> Response[PreloadRequest | Problem]: + """One request with per-file progress + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[PreloadRequest | Problem] + """ + + kwargs = _get_kwargs( + id=id, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + id: int, + *, + client: AuthenticatedClient | Client, +) -> PreloadRequest | Problem | None: + """One request with per-file progress + + Args: + id (int): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + PreloadRequest | Problem + """ + + return ( + await asyncio_detailed( + id=id, + client=client, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/api/requests/list_requests.py b/clients/media-preload-client/media_preload_client/api/requests/list_requests.py new file mode 100644 index 0000000..409a7c8 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/api/requests/list_requests.py @@ -0,0 +1,191 @@ +from http import HTTPStatus +from typing import Any + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.preload_request import PreloadRequest +from ...models.problem import Problem +from ...models.request_status import RequestStatus +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + *, + status: RequestStatus | Unset = UNSET, + limit: int | Unset = 20, +) -> dict[str, Any]: + + params: dict[str, Any] = {} + + json_status: str | Unset = UNSET + if not isinstance(status, Unset): + json_status = status.value + + params["status"] = json_status + + 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": "/v1/requests", + "params": params, + } + + return _kwargs + + +def _parse_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Problem | list[PreloadRequest] | None: + if response.status_code == 200: + response_200 = [] + _response_200 = response.json() + for response_200_item_data in _response_200: + response_200_item = PreloadRequest.from_dict(response_200_item_data) + + response_200.append(response_200_item) + + return response_200 + + if response.status_code == 401: + response_401 = Problem.from_dict(response.json()) + + return response_401 + + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: AuthenticatedClient | Client, response: httpx.Response +) -> Response[Problem | list[PreloadRequest]]: + 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, + status: RequestStatus | Unset = UNSET, + limit: int | Unset = 20, +) -> Response[Problem | list[PreloadRequest]]: + """Recent requests, newest first + + Args: + status (RequestStatus | Unset): + limit (int | Unset): Default: 20. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Problem | list[PreloadRequest]] + """ + + kwargs = _get_kwargs( + status=status, + limit=limit, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + *, + client: AuthenticatedClient | Client, + status: RequestStatus | Unset = UNSET, + limit: int | Unset = 20, +) -> Problem | list[PreloadRequest] | None: + """Recent requests, newest first + + Args: + status (RequestStatus | Unset): + limit (int | Unset): Default: 20. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Problem | list[PreloadRequest] + """ + + return sync_detailed( + client=client, + status=status, + limit=limit, + ).parsed + + +async def asyncio_detailed( + *, + client: AuthenticatedClient | Client, + status: RequestStatus | Unset = UNSET, + limit: int | Unset = 20, +) -> Response[Problem | list[PreloadRequest]]: + """Recent requests, newest first + + Args: + status (RequestStatus | Unset): + limit (int | Unset): Default: 20. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Problem | list[PreloadRequest]] + """ + + kwargs = _get_kwargs( + status=status, + limit=limit, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + *, + client: AuthenticatedClient | Client, + status: RequestStatus | Unset = UNSET, + limit: int | Unset = 20, +) -> Problem | list[PreloadRequest] | None: + """Recent requests, newest first + + Args: + status (RequestStatus | Unset): + limit (int | Unset): Default: 20. + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Problem | list[PreloadRequest] + """ + + return ( + await asyncio_detailed( + client=client, + status=status, + limit=limit, + ) + ).parsed diff --git a/clients/media-preload-client/media_preload_client/client.py b/clients/media-preload-client/media_preload_client/client.py new file mode 100644 index 0000000..edb246d --- /dev/null +++ b/clients/media-preload-client/media_preload_client/client.py @@ -0,0 +1,268 @@ +import ssl +from typing import Any, Self + +import httpx +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 httpx 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 + httpx.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 ``httpx.Client`` and ``httpx.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: httpx.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: httpx.Client | None = field(default=None, init=False) + _async_client: httpx.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: httpx.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: httpx.Client) -> Self: + """Manually set the underlying httpx.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) -> httpx.Client: + """Get the underlying httpx.Client, constructing a new one if not previously set""" + if self._client is None: + self._client = httpx.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 httpx docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx.Client (see httpx docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> Self: + """Manually set the underlying httpx.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) -> httpx.AsyncClient: + """Get the underlying httpx.AsyncClient, constructing a new one if not previously set""" + if self._async_client is None: + self._async_client = httpx.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 httpx.AsyncClient—you cannot enter twice (see httpx 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 httpx.AsyncClient (see httpx 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 httpx 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 + httpx.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 ``httpx.Client`` and ``httpx.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: httpx.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: httpx.Client | None = field(default=None, init=False) + _async_client: httpx.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: httpx.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: httpx.Client) -> Self: + """Manually set the underlying httpx.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) -> httpx.Client: + """Get the underlying httpx.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 = httpx.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 httpx docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx.Client (see httpx docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> Self: + """Manually set the underlying httpx.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) -> httpx.AsyncClient: + """Get the underlying httpx.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 = httpx.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 httpx.AsyncClient—you cannot enter twice (see httpx 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 httpx.AsyncClient (see httpx docs)""" + await self.get_async_httpx_client().__aexit__(*args, **kwargs) diff --git a/clients/media-preload-client/media_preload_client/errors.py b/clients/media-preload-client/media_preload_client/errors.py new file mode 100644 index 0000000..5f92e76 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/errors.py @@ -0,0 +1,16 @@ +"""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/clients/media-preload-client/media_preload_client/models/__init__.py b/clients/media-preload-client/media_preload_client/models/__init__.py new file mode 100644 index 0000000..f356ef1 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/__init__.py @@ -0,0 +1,31 @@ +"""Contains all the data models used in inputs/outputs""" + +from .agent_job import AgentJob +from .claim_request import ClaimRequest +from .create_request import CreateRequest +from .file_report import FileReport +from .file_report_result import FileReportResult +from .file_status import FileStatus +from .health import Health +from .media_item import MediaItem +from .media_type import MediaType +from .preload_file import PreloadFile +from .preload_request import PreloadRequest +from .problem import Problem +from .request_status import RequestStatus + +__all__ = ( + "AgentJob", + "ClaimRequest", + "CreateRequest", + "FileReport", + "FileReportResult", + "FileStatus", + "Health", + "MediaItem", + "MediaType", + "PreloadFile", + "PreloadRequest", + "Problem", + "RequestStatus", +) diff --git a/clients/media-preload-client/media_preload_client/models/agent_job.py b/clients/media-preload-client/media_preload_client/models/agent_job.py new file mode 100644 index 0000000..da306fe --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/agent_job.py @@ -0,0 +1,77 @@ +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="AgentJob") + + +@_attrs_define +class AgentJob: + """ + Attributes: + file_id (int): + path (str): + size_bytes (int): + """ + + file_id: int + path: str + size_bytes: int + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + file_id = self.file_id + + path = self.path + + size_bytes = self.size_bytes + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "fileId": file_id, + "path": path, + "sizeBytes": size_bytes, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + file_id = d.pop("fileId") + + path = d.pop("path") + + size_bytes = d.pop("sizeBytes") + + agent_job = cls( + file_id=file_id, + path=path, + size_bytes=size_bytes, + ) + + agent_job.additional_properties = d + return agent_job + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/clients/media-preload-client/media_preload_client/models/claim_request.py b/clients/media-preload-client/media_preload_client/models/claim_request.py new file mode 100644 index 0000000..9d5ad30 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/claim_request.py @@ -0,0 +1,61 @@ +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="ClaimRequest") + + +@_attrs_define +class ClaimRequest: + """ + Attributes: + agent_id (str): Example: vps-dcruit2r. + """ + + agent_id: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + agent_id = self.agent_id + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "agentId": agent_id, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + agent_id = d.pop("agentId") + + claim_request = cls( + agent_id=agent_id, + ) + + claim_request.additional_properties = d + return claim_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/clients/media-preload-client/media_preload_client/models/create_request.py b/clients/media-preload-client/media_preload_client/models/create_request.py new file mode 100644 index 0000000..111e7d4 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/create_request.py @@ -0,0 +1,118 @@ +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="CreateRequest") + + +@_attrs_define +class CreateRequest: + """ + Attributes: + item_id (str): Jellyfin item id from /v1/search + requested_by (str): Who asked + episodes (list[int] | Unset): Episode numbers within `season` + jellyfin_user (str | Unset): Jellyfin user name whose watch progress decides "next" + next_ (int | Unset): Next N unwatched episodes for jellyfinUser + note (str | Unset): + season (int | Unset): + """ + + item_id: str + requested_by: str + episodes: list[int] | Unset = UNSET + jellyfin_user: str | Unset = UNSET + next_: int | Unset = UNSET + note: str | Unset = UNSET + season: int | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + item_id = self.item_id + + requested_by = self.requested_by + + episodes: list[int] | Unset = UNSET + if not isinstance(self.episodes, Unset): + episodes = self.episodes + + jellyfin_user = self.jellyfin_user + + next_ = self.next_ + + note = self.note + + season = self.season + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "itemId": item_id, + "requestedBy": requested_by, + } + ) + if episodes is not UNSET: + field_dict["episodes"] = episodes + if jellyfin_user is not UNSET: + field_dict["jellyfinUser"] = jellyfin_user + if next_ is not UNSET: + field_dict["next"] = next_ + if note is not UNSET: + field_dict["note"] = note + if season is not UNSET: + field_dict["season"] = season + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + item_id = d.pop("itemId") + + requested_by = d.pop("requestedBy") + + episodes = cast(list[int], d.pop("episodes", UNSET)) + + jellyfin_user = d.pop("jellyfinUser", UNSET) + + next_ = d.pop("next", UNSET) + + note = d.pop("note", UNSET) + + season = d.pop("season", UNSET) + + create_request = cls( + item_id=item_id, + requested_by=requested_by, + episodes=episodes, + jellyfin_user=jellyfin_user, + next_=next_, + note=note, + season=season, + ) + + create_request.additional_properties = d + return 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/clients/media-preload-client/media_preload_client/models/file_report.py b/clients/media-preload-client/media_preload_client/models/file_report.py new file mode 100644 index 0000000..31910ea --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/file_report.py @@ -0,0 +1,82 @@ +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.file_report_result import FileReportResult +from ..types import UNSET, Unset + +T = TypeVar("T", bound="FileReport") + + +@_attrs_define +class FileReport: + """ + Attributes: + result (FileReportResult): + bytes_ (int | Unset): Bytes read from home for this file + error (str | Unset): + """ + + result: FileReportResult + bytes_: int | Unset = UNSET + error: str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + result = self.result.value + + bytes_ = self.bytes_ + + error = self.error + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "result": result, + } + ) + if bytes_ is not UNSET: + field_dict["bytes"] = bytes_ + 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: + d = dict(src_dict) + result = FileReportResult(d.pop("result")) + + bytes_ = d.pop("bytes", UNSET) + + error = d.pop("error", UNSET) + + file_report = cls( + result=result, + bytes_=bytes_, + error=error, + ) + + file_report.additional_properties = d + return file_report + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/clients/media-preload-client/media_preload_client/models/file_report_result.py b/clients/media-preload-client/media_preload_client/models/file_report_result.py new file mode 100644 index 0000000..6467922 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/file_report_result.py @@ -0,0 +1,10 @@ +from enum import StrEnum + + +class FileReportResult(StrEnum): + ALREADY_CACHED = "already_cached" + CACHED = "cached" + FAILED = "failed" + + def __str__(self) -> str: + return str(self.value) diff --git a/clients/media-preload-client/media_preload_client/models/file_status.py b/clients/media-preload-client/media_preload_client/models/file_status.py new file mode 100644 index 0000000..c7e3074 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/file_status.py @@ -0,0 +1,13 @@ +from enum import StrEnum + + +class FileStatus(StrEnum): + CACHED = "cached" + CANCELED = "canceled" + FAILED = "failed" + FETCHING = "fetching" + NOT_CACHEABLE = "not_cacheable" + QUEUED = "queued" + + def __str__(self) -> str: + return str(self.value) diff --git a/clients/media-preload-client/media_preload_client/models/health.py b/clients/media-preload-client/media_preload_client/models/health.py new file mode 100644 index 0000000..c363342 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/health.py @@ -0,0 +1,69 @@ +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="Health") + + +@_attrs_define +class Health: + """ + Attributes: + status (str): Example: ok. + version (str): + """ + + status: str + version: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + status = self.status + + version = self.version + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "status": status, + "version": version, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + status = d.pop("status") + + version = d.pop("version") + + health = cls( + status=status, + version=version, + ) + + health.additional_properties = d + return health + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/clients/media-preload-client/media_preload_client/models/media_item.py b/clients/media-preload-client/media_preload_client/models/media_item.py new file mode 100644 index 0000000..2b7dd0a --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/media_item.py @@ -0,0 +1,115 @@ +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.media_type import MediaType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="MediaItem") + + +@_attrs_define +class MediaItem: + """ + Attributes: + cacheable (bool): False when the item lives outside the cached folders + id (str): Jellyfin item id + name (str): + type_ (MediaType): + library (str | Unset): Jellyfin library path prefix, e.g. /media2/Videos/tvshows + season_count (int | Unset): + year (int | Unset): + """ + + cacheable: bool + id: str + name: str + type_: MediaType + library: str | Unset = UNSET + season_count: int | Unset = UNSET + year: int | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + cacheable = self.cacheable + + id = self.id + + name = self.name + + type_ = self.type_.value + + library = self.library + + season_count = self.season_count + + year = self.year + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "cacheable": cacheable, + "id": id, + "name": name, + "type": type_, + } + ) + if library is not UNSET: + field_dict["library"] = library + if season_count is not UNSET: + field_dict["seasonCount"] = season_count + if year is not UNSET: + field_dict["year"] = year + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + cacheable = d.pop("cacheable") + + id = d.pop("id") + + name = d.pop("name") + + type_ = MediaType(d.pop("type")) + + library = d.pop("library", UNSET) + + season_count = d.pop("seasonCount", UNSET) + + year = d.pop("year", UNSET) + + media_item = cls( + cacheable=cacheable, + id=id, + name=name, + type_=type_, + library=library, + season_count=season_count, + year=year, + ) + + media_item.additional_properties = d + return media_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/clients/media-preload-client/media_preload_client/models/media_type.py b/clients/media-preload-client/media_preload_client/models/media_type.py new file mode 100644 index 0000000..6541376 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/media_type.py @@ -0,0 +1,9 @@ +from enum import StrEnum + + +class MediaType(StrEnum): + MOVIE = "movie" + SERIES = "series" + + def __str__(self) -> str: + return str(self.value) diff --git a/clients/media-preload-client/media_preload_client/models/preload_file.py b/clients/media-preload-client/media_preload_client/models/preload_file.py new file mode 100644 index 0000000..bb03632 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/preload_file.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import datetime +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..models.file_status import FileStatus +from ..types import UNSET, Unset + +T = TypeVar("T", bound="PreloadFile") + + +@_attrs_define +class PreloadFile: + """ + Attributes: + id (int): + path (str): Path as seen by Jellyfin and webdav, e.g. /media2/Videos/tvshows/... + size_bytes (int): + status (FileStatus): + title (str): e.g. Dark Matter S02E08 + error (str | Unset): + fetched_bytes (int | Unset): + updated_at (datetime.datetime | Unset): + """ + + id: int + path: str + size_bytes: int + status: FileStatus + title: str + error: str | Unset = UNSET + fetched_bytes: int | Unset = UNSET + updated_at: datetime.datetime | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + id = self.id + + path = self.path + + size_bytes = self.size_bytes + + status = self.status.value + + title = self.title + + error = self.error + + fetched_bytes = self.fetched_bytes + + updated_at: str | Unset = UNSET + if not isinstance(self.updated_at, Unset): + updated_at = self.updated_at.isoformat() + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "id": id, + "path": path, + "sizeBytes": size_bytes, + "status": status, + "title": title, + } + ) + if error is not UNSET: + field_dict["error"] = error + if fetched_bytes is not UNSET: + field_dict["fetchedBytes"] = fetched_bytes + if updated_at is not UNSET: + field_dict["updatedAt"] = updated_at + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + id = d.pop("id") + + path = d.pop("path") + + size_bytes = d.pop("sizeBytes") + + status = FileStatus(d.pop("status")) + + title = d.pop("title") + + error = d.pop("error", UNSET) + + fetched_bytes = d.pop("fetchedBytes", UNSET) + + _updated_at = d.pop("updatedAt", UNSET) + updated_at: datetime.datetime | Unset + if isinstance(_updated_at, Unset): + updated_at = UNSET + else: + updated_at = datetime.datetime.fromisoformat(_updated_at) + + preload_file = cls( + id=id, + path=path, + size_bytes=size_bytes, + status=status, + title=title, + error=error, + fetched_bytes=fetched_bytes, + updated_at=updated_at, + ) + + preload_file.additional_properties = d + return preload_file + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/clients/media-preload-client/media_preload_client/models/preload_request.py b/clients/media-preload-client/media_preload_client/models/preload_request.py new file mode 100644 index 0000000..e1fa4d7 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/preload_request.py @@ -0,0 +1,136 @@ +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 + +from ..models.request_status import RequestStatus +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.preload_file import PreloadFile + + +T = TypeVar("T", bound="PreloadRequest") + + +@_attrs_define +class PreloadRequest: + """ + Attributes: + created_at (datetime.datetime): + files (list[PreloadFile]): + id (int): + item_id (str): + requested_by (str): + status (RequestStatus): + title (str): + note (str | Unset): + """ + + created_at: datetime.datetime + files: list[PreloadFile] + id: int + item_id: str + requested_by: str + status: RequestStatus + title: str + note: str | Unset = UNSET + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + created_at = self.created_at.isoformat() + + files = [] + for files_item_data in self.files: + files_item = files_item_data.to_dict() + files.append(files_item) + + id = self.id + + item_id = self.item_id + + requested_by = self.requested_by + + status = self.status.value + + title = self.title + + note = self.note + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "createdAt": created_at, + "files": files, + "id": id, + "itemId": item_id, + "requestedBy": requested_by, + "status": status, + "title": title, + } + ) + if note is not UNSET: + field_dict["note"] = note + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + from ..models.preload_file import PreloadFile # noqa: PLC0415 + + d = dict(src_dict) + created_at = datetime.datetime.fromisoformat(d.pop("createdAt")) + + files = [] + _files = d.pop("files") + for files_item_data in _files: + files_item = PreloadFile.from_dict(files_item_data) + + files.append(files_item) + + id = d.pop("id") + + item_id = d.pop("itemId") + + requested_by = d.pop("requestedBy") + + status = RequestStatus(d.pop("status")) + + title = d.pop("title") + + note = d.pop("note", UNSET) + + preload_request = cls( + created_at=created_at, + files=files, + id=id, + item_id=item_id, + requested_by=requested_by, + status=status, + title=title, + note=note, + ) + + preload_request.additional_properties = d + return preload_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/clients/media-preload-client/media_preload_client/models/problem.py b/clients/media-preload-client/media_preload_client/models/problem.py new file mode 100644 index 0000000..26e1192 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/problem.py @@ -0,0 +1,61 @@ +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="Problem") + + +@_attrs_define +class Problem: + """ + Attributes: + error (str): Example: series requests need jellyfinUser when using next. + """ + + error: str + additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> dict[str, Any]: + error = self.error + + field_dict: dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "error": error, + } + ) + + return field_dict + + @classmethod + def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: + d = dict(src_dict) + error = d.pop("error") + + problem = cls( + error=error, + ) + + problem.additional_properties = d + return 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/clients/media-preload-client/media_preload_client/models/request_status.py b/clients/media-preload-client/media_preload_client/models/request_status.py new file mode 100644 index 0000000..cbe14ca --- /dev/null +++ b/clients/media-preload-client/media_preload_client/models/request_status.py @@ -0,0 +1,13 @@ +from enum import StrEnum + + +class RequestStatus(StrEnum): + CANCELED = "canceled" + DONE = "done" + FAILED = "failed" + FETCHING = "fetching" + PARTIAL = "partial" + QUEUED = "queued" + + def __str__(self) -> str: + return str(self.value) diff --git a/clients/media-preload-client/media_preload_client/py.typed b/clients/media-preload-client/media_preload_client/py.typed new file mode 100644 index 0000000..1aad327 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561 \ No newline at end of file diff --git a/clients/media-preload-client/media_preload_client/types.py b/clients/media-preload-client/media_preload_client/types.py new file mode 100644 index 0000000..b64af09 --- /dev/null +++ b/clients/media-preload-client/media_preload_client/types.py @@ -0,0 +1,54 @@ +"""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 `httpx.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 httpx 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/clients/media-preload-client/pyproject.toml b/clients/media-preload-client/pyproject.toml new file mode 100644 index 0000000..a5f8e5e --- /dev/null +++ b/clients/media-preload-client/pyproject.toml @@ -0,0 +1,25 @@ +[project] +name = "media-preload-client" +version = "1.0.0" +description = "A client library for accessing media-preload" +authors = [] +requires-python = ">=3.11" +readme = "README.md" +dependencies = [ + "httpx>=0.23.1,<0.29.0", + "attrs>=22.2.0", +] + +[tool.uv.build-backend] +module-name = "media_preload_client" +module-root = "" + +[build-system] +requires = ["uv_build>=0.12.0,<0.13.0"] +build-backend = "uv_build" + +[tool.ruff] +line-length = 120 + +[tool.ruff.lint] +select = ["F", "I", "UP"] diff --git a/clients/media-preload.openapi.json b/clients/media-preload.openapi.json new file mode 100644 index 0000000..ce0613e --- /dev/null +++ b/clients/media-preload.openapi.json @@ -0,0 +1,647 @@ +{ + "components": { + "responses": { + "Problem": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Error" + } + }, + "schemas": { + "AgentJob": { + "properties": { + "fileId": { + "format": "int64", + "type": "integer" + }, + "path": { + "type": "string" + }, + "sizeBytes": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "fileId", + "path", + "sizeBytes" + ], + "type": "object" + }, + "ClaimRequest": { + "properties": { + "agentId": { + "example": "vps-dcruit2r", + "type": "string" + } + }, + "required": [ + "agentId" + ], + "type": "object" + }, + "CreateRequest": { + "properties": { + "episodes": { + "description": "Episode numbers within `season`", + "items": { + "minimum": 0, + "type": "integer" + }, + "type": "array" + }, + "itemId": { + "description": "Jellyfin item id from /v1/search", + "type": "string" + }, + "jellyfinUser": { + "description": "Jellyfin user name whose watch progress decides \"next\"", + "type": "string" + }, + "next": { + "description": "Next N unwatched episodes for jellyfinUser", + "maximum": 20, + "minimum": 1, + "type": "integer" + }, + "note": { + "maxLength": 500, + "type": "string" + }, + "requestedBy": { + "description": "Who asked", + "e.g. a Discord user name": null, + "maxLength": 100, + "type": "string" + }, + "season": { + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "itemId", + "requestedBy" + ], + "type": "object" + }, + "FileReport": { + "properties": { + "bytes": { + "description": "Bytes read from home for this file", + "format": "int64", + "type": "integer" + }, + "error": { + "type": "string" + }, + "result": { + "enum": [ + "cached", + "already_cached", + "failed" + ], + "type": "string" + } + }, + "required": [ + "result" + ], + "type": "object" + }, + "FileStatus": { + "enum": [ + "queued", + "fetching", + "cached", + "failed", + "canceled", + "not_cacheable" + ], + "type": "string" + }, + "Health": { + "properties": { + "status": { + "example": "ok", + "type": "string" + }, + "version": { + "type": "string" + } + }, + "required": [ + "status", + "version" + ], + "type": "object" + }, + "MediaItem": { + "properties": { + "cacheable": { + "description": "False when the item lives outside the cached folders", + "type": "boolean" + }, + "id": { + "description": "Jellyfin item id", + "type": "string" + }, + "library": { + "description": "Jellyfin library path prefix, e.g. /media2/Videos/tvshows", + "type": "string" + }, + "name": { + "type": "string" + }, + "seasonCount": { + "type": "integer" + }, + "type": { + "$ref": "#/components/schemas/MediaType" + }, + "year": { + "type": "integer" + } + }, + "required": [ + "id", + "name", + "type", + "cacheable" + ], + "type": "object" + }, + "MediaType": { + "enum": [ + "movie", + "series" + ], + "type": "string" + }, + "PreloadFile": { + "properties": { + "error": { + "type": "string" + }, + "fetchedBytes": { + "format": "int64", + "type": "integer" + }, + "id": { + "format": "int64", + "type": "integer" + }, + "path": { + "description": "Path as seen by Jellyfin and webdav, e.g. /media2/Videos/tvshows/...", + "type": "string" + }, + "sizeBytes": { + "format": "int64", + "type": "integer" + }, + "status": { + "$ref": "#/components/schemas/FileStatus" + }, + "title": { + "description": "e.g. Dark Matter S02E08", + "type": "string" + }, + "updatedAt": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "id", + "path", + "title", + "status", + "sizeBytes" + ], + "type": "object" + }, + "PreloadRequest": { + "properties": { + "createdAt": { + "format": "date-time", + "type": "string" + }, + "files": { + "items": { + "$ref": "#/components/schemas/PreloadFile" + }, + "type": "array" + }, + "id": { + "format": "int64", + "type": "integer" + }, + "itemId": { + "type": "string" + }, + "note": { + "type": "string" + }, + "requestedBy": { + "type": "string" + }, + "status": { + "$ref": "#/components/schemas/RequestStatus" + }, + "title": { + "type": "string" + } + }, + "required": [ + "id", + "itemId", + "title", + "requestedBy", + "status", + "createdAt", + "files" + ], + "type": "object" + }, + "Problem": { + "properties": { + "error": { + "example": "series requests need jellyfinUser when using next", + "type": "string" + } + }, + "required": [ + "error" + ], + "type": "object" + }, + "RequestStatus": { + "enum": [ + "queued", + "fetching", + "done", + "partial", + "failed", + "canceled" + ], + "type": "string" + } + }, + "securitySchemes": { + "bearerAuth": { + "scheme": "bearer", + "type": "http" + } + } + }, + "info": { + "description": "Warm the VPS media cache (webdav.godemperordoge.org) before someone watches something.\n\nA client (for example the Discord bot) searches the Jellyfin library and files a request\n(\"I will watch Dark Matter season 2\"). The API resolves it to media files and queues them.\nThe preload agent on the VPS claims queued files and reads them through the local rclone\ncache, so they stream from the VPS instead of over the home uplink.\n\nOnly Movies (including Arabic Shows) and the two TV libraries are cacheable; other files are\nreported as `not_cacheable`.\n\nAuth: `Authorization: Bearer <token>`. Client tokens may use the search and request endpoints;\nagent tokens may only use `/v1/agent/*`.\n", + "title": "media-preload", + "version": "1.0.0" + }, + "openapi": "3.0.3", + "paths": { + "/v1/agent/claim": { + "post": { + "operationId": "ClaimFile", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ClaimRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentJob" + } + } + }, + "description": "A file to fetch" + }, + "204": { + "description": "Nothing queued" + }, + "401": { + "$ref": "#/components/responses/Problem" + }, + "403": { + "$ref": "#/components/responses/Problem" + } + }, + "summary": "Agent takes the next queued file", + "tags": [ + "agent" + ] + } + }, + "/v1/agent/files/{fileId}": { + "parameters": [ + { + "in": "path", + "name": "fileId", + "required": true, + "schema": { + "format": "int64", + "type": "integer" + } + } + ], + "post": { + "operationId": "ReportFile", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FileReport" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "Recorded" + }, + "401": { + "$ref": "#/components/responses/Problem" + }, + "403": { + "$ref": "#/components/responses/Problem" + }, + "404": { + "$ref": "#/components/responses/Problem" + } + }, + "summary": "Agent reports the result for a claimed file", + "tags": [ + "agent" + ] + } + }, + "/v1/health": { + "get": { + "operationId": "GetHealth", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + }, + "description": "OK" + } + }, + "security": [], + "summary": "Liveness and version" + } + }, + "/v1/requests": { + "get": { + "operationId": "ListRequests", + "parameters": [ + { + "in": "query", + "name": "status", + "schema": { + "$ref": "#/components/schemas/RequestStatus" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "default": 20, + "maximum": 100, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/PreloadRequest" + }, + "type": "array" + } + } + }, + "description": "OK" + }, + "401": { + "$ref": "#/components/responses/Problem" + } + }, + "summary": "Recent requests, newest first", + "tags": [ + "requests" + ] + }, + "post": { + "description": "For a movie, `season`, `episodes` and `next` are ignored.\nFor a series, give exactly one of:\n- `season` (whole season), optionally with `episodes` (those episode numbers of that season);\n- `next` (the next N unwatched episodes for `jellyfinUser`).\nWith none of them, a series defaults to `next: 3` and then needs `jellyfinUser`.\n", + "operationId": "CreateRequest", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PreloadRequest" + } + } + }, + "description": "Queued (files already cached are marked `cached` right away by the agent)" + }, + "400": { + "$ref": "#/components/responses/Problem" + }, + "401": { + "$ref": "#/components/responses/Problem" + }, + "404": { + "$ref": "#/components/responses/Problem" + } + }, + "summary": "Ask for a movie or episodes to be cached", + "tags": [ + "requests" + ] + } + }, + "/v1/requests/{id}": { + "delete": { + "operationId": "CancelRequest", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PreloadRequest" + } + } + }, + "description": "Canceled (files already fetched stay cached)" + }, + "401": { + "$ref": "#/components/responses/Problem" + }, + "404": { + "$ref": "#/components/responses/Problem" + } + }, + "summary": "Cancel the files of a request that are still queued", + "tags": [ + "requests" + ] + }, + "get": { + "operationId": "GetRequest", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PreloadRequest" + } + } + }, + "description": "OK" + }, + "401": { + "$ref": "#/components/responses/Problem" + }, + "404": { + "$ref": "#/components/responses/Problem" + } + }, + "summary": "One request with per-file progress", + "tags": [ + "requests" + ] + }, + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "int64", + "type": "integer" + } + } + ] + }, + "/v1/search": { + "get": { + "operationId": "SearchLibrary", + "parameters": [ + { + "description": "Title to search for", + "in": "query", + "name": "q", + "required": true, + "schema": { + "minLength": 2, + "type": "string" + } + }, + { + "in": "query", + "name": "type", + "schema": { + "$ref": "#/components/schemas/MediaType" + } + }, + { + "in": "query", + "name": "limit", + "schema": { + "default": 10, + "maximum": 25, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/MediaItem" + }, + "type": "array" + } + } + }, + "description": "Matches, best first" + }, + "400": { + "$ref": "#/components/responses/Problem" + }, + "401": { + "$ref": "#/components/responses/Problem" + } + }, + "summary": "Search movies and series in Jellyfin", + "tags": [ + "library" + ] + } + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "servers": [ + { + "description": "on yveltal", + "url": "http://127.0.0.1:8125" + }, + { + "description": "from the VPS, over the wg-home tunnel", + "url": "http://10.77.0.2:8125" + } + ], + "tags": [ + { + "name": "library" + }, + { + "name": "requests" + }, + { + "name": "agent" + } + ] +} diff --git a/clients/openapi-python-client.yaml b/clients/openapi-python-client.yaml new file mode 100644 index 0000000..c67d57b --- /dev/null +++ b/clients/openapi-python-client.yaml @@ -0,0 +1,6 @@ +# Settings for generating clients/media-preload-client (see README) +project_name_override: media-preload-client +package_name_override: media_preload_client +post_hooks: + - "ruff check . --fix-only --select I,F401 --quiet" + - "ruff format . --quiet" diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..8d43f05 --- /dev/null +++ b/mise.toml @@ -0,0 +1,32 @@ +# Dev tools and tasks. Python and its dependencies are managed by uv. +# Lint and type checks cover the watch cog; doge_alignment predates them. +[tools] +uv = "0.13" + +[tasks.sync] +run = "uv sync" + +[tasks.fmt] +run = ["uv run ruff format watch tests", "uv run ruff check --fix watch tests"] + +[tasks.lint] +run = ["uv run ruff format --check watch tests", "uv run ruff check watch tests"] + +[tasks.typecheck] +run = "uv run ty check" + +[tasks.test] +run = "uv run pytest" + +[tasks.check] +depends = ["lint", "typecheck", "test"] + +[tasks.generate-client] +description = "Regenerate clients/media-preload-client from the live media-preload spec" +run = """ +curl -fsS http://10.0.0.38:8125/openapi.json | jq . > clients/media-preload.openapi.json +uvx --from openapi-python-client==0.29.1 --with ruff openapi-python-client generate \ + --path clients/media-preload.openapi.json --config clients/openapi-python-client.yaml \ + --meta uv --output-path clients/media-preload-client --overwrite +rm -rf clients/media-preload-client/.ruff_cache +""" diff --git a/pyproject.toml b/pyproject.toml index ce4d1d7..a3783a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,6 +15,29 @@ dependencies = [ ] +[dependency-groups] +dev = [ + "media-preload-client", + # Red's pytest plugin imports pip + "pip", + "pytest>=8", + "pytest-asyncio>=0.24", + "ruff>=0.17", + "ty>=0.0.97", +] + +[tool.uv.sources] +media-preload-client = { path = "clients/media-preload-client", editable = true } + +[tool.pytest.ini_options] +testpaths = ["tests"] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" + +[tool.ty.src] +# The watch cog and its tests; doge_alignment predates the type checking +include = ["watch", "tests"] + [build-system] requires = ["uv_build>=0.7.13,<0.8"] build-backend = "uv_build" @@ -53,8 +76,8 @@ exclude = [ line-length = 80 indent-width = 8 -# Assume Python 3.13 -target-version = "py313" +# Red 3.5 runs on Python 3.11 +target-version = "py311" [tool.ruff.lint] # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default. @@ -110,6 +133,9 @@ unfixable = [] # Allow unused variables when underscore-prefixed. dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["S101"] + [tool.ruff.format] # Like Black, use double quotes for strings. quote-style = "double" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..72afd58 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,6 @@ +"""Import the watch cog's modules the way Red does.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) diff --git a/tests/test_watch_spec.py b/tests/test_watch_spec.py new file mode 100644 index 0000000..d5c5cdb --- /dev/null +++ b/tests/test_watch_spec.py @@ -0,0 +1,184 @@ +"""Parsing what to watch, and describing preload progress.""" + +from datetime import UTC, datetime + +import pytest +from media_preload_client.models import ( + FileStatus, + PreloadFile, + PreloadRequest, + RequestStatus, +) + +from watch.spec import ( + EpisodeSpec, + SpecError, + bar, + compact_ranges, + describe, + human_size, + is_finished, + parse_episodes, + parse_season, + progress, + split_query, +) + + +@pytest.mark.parametrize( + ("query", "title", "spec"), + [ + ("The Matrix", "The Matrix", None), + ( + "Dark Matter s2e8-10", + "Dark Matter", + EpisodeSpec(2, (8, 9, 10)), + ), + ("Dark Matter S2E8", "Dark Matter", EpisodeSpec(2, (8,))), + ( + "Dark Matter s2 e8-e10", + "Dark Matter", + EpisodeSpec(2, (8, 9, 10)), + ), + ( + "Dark Matter s2e1,3,5", + "Dark Matter", + EpisodeSpec(2, (1, 3, 5)), + ), + ("Dark Matter s2", "Dark Matter", EpisodeSpec(season=2)), + ("Dark Matter season 2", "Dark Matter", EpisodeSpec(season=2)), + ("Dark Matter next", "Dark Matter", EpisodeSpec(next=3)), + ("Dark Matter NEXT 5", "Dark Matter", EpisodeSpec(next=5)), + (" Frieren s1e3 ", "Frieren", EpisodeSpec(1, (3,))), + # Titles that merely contain the words stay titles + ("Next Friday", "Next Friday", None), + ("Seasons", "Seasons", None), + ], +) +def test_split_query(query: str, title: str, spec: EpisodeSpec | None) -> None: + """The title and the episode spec are split apart.""" + assert split_query(query) == (title, spec) + + +@pytest.mark.parametrize( + "query", + ["Show s2e10-8", "Show s0", "Show s0e1", "Show s1e0", "Show next 99"], +) +def test_bad_specs_are_rejected(query: str) -> None: + """Backwards ranges, season or episode 0, and huge "next" are errors.""" + with pytest.raises(SpecError): + split_query(query) + + +def test_parse_episodes_merges_and_sorts() -> None: + """Overlapping ranges collapse into one sorted list.""" + assert parse_episodes("10, 8-9, 9") == (8, 9, 10) + + +def test_parse_episodes_limits_size() -> None: + """A single request can't ask for more than 50 episodes.""" + with pytest.raises(SpecError): + parse_episodes("1-51") + + +def test_parse_season() -> None: + """Seasons are positive numbers.""" + assert parse_season(" 3 ") == 3 + for bad in ("0", "x", ""): + with pytest.raises(SpecError): + parse_season(bad) + + +def test_describe_spec() -> None: + """Specs read naturally in messages.""" + assert EpisodeSpec(2, (8, 9, 10, 12)).describe() == "S2 E8-10,12" + assert EpisodeSpec(season=2).describe() == "all of season 2" + assert EpisodeSpec(next=3).describe() == "the next 3 unwatched episodes" + + +def test_compact_ranges() -> None: + """Runs of episodes become ranges.""" + assert compact_ranges((1, 2, 3, 5, 7, 8)) == "1-3,5,7-8" + assert compact_ranges(()) == "" + + +@pytest.mark.parametrize( + ("size", "text"), + [(0, "0 B"), (999, "999 B"), (1500, "1.5 KB"), (844_000_000, "844 MB")], +) +def test_human_size(size: int, text: str) -> None: + """Sizes use decimal units like the rest of the home lab.""" + assert human_size(size) == text + + +def test_bar() -> None: + """Bars fill proportionally and handle empty totals.""" + assert bar(1, 2, width=4) == "▓▓░░ 50%" + assert bar(0, 0, width=4) == "▓▓▓▓ 100%" + + +def make_request(status: RequestStatus) -> PreloadRequest: + """Dark Matter S2E8-10 as homelab's end-to-end test left it.""" + files = [ + PreloadFile( + id=1, + path="/media2/Videos/tvshows/Dark Matter/S02E08.mkv", + title="Dark Matter S02E08", + status=FileStatus.CACHED, + size_bytes=800_000_000, + ), + PreloadFile( + id=2, + path="/media2/Videos/tvshows/Dark Matter/S02E10.mkv", + title="Dark Matter S02E10", + status=FileStatus.FETCHING, + size_bytes=844_000_000, + fetched_bytes=422_000_000, + ), + PreloadFile( + id=3, + path="/media/elsewhere.mkv", + title="Elsewhere", + status=FileStatus.NOT_CACHEABLE, + size_bytes=5, + ), + ] + return PreloadRequest( + id=7, + item_id="abc", + title="Dark Matter", + requested_by="discord:doge", + status=status, + created_at=datetime(2026, 11, 5, tzinfo=UTC), + files=files, + ) + + +def test_progress_ignores_uncacheable_files() -> None: + """Totals count cached and fetching files only.""" + assert progress(make_request(RequestStatus.FETCHING)) == ( + 1_222_000_000, + 1_644_000_000, + ) + + +def test_describe_request() -> None: + """Each file gets a line, plus an overall bar.""" + text = describe(make_request(RequestStatus.FETCHING)) + assert "✅ Dark Matter S02E08 — 800 MB" in text + assert "⬇️ Dark Matter S02E10 — ▓▓▓▓░░░░ 50%" in text + assert "🚫 Elsewhere" in text + assert text.endswith("74% · 1.2 GB of 1.6 GB") + + +def test_describe_truncates_long_requests() -> None: + """Long seasons don't overflow the embed.""" + request = make_request(RequestStatus.QUEUED) + request.files = request.files[:1] * 20 + assert "…and 5 more" in describe(request) + + +def test_is_finished() -> None: + """Polling stops once nothing will change.""" + assert not is_finished(make_request(RequestStatus.FETCHING)) + assert is_finished(make_request(RequestStatus.PARTIAL)) diff --git a/uv.lock b/uv.lock index 30e72de..493abc1 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 2 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.13'", @@ -75,6 +75,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/76/ac/a7305707cb852b7e16ff80eaf5692309bde30e2b1100a1fcacdc8f731d97/aiosignal-1.3.1-py3-none-any.whl", hash = "sha256:f8376fb07dd1e86a584e4fcdec80b36b7f81aac666ebc724e2c090300dd83b17", size = 7617, upload-time = "2022-11-08T16:03:57.483Z" }, ] +[[package]] +name = "anyio" +version = "4.14.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, +] + [[package]] name = "apsw" version = "3.46.1.0" @@ -250,6 +263,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/c1/ec214e9c94000d1c1974ec67ced1c970c148aa6b8d8373066123fc3dbf06/Brotli-1.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:9011560a466d2eb3f5a6e4929cf4a09be405c64154e12df0dd72713f6500e32b", size = 358517, upload-time = "2024-10-18T12:32:54.066Z" }, ] +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + [[package]] name = "cffi" version = "1.17.1" @@ -361,6 +383,16 @@ dependencies = [ { name = "wand" }, ] +[package.dev-dependencies] +dev = [ + { name = "media-preload-client" }, + { name = "pip" }, + { name = "pytest" }, + { name = "pytest-asyncio" }, + { name = "ruff" }, + { name = "ty" }, +] + [package.metadata] requires-dist = [ { name = "discord", specifier = ">=2.3.2" }, @@ -369,6 +401,16 @@ requires-dist = [ { name = "wand", specifier = ">=0.6.13" }, ] +[package.metadata.requires-dev] +dev = [ + { name = "media-preload-client", editable = "clients/media-preload-client" }, + { name = "pip" }, + { name = "pytest", specifier = ">=8" }, + { name = "pytest-asyncio", specifier = ">=0.24" }, + { name = "ruff", specifier = ">=0.17" }, + { name = "ty", specifier = ">=0.0.97" }, +] + [[package]] name = "frozenlist" version = "1.5.0" @@ -423,6 +465,43 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c6/c8/a5be5b7550c10858fcf9b0ea054baccab474da77d37f1e828ce043a3a5d4/frozenlist-1.5.0-py3-none-any.whl", hash = "sha256:d994863bba198a4a518b467bb971c56e1db3f180a25c6cf7bb1949c267f748c3", size = 11901, upload-time = "2024-10-23T09:48:28.851Z" }, ] +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + [[package]] name = "idna" version = "3.10" @@ -444,6 +523,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/d9/a1e041c5e7caa9a05c925f4bdbdfb7f006d1f74996af53467bc394c97be7/importlib_metadata-8.5.0-py3-none-any.whl", hash = "sha256:45e54197d28b7a7f1559e60b95e7c567032b602131fbd588f1497f47880aa68b", size = 26514, upload-time = "2024-09-11T14:56:07.019Z" }, ] +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + [[package]] name = "markdown" version = "3.7" @@ -474,6 +562,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] +[[package]] +name = "media-preload-client" +version = "1.0.0" +source = { editable = "clients/media-preload-client" } +dependencies = [ + { name = "attrs" }, + { name = "httpx" }, +] + +[package.metadata] +requires-dist = [ + { name = "attrs", specifier = ">=22.2.0" }, + { name = "httpx", specifier = ">=0.23.1,<0.29.0" }, +] + [[package]] name = "multidict" version = "6.1.0" @@ -584,6 +687,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469, upload-time = "2025-04-19T11:48:57.875Z" }, ] +[[package]] +name = "pip" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/53/c7/f8d9e2e0e7c1ed8a22a10eeb3b5bf7860bc07d8446c7a978a882c5c8214b/pip-26.3.tar.gz", hash = "sha256:6c36ae7da8695be67e3cd9f7d87919667ced53f57ce2ede75d89b5912ed2bc4c", size = 1934348, upload-time = "2026-11-02T20:34:27.738Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/25/ee8c38ae72d66b844ce8eb9711ba905dba21ca1a8a0c960057c41cd23337/pip-26.3-py3-none-any.whl", hash = "sha256:f3b60b20ffaadd4415ed7957212a38ac63fa4c5fa375bd0f4a797777940fad13", size = 1950951, upload-time = "2026-11-02T20:34:25.728Z" }, +] + [[package]] name = "platformdirs" version = "4.3.6" @@ -593,6 +705,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3c/a6/bc1012356d8ece4d66dd75c4b9fc6c1f6650ddd5991e421177d9f8f671be/platformdirs-4.3.6-py3-none-any.whl", hash = "sha256:73e575e1408ab8103900836b97580d5307456908a03e92031bab39e4554cc3fb", size = 18439, upload-time = "2024-09-17T19:06:49.212Z" }, ] +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + [[package]] name = "propcache" version = "0.2.0" @@ -683,6 +804,35 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/0b/9fcc47d19c48b59121088dd6da2488a49d5f72dacf8262e2790a1d2c7d15/pygments-2.19.1-py3-none-any.whl", hash = "sha256:9ea1544ad55cecf4b8242fab6dd35a93bbce657034b0611ee383099054ab6d8c", size = 1225293, upload-time = "2025-01-06T17:26:25.553Z" }, ] +[[package]] +name = "pytest" +version = "9.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, +] + +[[package]] +name = "pytest-asyncio" +version = "1.4.1.post1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/7f/c60a4338420b33453d4f814ac0c930abd399f162b9bdd21af4b9e363037f/pytest_asyncio-1.4.1.post1.tar.gz", hash = "sha256:f582d9ea4a1c082195abe8bd29a1fe106aeb1cd435e3dad2d3bc2749935c36a2", size = 145360, upload-time = "2026-11-01T18:26:03.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/de/adbc7578959cfab07e5e7c05cf6d54224a51e7667ea2c07458b6bc571e75/pytest_asyncio-1.4.1.post1-py3-none-any.whl", hash = "sha256:0755e488cc0a2b9bd2eab7292cc6390d4cbb8390f1020745647bae5a708e0165", size = 17140, upload-time = "2026-11-01T18:26:02.168Z" }, +] + [[package]] name = "python-dateutil" version = "2.9.0.post0" @@ -868,6 +1018,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0d/9b/63f4c7ebc259242c89b3acafdb37b41d1185c07ff0011164674e9076b491/rich-14.0.0-py3-none-any.whl", hash = "sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0", size = 243229, upload-time = "2025-03-30T14:15:12.283Z" }, ] +[[package]] +name = "ruff" +version = "0.17.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/59/73/81f140c4edd9cc323de5478e6bbd3bbcfae9a82692df1a258de8cec6a6d2/ruff-0.17.3.tar.gz", hash = "sha256:a57049c8addb3662073859bb55a7ad35aa54f8a7c9ed268911d1333c5aadaaa9", size = 5339444, upload-time = "2026-10-27T00:34:05.914Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/8c/083365310c4e79c842f25bf5a842facbd9b0c0ec336f96dffa5074fe723d/ruff-0.17.3-py3-none-linux_armv6l.whl", hash = "sha256:ab86b84cd9d05e56d329742c0cabdcbe2d1d56c98f4a04aab9b5b66196febfb4", size = 10216522, upload-time = "2026-10-27T00:33:29.822Z" }, + { url = "https://files.pythonhosted.org/packages/72/26/4b2edf31cfebe9605d8f6ed8f1d6f376d3a53d4c9a123e62661c64c440f0/ruff-0.17.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e407b4a6852853a9a2cdce96963e94ad9775578bb44e7561a0f2829f3cc04b11", size = 10217786, upload-time = "2026-10-27T00:33:33.949Z" }, + { url = "https://files.pythonhosted.org/packages/a2/7e/537aba4b7f54397a374d2f6a6fc93e9c8015e18553f31a4a7b7dbced48b5/ruff-0.17.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b75cc113b3aca388933d8296b667b1ac401a80317ea3074c9b0a66541199da29", size = 9440362, upload-time = "2026-10-27T00:33:35.784Z" }, + { url = "https://files.pythonhosted.org/packages/3d/66/283e39734f66c8a5ebaa93c22eb7b7515779a0b1d5a5c0ad20e05c0edb41/ruff-0.17.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab5fa7ed5ce18554ea69d850ad162cbaa0c85fc47c08d83a569f806681c9a6ad", size = 10094281, upload-time = "2026-10-27T00:33:38.216Z" }, + { url = "https://files.pythonhosted.org/packages/21/4c/1ffc768497bd025a32c72152771e40c0b99bddc5cc6e4f50c7949a395346/ruff-0.17.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c673c170e27834d1262e3a9c1e97bdc9b9c3b180c63d89173ce69747232474c1", size = 10022543, upload-time = "2026-10-27T00:33:40.181Z" }, + { url = "https://files.pythonhosted.org/packages/73/c3/f90db547301080fcb82c92abf914c8bd57b89911d9b65a6c4cc6b52d0635/ruff-0.17.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a754c0341bc9ca151b7b335988b3263921c08859f84ca219b70cee825571b6f", size = 10683921, upload-time = "2026-10-27T00:33:42.182Z" }, + { url = "https://files.pythonhosted.org/packages/e5/98/92d4a8a26c6c96cf1a5b34dd59036d8a71e52d650aab065c58867e964e63/ruff-0.17.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4590b9d86c0b1543ebb09094254e191cd43fe8edaf330baa035aab03da251532", size = 11373408, upload-time = "2026-10-27T00:33:44.19Z" }, + { url = "https://files.pythonhosted.org/packages/43/02/1f24d2e3064c9753926deeb901afa57777b37ee46799b09ddd7aee6e5145/ruff-0.17.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bbde18beccd98c29a227c63c99022e3443b99258e08326df6425dfe0443705ef", size = 10977469, upload-time = "2026-10-27T00:33:46.179Z" }, + { url = "https://files.pythonhosted.org/packages/f0/20/fecedea2209f574ab92033b344e01a7f0c2dc76c6d6d19a14c9f8141173f/ruff-0.17.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7fa4b0f931cdbcb8a52044f370a3eb429fb42eb88807b0e800fcaa98dd42b24e", size = 10577491, upload-time = "2026-10-27T00:33:48.233Z" }, + { url = "https://files.pythonhosted.org/packages/33/36/b93fdf0bc6f84f0cd487aadfb0354deb40013669ea35ac3d26855de1e959/ruff-0.17.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:39405f341deec934b4289634324ad695f72df2970f9121582872eaf5b722f0f5", size = 10608748, upload-time = "2026-10-27T00:33:50.284Z" }, + { url = "https://files.pythonhosted.org/packages/5d/b7/7d3f5f14145daead1efb0b9a8289ed1daa100f419d60774375951723ce00/ruff-0.17.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:68074094f55ca3d29ab19491f640282f7a84061c4c7977aa5094b968ca457e9a", size = 10075057, upload-time = "2026-10-27T00:33:52.074Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ed/93ff7a5909ee56e2bd4b982deae9e0efb2724417874a90c9e41ad66c6dd7/ruff-0.17.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:27bb571ac78fef178fe5118d2827df95c2aae74a48fff2b15f6acd03af5ff5bb", size = 10022431, upload-time = "2026-10-27T00:33:54.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/07/a83b9eeec8c1c3c0e4eda15f06c3a91001bfd2687ea2f07b750719bf9712/ruff-0.17.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:029c37cbd3de48ca37aa12117bead2d065f15da17d66bf84e0d4274013705db2", size = 10394903, upload-time = "2026-10-27T00:33:56.158Z" }, + { url = "https://files.pythonhosted.org/packages/af/b2/05c39857c2526fcbebe46ad93a8dc97424656dfef14d3ef933abe1ffd331/ruff-0.17.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:692fdb46d0fd9c71e380947dc5fc72f2c3f881073bc1f739e4579376231affbe", size = 10799780, upload-time = "2026-10-27T00:33:58.204Z" }, + { url = "https://files.pythonhosted.org/packages/ec/d9/47171a16739eb7a353936b31c20cf54340531e68c9af7d72fd7a784e235d/ruff-0.17.3-py3-none-win32.whl", hash = "sha256:46539cb031b01fd29ae0a02142483c46640b233ee12bb1c1b690bffa1555d5ca", size = 9908481, upload-time = "2026-10-27T00:34:00.087Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a0/f08c1631bfd81faa6a90eaf70c37c786c11bed2046302b56bb506c25e1a0/ruff-0.17.3-py3-none-win_amd64.whl", hash = "sha256:56b8ffb3f3b3cbccb8b76b71b38261b7ed982ef5d20f5b447b1b61a7f4949b24", size = 10341333, upload-time = "2026-10-27T00:34:02.099Z" }, + { url = "https://files.pythonhosted.org/packages/99/d5/4ad4ed31413c301430918e70d3d38ae6f097af0766cb9ab8c9d502b2a4d6/ruff-0.17.3-py3-none-win_arm64.whl", hash = "sha256:81fce74bcd6be0e9da7c67c7553fd0f1f12964a2052cd728ef917b937a5ca1d9", size = 9854332, upload-time = "2026-10-27T00:34:03.847Z" }, +] + [[package]] name = "schema" version = "0.7.7" @@ -886,6 +1061,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] +[[package]] +name = "ty" +version = "0.0.97" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cf/57/d0cabbc33e6e04c0406b9771ef3a05b13f34c3c22e69c3696ab5431dc28b/ty-0.0.97.tar.gz", hash = "sha256:5346478c114ca9aece58b4df94e41cc17f373177f0795d15db8e95a8d1edae0f", size = 8152797, upload-time = "2026-11-04T09:15:44.47Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/47/73bbd93b7d580be6a751b069aa75bc5dd008c3180ffc1747f8914b301fd4/ty-0.0.97-py3-none-linux_armv6l.whl", hash = "sha256:6ebc145803a0e3a1d3087cadae35e2003dc795914ff0048131286e62d517f461", size = 14657644, upload-time = "2026-11-04T09:14:49.574Z" }, + { url = "https://files.pythonhosted.org/packages/54/4f/40ca071c4ac093cf2e124612bd4adba97af85de89fe6c1599710a23d63a1/ty-0.0.97-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:76a094299aef30130570d3c01f0ea7a13e2036a15db9a35be2cbc050f2a73d02", size = 14219229, upload-time = "2026-11-04T09:14:52.944Z" }, + { url = "https://files.pythonhosted.org/packages/18/57/8c0d346fe872ee2813b3afa34b93d5e5e8a2f9c39db9f8be32351d2d08c5/ty-0.0.97-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6a5c9414303fe3bb461c174c59a70881c48934c1983a36e109aa2b18b5f3bea5", size = 13274833, upload-time = "2026-11-04T09:14:55.963Z" }, + { url = "https://files.pythonhosted.org/packages/e7/74/76c3d6236acef0ca7f1a57fb8923bac098eba629e9f93bd34427a510e191/ty-0.0.97-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65ac762c4ad4abffe085b91795488b9780befea14d9c4ceaa18a02d0bd5fde11", size = 14120577, upload-time = "2026-11-04T09:14:59.274Z" }, + { url = "https://files.pythonhosted.org/packages/c5/e2/12a2f226a9faa718c569da0074a31ef8c28722b49d1e89ea8df22f74f6e7/ty-0.0.97-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eeecb6128caf6a2e64c62f1e5484b61dd30608e870f726615be7f3d643a45467", size = 14385457, upload-time = "2026-11-04T09:15:02.173Z" }, + { url = "https://files.pythonhosted.org/packages/78/36/8f2dd9b5ab9466d26211cfd6e74b808f37b8bac171beb490f431e916c03f/ty-0.0.97-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:91284ae3799c44bcde4c7cdae6b4574ede196b1adeaff8f4dba23888a76fa50f", size = 15354810, upload-time = "2026-11-04T09:15:05.714Z" }, + { url = "https://files.pythonhosted.org/packages/0a/e1/9b19f32aa6345d0feece2201323b8d8db6cb716d544ff61fbbdcfc2fefb6/ty-0.0.97-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:11878ffe50115e2c7725e8e4d30c6ec827ee97bbd92b8b9a7fcd54d49fa07235", size = 15784826, upload-time = "2026-11-04T09:15:08.879Z" }, + { url = "https://files.pythonhosted.org/packages/3d/95/e79cc647ce1d7ba6140401c76c0298be2b24335c2650c6e90d0950c2e8ce/ty-0.0.97-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d197c4a5d273cc3cb7a81c2e54d9e911f1d841b3e8abe2bfcb6185884c02af87", size = 15714807, upload-time = "2026-11-04T09:15:12.1Z" }, + { url = "https://files.pythonhosted.org/packages/db/6d/b432bebff5dba0883c40e66a19f3ac40ac268defb87f4b641b371c989624/ty-0.0.97-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4750e490b285d9083cc49588bbbecd1b5e02476dca882e127586cd289b4d92df", size = 16589366, upload-time = "2026-11-04T09:15:15.426Z" }, + { url = "https://files.pythonhosted.org/packages/c3/8c/3abaa79ccc327ff1f5480ccac145a09529f475a43c1c1b2bae9d26cfffc5/ty-0.0.97-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:5b8cba6a04c3a5d9380977ad3789328a23630cfd1f89f56b06c819c42ebfed65", size = 15242399, upload-time = "2026-11-04T09:15:18.748Z" }, + { url = "https://files.pythonhosted.org/packages/8a/22/1d9e8ed559484a92422514a17d8c95a944aa32d91d45176659fa6fc2f528/ty-0.0.97-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:042a28b8d3d0ebd86b8c20c09544a4623c8408dcaf40fce5d73c72c2956db34f", size = 14101542, upload-time = "2026-11-04T09:15:21.877Z" }, + { url = "https://files.pythonhosted.org/packages/88/b0/6be00fd0ff3cdb6e8ade36837390ae2d3b06a662424ec231ffabf9df8811/ty-0.0.97-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:37815bde7e9344fa91533bdf09960c065278a7f3a33cf3aa642b394f67f2d115", size = 14392166, upload-time = "2026-11-04T09:15:25.235Z" }, + { url = "https://files.pythonhosted.org/packages/0d/a0/9b245e691b6df38903e2b782f87bf86a5dd258e700e663414a7585515d9f/ty-0.0.97-py3-none-musllinux_1_2_i686.whl", hash = "sha256:b36092f9249ec53efc42972ef35039a3e28042ea0b5abc8ce174668d5b4f8c8e", size = 14759162, upload-time = "2026-11-04T09:15:28.366Z" }, + { url = "https://files.pythonhosted.org/packages/cf/81/b6e8fb597019e50702ad2d3d25017910f83321471e9b1c13c46f5666bdf1/ty-0.0.97-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:5428aab4930abe9527f6cd66f2bbbd009291c463eb256c895e23857dc5a930ea", size = 15104202, upload-time = "2026-11-04T09:15:31.993Z" }, + { url = "https://files.pythonhosted.org/packages/eb/bc/be5c37bac8b99853e68ea5f11536231ffa988f63cb6785288cf6d5d87368/ty-0.0.97-py3-none-win32.whl", hash = "sha256:8e2aa95973b1be330db33c46b10ba02d92e35930b70d06200c1f06512af6824a", size = 13560323, upload-time = "2026-11-04T09:15:35.258Z" }, + { url = "https://files.pythonhosted.org/packages/b6/47/5d9b908dbc4a2addb984c3d58f008db75dd9c7cd04f0a7d92530779c1bd5/ty-0.0.97-py3-none-win_amd64.whl", hash = "sha256:69deddd2d1c4fbb2cae902a8c0d7c7ed67113659edcfd59ab5b6e4a2a02081ee", size = 14184823, upload-time = "2026-11-04T09:15:38.335Z" }, + { url = "https://files.pythonhosted.org/packages/24/50/f0e0e2f137bd1b3539809a248b552002cd0b8b00ed36114acb9ca72eca8c/ty-0.0.97-py3-none-win_arm64.whl", hash = "sha256:88ec7fd1a91d70ed43fab52e326b375129c44c6b64d6c289825fb4561bc80253", size = 13685279, upload-time = "2026-11-04T09:15:41.961Z" }, +] + [[package]] name = "typing-extensions" version = "4.13.2" diff --git a/watch/__init__.py b/watch/__init__.py new file mode 100644 index 0000000..fe86106 --- /dev/null +++ b/watch/__init__.py @@ -0,0 +1,15 @@ +"""Red cog: preload movies and episodes into the media cache.""" + +from redbot.core.bot import Red + +from .watch import Watch + +__red_end_user_data_statement__ = ( + "This cog stores the Jellyfin user name you link with `watch link`, " + "to find your next unwatched episodes. `watch unlink` deletes it." +) + + +async def setup(bot: Red) -> None: + """Red's entry point.""" + await bot.add_cog(Watch(bot)) diff --git a/watch/info.json b/watch/info.json new file mode 100644 index 0000000..3410196 --- /dev/null +++ b/watch/info.json @@ -0,0 +1,15 @@ +{ + "author": ["GodEmperorDoge"], + "name": "Watch", + "short": "Preload a movie or episodes so they stream fast.", + "description": "Ask the home lab's media-preload service to cache a movie, a season, some episodes, or your next unwatched episodes, and follow the download in the channel.", + "install_msg": "Set the API token with the PRELOAD_BOT_TOKEN environment variable or `[p]set api media_preload token,<token>` (and url,<url> if it isn't http://host.containers.internal:8125).", + "end_user_data_statement": "This cog stores the Jellyfin user name you link with `watch link`, to find your next unwatched episodes. `watch unlink` deletes it.", + "requirements": [ + "media-preload-client @ git+https://github.com/RustyRaptor/doge_cogs.git#subdirectory=clients/media-preload-client" + ], + "min_bot_version": "3.5.0", + "min_python_version": [3, 11, 0], + "tags": ["media", "jellyfin", "webdav"], + "type": "COG" +} diff --git a/watch/spec.py b/watch/spec.py new file mode 100644 index 0000000..86416ab --- /dev/null +++ b/watch/spec.py @@ -0,0 +1,228 @@ +"""Parse what a user wants to watch and describe a preload's progress. + +Kept apart from the Discord code so it can be tested without a bot. +""" + +import re +from dataclasses import dataclass + +from media_preload_client.models import ( + FileStatus, + PreloadFile, + PreloadRequest, + RequestStatus, +) +from media_preload_client.types import Unset + +MAX_EPISODES = 50 +DEFAULT_NEXT = 3 + +FINISHED = frozenset( + { + RequestStatus.DONE, + RequestStatus.PARTIAL, + RequestStatus.FAILED, + RequestStatus.CANCELED, + } +) + +FILE_ICONS: dict[FileStatus, str] = { + FileStatus.QUEUED: "⏳", + FileStatus.FETCHING: "⬇️", + FileStatus.CACHED: "✅", + FileStatus.FAILED: "❌", + FileStatus.CANCELED: "⏹️", + FileStatus.NOT_CACHEABLE: "🚫", +} + + +class SpecError(ValueError): + """The episode part of a request can't be understood.""" + + +@dataclass(frozen=True) +class EpisodeSpec: + """Which episodes of a series to preload. + + Exactly one form is used: a whole ``season``, some ``episodes`` of a + season, or the ``next`` N unwatched episodes. + """ + + season: int | None = None + episodes: tuple[int, ...] = () + next: int | None = None + + def describe(self) -> str: + """Return a short human description, e.g. ``S2 E8-10``.""" + if self.next is not None: + return f"the next {self.next} unwatched episodes" + if not self.episodes: + return f"all of season {self.season}" + return f"S{self.season} E{compact_ranges(self.episodes)}" + + +# Trailing episode specs, tried in order against the end of the query +_SEASON_EPISODES = re.compile( + r"\s+s(?:eason\s*)?(\d{1,2})\s*e(?:p(?:isodes?)?\s*)?" + r"(\d{1,3}(?:\s*-\s*e?\d{1,3})?(?:\s*,\s*\d{1,3}(?:\s*-\s*\d{1,3})?)*)$", + re.IGNORECASE, +) +_SEASON = re.compile(r"\s+s(?:eason\s*)?(\d{1,2})$", re.IGNORECASE) +_NEXT = re.compile(r"\s+next(?:\s+(\d{1,2}))?$", re.IGNORECASE) + + +def parse_episodes(text: str) -> tuple[int, ...]: + """Turn ``"8-10,12"`` into ``(8, 9, 10, 12)``. + + Raises: + SpecError: for backwards ranges, episode 0 or too many episodes. + + """ + numbers: set[int] = set() + for part in text.replace(" ", "").lower().replace("e", "").split(","): + if "-" in part: + start_text, end_text = part.split("-", 1) + start, end = int(start_text), int(end_text) + if end < start: + msg = f"episode range {part} goes backwards" + raise SpecError(msg) + numbers.update(range(start, end + 1)) + else: + numbers.add(int(part)) + if 0 in numbers: + msg = "episodes start at 1" + raise SpecError(msg) + if len(numbers) > MAX_EPISODES: + msg = f"that's more than {MAX_EPISODES} episodes" + raise SpecError(msg) + return tuple(sorted(numbers)) + + +def parse_season(text: str) -> int: + """Return the season number in ``text``. + + Raises: + SpecError: if it isn't a number from 1 up. + + """ + try: + season = int(text.strip()) + except ValueError: + msg = f"{text!r} isn't a season number" + raise SpecError(msg) from None + if season < 1: + msg = "seasons start at 1" + raise SpecError(msg) + return season + + +def split_query(text: str) -> tuple[str, EpisodeSpec | None]: + """Split ``"Dark Matter s2e8-10"`` into a title and an episode spec. + + Understands ``s2``, ``season 2``, ``s2e8``, ``s2e8-10``, ``s2e1,3,5`` + and ``next`` or ``next 5`` at the end of the query. + + Raises: + SpecError: if the spec is malformed. + + """ + text = " ".join(text.split()) + padded = f" {text}" + if match := _SEASON_EPISODES.search(padded): + season = int(match.group(1)) + spec = EpisodeSpec(season, parse_episodes(match.group(2))) + elif match := _SEASON.search(padded): + spec = EpisodeSpec(season=int(match.group(1))) + elif match := _NEXT.search(padded): + count = int(match.group(1) or DEFAULT_NEXT) + if not 1 <= count <= MAX_EPISODES: + msg = f"next takes 1 to {MAX_EPISODES} episodes" + raise SpecError(msg) + spec = EpisodeSpec(next=count) + else: + return text, None + if spec.season == 0: + msg = "seasons start at 1" + raise SpecError(msg) + return padded[: match.start()].strip(), spec + + +def compact_ranges(numbers: tuple[int, ...]) -> str: + """Turn ``(8, 9, 10, 12)`` back into ``"8-10,12"``.""" + nums = sorted(set(numbers)) + parts: list[str] = [] + i = 0 + while i < len(nums): + j = i + while j + 1 < len(nums) and nums[j + 1] == nums[j] + 1: + j += 1 + parts.append(str(nums[i]) if i == j else f"{nums[i]}-{nums[j]}") + i = j + 1 + return ",".join(parts) + + +def human_size(size: int) -> str: + """Return ``size`` bytes as e.g. ``844 MB`` or ``1.2 GB``.""" + value = float(size) + unit = "B" + for unit in ("B", "KB", "MB", "GB", "TB"): + if value < 1000 or unit == "TB": + break + value /= 1000 + if unit == "B" or value >= 100: + return f"{value:.0f} {unit}" + return f"{value:.1f} {unit}" + + +def _fetched(file: PreloadFile) -> int: + if file.status == FileStatus.CACHED: + return file.size_bytes + fetched = file.fetched_bytes + return 0 if isinstance(fetched, Unset) else fetched + + +def progress(request: PreloadRequest) -> tuple[int, int]: + """Return (bytes fetched, bytes total) over the cacheable files.""" + files = [ + f + for f in request.files + if f.status + not in (FileStatus.NOT_CACHEABLE, FileStatus.CANCELED) + ] + return sum(_fetched(f) for f in files), sum(f.size_bytes for f in files) + + +def bar(done: int, total: int, width: int = 16) -> str: + """Return a text progress bar such as ``▓▓▓▓░░░░ 50%``.""" + fraction = 1.0 if total <= 0 else min(done / total, 1.0) + filled = round(fraction * width) + return f"{'▓' * filled}{'░' * (width - filled)} {fraction:.0%}" + + +def file_line(file: PreloadFile) -> str: + """Return one line describing a file's state.""" + icon = FILE_ICONS.get(file.status, "•") + line = f"{icon} {file.title}" + if file.status == FileStatus.FETCHING: + line += f" — {bar(_fetched(file), file.size_bytes, width=8)}" + elif file.status == FileStatus.CACHED: + line += f" — {human_size(file.size_bytes)}" + elif file.status == FileStatus.FAILED and isinstance(file.error, str): + line += f" — {file.error[:80]}" + return line + + +def describe(request: PreloadRequest, max_files: int = 15) -> str: + """Return the progress text shown in Discord for ``request``.""" + lines = [file_line(f) for f in request.files[:max_files]] + if len(request.files) > max_files: + lines.append(f"…and {len(request.files) - max_files} more") + done, total = progress(request) + sizes = f"{human_size(done)} of {human_size(total)}" + lines += ["", f"{bar(done, total)} · {sizes}"] + return "\n".join(lines) + + +def is_finished(request: PreloadRequest) -> bool: + """Whether the request will not change any more.""" + return request.status in FINISHED diff --git a/watch/watch.py b/watch/watch.py new file mode 100644 index 0000000..9c29bf6 --- /dev/null +++ b/watch/watch.py @@ -0,0 +1,620 @@ +"""``d!watch``: preload a movie or episodes into the media cache. + +Talks to media-preload (the home lab's preload service) through the +generated ``media_preload_client``. Files are fetched into the VPS media +cache so they stream quickly from webdav. +""" + +import asyncio +import contextlib +import logging +import os +from typing import Any, Literal + +import discord +import httpx +from media_preload_client import AuthenticatedClient +from media_preload_client.api.library import search_library +from media_preload_client.api.requests import ( + cancel_request, + create_request, + get_request, + list_requests, +) +from media_preload_client.models import ( + CreateRequest, + MediaItem, + MediaType, + PreloadRequest, + Problem, +) +from media_preload_client.types import UNSET, Response +from redbot.core import Config, commands +from redbot.core.bot import Red + +from .spec import ( + DEFAULT_NEXT, + EpisodeSpec, + SpecError, + describe, + is_finished, + parse_episodes, + parse_season, + split_query, +) + +log = logging.getLogger("red.doge_cogs.watch") + +# Inside a rootless podman network the host's LAN address is the container +# itself; podman maps host.containers.internal to the host. +DEFAULT_URL = "http://host.containers.internal:8125" +POLL_SECONDS = 10 +POLL_LIMIT_SECONDS = 3 * 3600 +VIEW_TIMEOUT = 120 + +# Who can run a command: a server member, or a user in DMs +Person = discord.User | discord.Member + +RequestType = Literal["discord_deleted_user", "owner", "user", "user_strict"] + + +class PreloadError(Exception): + """media-preload refused or failed a call.""" + + +def _unwrap(response: Response[Any]) -> Any: # noqa: ANN401 (generated types) + """Return a response's model, or raise with the API's error message.""" + if isinstance(response.parsed, Problem): + raise PreloadError(response.parsed.error) + if response.status_code >= 400 or response.parsed is None: # noqa: PLR2004 + msg = f"media-preload answered HTTP {response.status_code}" + raise PreloadError(msg) + return response.parsed + + +async def _timed_out(prompt: discord.Message) -> None: + """Replace an expired prompt's buttons with a note.""" + with contextlib.suppress(discord.HTTPException): + await prompt.edit(content="Never mind, timed out.", view=None) + + +def item_label(item: MediaItem) -> str: + """Return e.g. ``Dark Matter (2024) · series``.""" + year = f" ({item.year})" if isinstance(item.year, int) else "" + return f"{item.name}{year} · {item.type_.value}" + + +class OwnerView(discord.ui.View): + """A view that only the user who ran the command can use.""" + + def __init__(self, author: Person) -> None: + """Lock the view to ``author``.""" + super().__init__(timeout=VIEW_TIMEOUT) + self.author = author + + async def interaction_check( + self, interaction: discord.Interaction + ) -> bool: + """Refuse clicks from anyone else.""" + if interaction.user.id == self.author.id: + return True + await interaction.response.send_message( + "This isn't your request.", ephemeral=True + ) + return False + + +class ItemSelect(discord.ui.Select["PickItem"]): + """The select menu inside :class:`PickItem`.""" + + def __init__(self, items: list[MediaItem]) -> None: + """List up to 25 ``items``.""" + super().__init__( + placeholder="Which one?", + options=[ + discord.SelectOption( + label=item_label(item)[:100], + value=item.id, + ) + for item in items[:25] + ], + ) + + async def callback(self, interaction: discord.Interaction) -> None: + """Hand the choice to the view.""" + if self.view is not None: + await self.view.picked(interaction, self.values[0]) + + +class PickItem(OwnerView): + """Choose one search result.""" + + def __init__(self, author: Person, items: list[MediaItem]) -> None: + """Offer ``items`` in a select menu.""" + super().__init__(author) + self.items = {item.id: item for item in items} + self.chosen: MediaItem | None = None + self.add_item(ItemSelect(items)) + + async def picked( + self, interaction: discord.Interaction, item_id: str + ) -> None: + """Record the chosen item and close the view.""" + self.chosen = self.items[item_id] + await interaction.response.edit_message( + content=f"Picked **{item_label(self.chosen)}**.", + view=None, + ) + self.stop() + + +class EpisodesModal(discord.ui.Modal, title="Which episodes?"): + """Ask for a season and, optionally, episode numbers.""" + + season: "discord.ui.TextInput[EpisodesModal]" = discord.ui.TextInput( + label="Season", placeholder="2", max_length=2 + ) + episodes: "discord.ui.TextInput[EpisodesModal]" = discord.ui.TextInput( + label="Episodes (empty for the whole season)", + placeholder="8-10, 12", + required=False, + max_length=60, + ) + + def __init__(self, view: "PickEpisodes") -> None: + """Report the answer back to ``view``.""" + super().__init__(timeout=VIEW_TIMEOUT) + self.view = view + + async def on_submit(self, interaction: discord.Interaction) -> None: + """Validate the answer and hand it to the view.""" + try: + season = parse_season(self.season.value) + episodes = ( + parse_episodes(self.episodes.value) + if self.episodes.value.strip() + else () + ) + except (ValueError, SpecError) as exc: + await interaction.response.send_message( + f"That didn't work: {exc}", ephemeral=True + ) + return + await self.view.finish( + interaction, EpisodeSpec(season, episodes) + ) + + +class PickEpisodes(OwnerView): + """Choose the next unwatched episodes or a season/episodes.""" + + def __init__( + self, + author: Person, + jellyfin_user: str | None, + ) -> None: + """Offer "next" only when a Jellyfin user is linked.""" + super().__init__(author) + self.spec: EpisodeSpec | None = None + if jellyfin_user is None: + self.next_button.disabled = True + self.next_button.label = "Next 3 (link first)" + + async def finish( + self, interaction: discord.Interaction, spec: EpisodeSpec + ) -> None: + """Record ``spec`` and close the view.""" + self.spec = spec + await interaction.response.edit_message( + content=f"Preloading {spec.describe()}…", view=None + ) + self.stop() + + @discord.ui.button( + label=f"Next {DEFAULT_NEXT} unwatched", + style=discord.ButtonStyle.primary, + ) + async def next_button( + self, + interaction: discord.Interaction, + _button: discord.ui.Button["PickEpisodes"], + ) -> None: + """Preload the next unwatched episodes.""" + await self.finish(interaction, EpisodeSpec(next=DEFAULT_NEXT)) + + @discord.ui.button(label="Season / episodes…") + async def season_button( + self, + interaction: discord.Interaction, + _button: discord.ui.Button["PickEpisodes"], + ) -> None: + """Ask for a season and episodes.""" + await interaction.response.send_modal(EpisodesModal(self)) + + +class CancelView(discord.ui.View): + """A cancel button under a progress message.""" + + def __init__( + self, cog: "Watch", request_id: int, owner_id: int + ) -> None: + """Cancel ``request_id``; allowed for its requester and mods.""" + super().__init__(timeout=None) + self.cog = cog + self.request_id = request_id + self.owner_id = owner_id + + @discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger) + async def cancel( + self, + interaction: discord.Interaction, + _button: discord.ui.Button["CancelView"], + ) -> None: + """Cancel the files that are still queued.""" + user = interaction.user + allowed = user.id == self.owner_id or ( + isinstance(user, discord.Member) + and user.guild_permissions.manage_messages + ) + if not allowed: + await interaction.response.send_message( + "Only the requester or a moderator can cancel.", + ephemeral=True, + ) + return + try: + await self.cog.cancel(self.request_id) + except (PreloadError, httpx.HTTPError) as exc: + await interaction.response.send_message( + f"Couldn't cancel: {exc}", ephemeral=True + ) + return + await interaction.response.send_message( + "Canceled the files that hadn't started.", + ephemeral=True, + ) + + +class Watch(commands.Cog): + """Preload movies and episodes so they stream quickly from webdav.""" + + def __init__(self, bot: Red) -> None: + """Create the cog.""" + self.bot = bot + self.config = Config.get_conf( + self, identifier=0x0D06EBA7C4, force_registration=True + ) + self.config.register_user(jellyfin_user=None) + self._pollers: set[asyncio.Task[None]] = set() + + async def cog_unload(self) -> None: + """Stop polling.""" + for task in self._pollers: + task.cancel() + + async def red_delete_data_for_user( + self, *, requester: RequestType, user_id: int + ) -> None: + """Forget a user's linked Jellyfin name.""" + del requester + await self.config.user_from_id(user_id).clear() + + async def _client(self) -> AuthenticatedClient: + tokens = await self.bot.get_shared_api_tokens("media_preload") + token = os.environ.get("PRELOAD_BOT_TOKEN") or tokens.get( + "token" + ) + if not token: + msg = ( + "no media-preload token: set PRELOAD_BOT_TOKEN " + "or `[p]set api media_preload token,...`" + ) + raise PreloadError(msg) + url = ( + os.environ.get("PRELOAD_API_URL") + or tokens.get("url") + or DEFAULT_URL + ) + return AuthenticatedClient( + base_url=url, + token=token, + timeout=httpx.Timeout(30.0), + ) + + async def search( + self, query: str, *, series_only: bool + ) -> list[MediaItem]: + """Search the library; cacheable items first.""" + client = await self._client() + async with client as c: + items = _unwrap( + await search_library.asyncio_detailed( + client=c, + q=query, + type_=MediaType.SERIES + if series_only + else UNSET, + limit=10, + ) + ) + return sorted(items, key=lambda i: not i.cacheable) + + async def create( + self, + item: MediaItem, + spec: EpisodeSpec | None, + requester: Person, + jellyfin_user: str | None, + ) -> PreloadRequest: + """Ask media-preload to cache ``item``.""" + body = CreateRequest( + item_id=item.id, + requested_by=f"discord:{requester.name}", + ) + if item.type_ == MediaType.SERIES and spec is not None: + if spec.next is not None: + body.next_ = spec.next + else: + body.season = spec.season or UNSET + if spec.episodes: + body.episodes = list(spec.episodes) + if jellyfin_user: + body.jellyfin_user = jellyfin_user + client = await self._client() + async with client as c: + return _unwrap( + await create_request.asyncio_detailed( + client=c, body=body + ) + ) + + async def fetch(self, request_id: int) -> PreloadRequest: + """Return a request with per-file progress.""" + client = await self._client() + async with client as c: + return _unwrap( + await get_request.asyncio_detailed( + request_id, client=c + ) + ) + + async def cancel(self, request_id: int) -> PreloadRequest: + """Cancel the files of a request that are still queued.""" + client = await self._client() + async with client as c: + return _unwrap( + await cancel_request.asyncio_detailed( + request_id, client=c + ) + ) + + def _embed(self, request: PreloadRequest) -> discord.Embed: + colour = ( + discord.Colour.green() + if request.status.value == "done" + else discord.Colour.blurple() + if not is_finished(request) + else discord.Colour.orange() + ) + embed = discord.Embed( + title=f"Preloading {request.title}", + description=describe(request), + colour=colour, + ) + embed.set_footer( + text=f"Request #{request.id} · {request.status.value}" + ) + return embed + + async def _follow( + self, + message: discord.Message, + request: PreloadRequest, + ) -> None: + """Edit ``message`` with progress until the request finishes.""" + waited = 0 + while not is_finished(request) and waited < POLL_LIMIT_SECONDS: + await asyncio.sleep(POLL_SECONDS) + waited += POLL_SECONDS + try: + request = await self.fetch(request.id) + except (PreloadError, httpx.HTTPError): + log.warning( + "Polling request %s failed", + request.id, + exc_info=True, + ) + continue + with contextlib.suppress(discord.HTTPException): + await message.edit(embed=self._embed(request)) + with contextlib.suppress(discord.HTTPException): + await message.edit( + embed=self._embed(request), view=None + ) + + async def _start( + self, + ctx: commands.Context, + item: MediaItem, + spec: EpisodeSpec | None, + ) -> None: + jellyfin_user = await self.config.user( + ctx.author + ).jellyfin_user() + try: + request = await self.create( + item, spec, ctx.author, jellyfin_user + ) + except (PreloadError, httpx.HTTPError) as exc: + await ctx.send(f"Couldn't start that: {exc}") + return + message = await ctx.send( + embed=self._embed(request), + view=None + if is_finished(request) + else CancelView(self, request.id, ctx.author.id), + ) + task = asyncio.create_task(self._follow(message, request)) + self._pollers.add(task) + task.add_done_callback(self._pollers.discard) + + async def _pick_item( + self, ctx: commands.Context, items: list[MediaItem], title: str + ) -> MediaItem | None: + exact = [i for i in items if i.name.lower() == title.lower()] + if len(items) == 1 or len(exact) == 1: + return exact[0] if exact else items[0] + view = PickItem(ctx.author, items) + prompt = await ctx.send( + f"I found {len(items)} matches for **{title}**:", + view=view, + ) + if await view.wait(): + await _timed_out(prompt) + return None + return view.chosen + + @commands.guild_only() + @commands.cooldown(1, 15, commands.BucketType.user) + @commands.group(name="watch", invoke_without_command=True) + async def watch(self, ctx: commands.Context, *, query: str) -> None: + """Preload something you're about to watch. + + Examples: + - `[p]watch The Matrix` + - `[p]watch Dark Matter s2e8-10` (episodes 8 to 10 of season 2) + - `[p]watch Dark Matter s2` (all of season 2) + - `[p]watch Dark Matter next 4` (your next 4 unwatched) + + For a series without episodes, you get buttons to choose. + "next" needs `[p]watch link <jellyfin name>` first. + + """ + try: + title, spec = split_query(query) + except SpecError as exc: + await ctx.send(f"I didn't get the episodes: {exc}") + return + if len(title) < 2: # noqa: PLR2004 (the API's minimum) + await ctx.send("Give me a title to look for.") + return + async with ctx.typing(): + try: + items = await self.search( + title, series_only=spec is not None + ) + except (PreloadError, httpx.HTTPError) as exc: + await ctx.send(f"Search failed: {exc}") + return + cacheable = [i for i in items if i.cacheable] + if not cacheable: + await ctx.send( + f"Nothing cacheable matches **{title}**." + if items + else f"I couldn't find **{title}**." + ) + return + item = await self._pick_item(ctx, cacheable, title) + if item is None: + return + jellyfin_user = await self.config.user( + ctx.author + ).jellyfin_user() + if ( + spec is not None + and spec.next is not None + and not jellyfin_user + ): + await ctx.send( + "For **next**, tell me your Jellyfin name with " + f"`{ctx.clean_prefix}watch link <name>`." + ) + return + if item.type_ == MediaType.SERIES and spec is None: + view = PickEpisodes(ctx.author, jellyfin_user) + prompt = await ctx.send( + f"Which episodes of **{item.name}**?", view=view + ) + if await view.wait() or view.spec is None: + await _timed_out(prompt) + return + spec = view.spec + await self._start(ctx, item, spec) + + @watch.command(name="link") + async def watch_link(self, ctx: commands.Context, *, name: str) -> None: + """Link your Jellyfin user name, for "next" requests.""" + await self.config.user(ctx.author).jellyfin_user.set( + name.strip() + ) + await ctx.send( + f"Linked to Jellyfin user **{name.strip()}**. " + f"`{ctx.clean_prefix}watch <show> next` now uses your " + "watch progress." + ) + + @watch.command(name="unlink") + async def watch_unlink(self, ctx: commands.Context) -> None: + """Forget your Jellyfin user name.""" + await self.config.user(ctx.author).jellyfin_user.clear() + await ctx.send("Unlinked.") + + @watch.command(name="status") + async def watch_status( + self, ctx: commands.Context, request_id: int | None = None + ) -> None: + """Show one request, or the latest few.""" + try: + if request_id is not None: + request = await self.fetch(request_id) + await ctx.send(embed=self._embed(request)) + return + client = await self._client() + async with client as c: + requests = _unwrap( + await list_requests.asyncio_detailed( + client=c, limit=5 + ) + ) + except (PreloadError, httpx.HTTPError) as exc: + await ctx.send(f"Couldn't get that: {exc}") + return + if not requests: + await ctx.send("No preloads yet.") + return + lines = [ + f"`#{r.id}` **{r.title}** · {r.status.value} · " + f"{r.requested_by}" + for r in requests + ] + await ctx.send("\n".join(lines)) + + @watch.command(name="cancel") + async def watch_cancel( + self, ctx: commands.Context, request_id: int + ) -> None: + """Cancel the queued files of a request.""" + try: + request = await self.fetch(request_id) + mine = ( + request.requested_by + == f"discord:{ctx.author.name}" + ) + is_mod = isinstance( + ctx.author, discord.Member + ) and await self.bot.is_mod(ctx.author) + if not ( + mine + or is_mod + or await self.bot.is_owner(ctx.author) + ): + await ctx.send( + "Only the requester or a moderator can " + "cancel that." + ) + return + request = await self.cancel(request_id) + except (PreloadError, httpx.HTTPError) as exc: + await ctx.send(f"Couldn't cancel: {exc}") + return + await ctx.send(embed=self._embed(request))