diff --git a/CHANGELOG.md b/CHANGELOG.md index caf0e50..cece1c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Changed +- **Whisparr v2 + Eros now use the shared *Arr HTTP client** — `arr_request()` in `whisparr/api.py` and `eros/api.py` now delegate to `src/primary/utils/arr_client.py` (signatures unchanged). This completes the shared-client migration for all six *Arr apps. The User-Agent sent to Whisparr/Eros is now built from the running version (`version.txt`) instead of the hardcoded `Seekarr/7.0.0`, and both gain the shared client's detailed HTTP/JSON error logging (status code + response snippet). (#101) - **Lidarr + Readarr now use the shared *Arr HTTP client** — `arr_request()` in `lidarr/api.py` and `readarr/api.py` now delegate to `src/primary/utils/arr_client.py` (signatures unchanged; Readarr keeps its settings/instance-credential fallback as a thin wrapper). The User-Agent sent to Lidarr/Readarr is now built from the running version (`version.txt`) instead of the hardcoded `Seekarr/7.0.0`, and both gain the shared client's detailed JSON/HTTP error logging. Lidarr's defensive `True` return for non-JSON 2xx responses is replaced by `{}` (stricter-safe: a bare `True` would crash `.get()` consumers; Lidarr always returns JSON in practice). (#100) - **Sonarr + Radarr now use the shared *Arr HTTP client** — `arr_request()` in `sonarr/api.py` and `radarr/api.py` are now thin wrappers delegating to `src/primary/utils/arr_client.py` (signatures unchanged). The User-Agent they send is now built from the running version (`version.txt`) instead of the hardcoded `Seekarr/7.0.0`, and Radarr requests now include the URL-scheme validation the other apps already had. Sonarr's three paginated fetch functions (documented `session` exceptions) now also use the shared User-Agent source. (#99) diff --git a/src/primary/apps/eros/api.py b/src/primary/apps/eros/api.py index 983caaa..dc1a763 100644 --- a/src/primary/apps/eros/api.py +++ b/src/primary/apps/eros/api.py @@ -6,17 +6,16 @@ Uses the /api/v3/ endpoint path. Internal config key is 'eros'. """ -import requests -import json from typing import List, Dict, Any, Optional from src.primary.utils.logger import get_logger from src.primary.settings_manager import get_ssl_verify_setting +import src.primary.utils.arr_client as arr_client # Get logger for the Eros app eros_logger = get_logger("eros") -# Use a session for better performance -session = requests.Session() +# Shared session (re-exported so callers/tests can keep using eros_api.session) +session = arr_client.session def arr_request(api_url: str, api_key: str, api_timeout: int, endpoint: str, method: str = "GET", data: Dict = None, params: Dict = None) -> Any: """ @@ -34,69 +33,17 @@ def arr_request(api_url: str, api_key: str, api_timeout: int, endpoint: str, met Returns: The parsed JSON response or None if the request failed """ - try: - if not api_url or not api_key: - eros_logger.error("No URL or API key provided") - return None - - if not (api_url.startswith('http://') or api_url.startswith('https://')): - eros_logger.error(f"Invalid URL format: {api_url} - URL must start with http:// or https://") - return None - - full_url = f"{api_url.rstrip('/')}/api/v3/{endpoint.lstrip('/')}" - - eros_logger.debug(f"Making {method} request to: {full_url}") - - headers = { - "X-Api-Key": api_key, - "Content-Type": "application/json", - "User-Agent": "Seekarr/7.0.0 (https://github.com/diybits/seekarr)" - } - - verify_ssl = get_ssl_verify_setting() - - if not verify_ssl: - eros_logger.debug("SSL verification disabled by user setting") - - try: - if method.upper() == "GET": - response = session.get(full_url, headers=headers, params=params, timeout=api_timeout, verify=verify_ssl) - elif method.upper() == "POST": - response = session.post(full_url, headers=headers, json=data, timeout=api_timeout, verify=verify_ssl) - elif method.upper() == "PUT": - response = session.put(full_url, headers=headers, json=data, timeout=api_timeout, verify=verify_ssl) - elif method.upper() == "DELETE": - response = session.delete(full_url, headers=headers, timeout=api_timeout, verify=verify_ssl) - else: - eros_logger.error(f"Unsupported HTTP method: {method}") - return None - - try: - response.raise_for_status() - except requests.exceptions.HTTPError as e: - eros_logger.error(f"Error during {method} request to {endpoint}: {e}, Status Code: {response.status_code}") - eros_logger.debug(f"Response content: {response.text[:200]}") - return None - - try: - if response.text: - result = response.json() - eros_logger.debug(f"Response from {response.url}: Status {response.status_code}, JSON parsed successfully") - return result - else: - eros_logger.debug(f"Response from {response.url}: Status {response.status_code}, Empty response") - return {} - except json.JSONDecodeError: - eros_logger.error(f"Invalid JSON response from API: {response.text[:200]}") - return None - - except requests.exceptions.RequestException as e: - eros_logger.error(f"Request failed: {e}") - return None - except Exception as e: - eros_logger.error(f"Unexpected error during API request: {e}") - return None - + # Delegated to the shared *Arr client (src/primary/utils/arr_client.py). + # Eros (Whisparr v3) serves its REST API under /api/v3/ + # (upstream Whisparr.Api.V3 controllers, movie-based wanted endpoints). + # get_ssl_verify_setting() is resolved here (app namespace) so existing + # test monkeypatches on this module keep working. + return arr_client.arr_request( + "eros", api_url, api_key, api_timeout, endpoint, + method=method, data=data, params=params, + api_prefix="v3", + ssl_verify=get_ssl_verify_setting(), + ) def get_download_queue_size(api_url: str, api_key: str, api_timeout: int) -> int: """ diff --git a/src/primary/apps/whisparr/api.py b/src/primary/apps/whisparr/api.py index a6779fc..342e1ff 100644 --- a/src/primary/apps/whisparr/api.py +++ b/src/primary/apps/whisparr/api.py @@ -7,17 +7,16 @@ version starts with '2' to confirm this is a v2 instance. """ -import requests -import json from typing import List, Dict, Any, Optional from src.primary.utils.logger import get_logger from src.primary.settings_manager import get_ssl_verify_setting +import src.primary.utils.arr_client as arr_client # Get logger for the Whisparr app whisparr_logger = get_logger("whisparr") -# Use a session for better performance -session = requests.Session() +# Shared session (re-exported so callers/tests can keep using whisparr_api.session) +session = arr_client.session def arr_request(api_url: str, api_key: str, api_timeout: int, endpoint: str, method: str = "GET", data: Dict = None, params: Dict = None) -> Any: """ @@ -34,75 +33,17 @@ def arr_request(api_url: str, api_key: str, api_timeout: int, endpoint: str, met Returns: The parsed JSON response or None if the request failed """ - try: - if not api_url or not api_key: - whisparr_logger.error("No URL or API key provided") - return None - - # Ensure api_url has a scheme - if not (api_url.startswith('http://') or api_url.startswith('https://')): - whisparr_logger.error(f"Invalid URL format: {api_url} - URL must start with http:// or https://") - return None - - # Whisparr v2 serves its REST API exclusively under /api/v3/ - # (upstream Whisparr.Api.V3 controllers), so that is the only path we use. - full_url = f"{api_url.rstrip('/')}/api/v3/{endpoint.lstrip('/')}" - - whisparr_logger.debug(f"Making {method} request to: {full_url}") - - # Set up headers with User-Agent to identify Seekarr - headers = { - "X-Api-Key": api_key, - "Content-Type": "application/json", - "User-Agent": "Seekarr/7.0.0 (https://github.com/diybits/seekarr)" - } - - # Get SSL verification setting - verify_ssl = get_ssl_verify_setting() - - if not verify_ssl: - whisparr_logger.debug("SSL verification disabled by user setting") - - try: - if method.upper() == "GET": - response = session.get(full_url, headers=headers, params=params, timeout=api_timeout, verify=verify_ssl) - elif method.upper() == "POST": - response = session.post(full_url, headers=headers, json=data, timeout=api_timeout, verify=verify_ssl) - elif method.upper() == "PUT": - response = session.put(full_url, headers=headers, json=data, timeout=api_timeout, verify=verify_ssl) - elif method.upper() == "DELETE": - response = session.delete(full_url, headers=headers, timeout=api_timeout, verify=verify_ssl) - else: - whisparr_logger.error(f"Unsupported HTTP method: {method}") - return None - - # Check if the request was successful - try: - response.raise_for_status() - except requests.exceptions.HTTPError as e: - whisparr_logger.error(f"Error during {method} request to {endpoint}: {e}, Status Code: {response.status_code}") - whisparr_logger.debug(f"Response content: {response.text[:200]}") - return None - - # Try to parse JSON response - try: - if response.text: - result = response.json() - whisparr_logger.debug(f"Response from {response.url}: Status {response.status_code}, JSON parsed successfully") - return result - else: - whisparr_logger.debug(f"Response from {response.url}: Status {response.status_code}, Empty response") - return {} - except json.JSONDecodeError: - whisparr_logger.error(f"Invalid JSON response from API: {response.text[:200]}") - return None - - except requests.exceptions.RequestException as e: - whisparr_logger.error(f"Request failed: {e}") - return None - except Exception as e: - whisparr_logger.error(f"Unexpected error during API request: {e}") - return None + # Delegated to the shared *Arr client (src/primary/utils/arr_client.py). + # Whisparr v2 serves its REST API exclusively under /api/v3/ + # (upstream Whisparr.Api.V3 controllers), so that is the only path we use. + # get_ssl_verify_setting() is resolved here (app namespace) so existing + # test monkeypatches on this module keep working. + return arr_client.arr_request( + "whisparr", api_url, api_key, api_timeout, endpoint, + method=method, data=data, params=params, + api_prefix="v3", + ssl_verify=get_ssl_verify_setting(), + ) def get_download_queue_size(api_url: str, api_key: str, api_timeout: int) -> int: """ diff --git a/tests/test_eros_api.py b/tests/test_eros_api.py index 217bdd4..386c8c1 100644 --- a/tests/test_eros_api.py +++ b/tests/test_eros_api.py @@ -294,3 +294,21 @@ def test_check_connection_returns_false_on_exception(monkeypatch): with patch.object(eros_api, "arr_request", side_effect=Exception("boom")): result = eros_api.check_connection("http://eros:6969", "key", 30) assert result is False + + +# ── Shared client delegation (T6d) ─────────────────────────────────────────── + +def test_session_is_shared_arr_client_session(): + import src.primary.utils.arr_client as arr_client + assert eros_api.session is arr_client.session + + +def test_arr_request_uses_shared_user_agent(monkeypatch): + import src.primary.utils.arr_client as arr_client + monkeypatch.setattr("src.primary.apps.eros.api.get_ssl_verify_setting", lambda: True) + captured = {} + with patch.object(eros_api.session, "get", side_effect=_capture_session_get({"version": "3.0.0.1234"}, captured)): + eros_api.arr_request("http://eros:9706", "key", 30, "system/status") + # UA comes from the shared version source (version.txt), not a hardcoded string + assert captured["headers"]["User-Agent"] == arr_client.get_user_agent() + assert "/api/v3/" in captured["url"] diff --git a/tests/test_whisparr_api.py b/tests/test_whisparr_api.py index c715ff4..2cb14d6 100644 --- a/tests/test_whisparr_api.py +++ b/tests/test_whisparr_api.py @@ -203,3 +203,21 @@ def test_check_connection_returns_false_for_unexpected_version(monkeypatch): with patch.object(whisparr_api.session, "get", side_effect=_capture_session_get({"version": "3.0.0"}, {})): result = whisparr_api.check_connection("http://whisparr:6969", "key", 30) assert result is False + + +# ── Shared client delegation (T6d) ─────────────────────────────────────────── + +def test_session_is_shared_arr_client_session(): + import src.primary.utils.arr_client as arr_client + assert whisparr_api.session is arr_client.session + + +def test_arr_request_uses_shared_user_agent(monkeypatch): + import src.primary.utils.arr_client as arr_client + monkeypatch.setattr("src.primary.apps.whisparr.api.get_ssl_verify_setting", lambda: True) + captured = {} + with patch.object(whisparr_api.session, "get", side_effect=_capture_session_get({"version": "2.0.0.0"}, captured)): + whisparr_api.arr_request("http://whisparr:6969", "key", 30, "system/status") + # UA comes from the shared version source (version.txt), not a hardcoded string + assert captured["headers"]["User-Agent"] == arr_client.get_user_agent() + assert "/api/v3/" in captured["url"]