forked from kenzuya/unshackle
fix(api): let a core failure name its own API error code
This commit is contained in:
@@ -166,15 +166,21 @@ service yields `INVALID_SERVICE`. These carry a precise code, message, and often
|
||||
populated `details` object.
|
||||
|
||||
**Categorised exceptions.** When an endpoint calls into a streaming service and an
|
||||
uncategorised exception bubbles up, the server runs it through a classifier that
|
||||
inspects the exception type and message and maps it to the most appropriate code.
|
||||
The classification is keyword-based, checked in order:
|
||||
exception that is not an `APIError` bubbles up, the server gives it a code in two steps:
|
||||
|
||||
1. **The code the failure names.** An unshackle core failure states its own code: a region
|
||||
check gives `GEOFENCE`, a proxy that fails gives `INVALID_PROXY`, a login that needs
|
||||
an absent user gives `AUTH_FAILED`, and a DRM failure gives `DRM_ERROR`. The server
|
||||
reads this code first, so the wording of the message does not change it.
|
||||
2. **The keywords of the message.** A failure that names no code, such as the plain text
|
||||
that a service raises, gets a code from the words in its message, checked in order:
|
||||
|
||||
| If the error mentions... | It becomes | Retryable |
|
||||
|---|---|---|
|
||||
| `geofence`, `geoblock`, `geo-block`, `geolocation`, `region`, `not available in`, `territory` | `GEOFENCE` (403) | no |
|
||||
| `proxy` | `INVALID_PROXY` (400) | no |
|
||||
| `auth`, `login`, `credential`, `unauthorized`, `forbidden`, `token` | `AUTH_FAILED` (401) | no |
|
||||
| `connection`, `timeout`, `network`, `unreachable`, `socket`, `dns`, `resolve` (or `ConnectionError`, `TimeoutError`, `URLError`, `SSLError`) | `NETWORK_ERROR` (424) | yes |
|
||||
| `geofence`, `geoblock`, `region`, `not available in`, `territory` | `GEOFENCE` (403) | no |
|
||||
| `not found`, `404`, `does not exist`, `invalid id` | `NOT_FOUND` (404) | no |
|
||||
| `rate limit`, `too many requests`, `429`, `throttle` | `RATE_LIMITED` (429) | yes |
|
||||
| `drm`, `license`, `widevine`, `playready`, `decrypt` | `DRM_ERROR` (422) | no |
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Each core raiser names its own API error code, so a reworded message keeps the code."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
import click
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core import service as service_mod
|
||||
from unshackle.core.api.errors import categorize_exception
|
||||
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
|
||||
from unshackle.core.drm import ClearKeyCENC, MonaLisa, PlayReady, Widevine, decrypters
|
||||
from unshackle.core.import_service import ImportService, manifest_fetch_error
|
||||
from unshackle.core.proxies.gluetun import Gluetun
|
||||
from unshackle.core.proxies.nordvpn import NordVPN
|
||||
from unshackle.core.proxies.resolve import Unavailable, find_provider, pick_proxy
|
||||
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.utils import ip_info, run_proxy
|
||||
|
||||
|
||||
def code_of(call: Callable[[], Any]) -> Optional[APIErrorCode]:
|
||||
"""The code the raised exception names itself, not the one its message would give."""
|
||||
with pytest.raises(BaseException) as caught:
|
||||
call()
|
||||
return getattr(caught.value, "error_code", None)
|
||||
|
||||
|
||||
def test_a_login_email_for_a_vpn_provider_is_a_proxy_error() -> None:
|
||||
assert code_of(lambda: NordVPN("user@example.com", "secret")) == APIErrorCode.INVALID_PROXY
|
||||
assert code_of(lambda: SurfsharkVPN("user@example.com", "secret")) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_gluetun_without_docker_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(binaries, "Docker", None)
|
||||
assert code_of(Gluetun) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_a_provider_that_failed_to_load_or_is_unknown_is_a_proxy_error() -> None:
|
||||
providers = [Unavailable("NordVPN", ValueError("bad credentials"))]
|
||||
assert code_of(lambda: find_provider(providers, "nordvpn")) == APIErrorCode.INVALID_PROXY
|
||||
assert code_of(lambda: find_provider(providers, "other")) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_a_query_no_provider_answers_is_a_proxy_error() -> None:
|
||||
assert code_of(lambda: pick_proxy([], "gb")) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxied, failures", [(None, 99), ({"ip": "1.1.1.1", "country": "gb"}, 0)])
|
||||
def test_a_failed_proxy_check_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch, proxied: Any, failures: int) -> None:
|
||||
def lookup(session: Any = None, cached: bool = False, errors: Any = None) -> Any:
|
||||
if errors is not None:
|
||||
errors.extend(OSError("refused") for _ in range(failures))
|
||||
return proxied if session is not None and not cached else {"ip": "1.1.1.1"}
|
||||
|
||||
monkeypatch.setattr(ip_info, "get_ip_info", lookup)
|
||||
assert code_of(lambda: ip_info.verify_proxy_exit(SimpleNamespace())) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
class Blocked(Service):
|
||||
GEOBLOCK = ("gb",)
|
||||
|
||||
def get_titles(self): # type: ignore[no-untyped-def]
|
||||
raise NotImplementedError
|
||||
|
||||
def get_tracks(self, title): # type: ignore[no-untyped-def]
|
||||
raise NotImplementedError
|
||||
|
||||
def get_chapters(self, title): # type: ignore[no-untyped-def]
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy", [None, "https://u:p@chosen.example:89"], ids=["own-region", "proxy-region"])
|
||||
def test_a_blocked_region_is_a_geofence_error(monkeypatch: pytest.MonkeyPatch, proxy: Optional[str]) -> None:
|
||||
monkeypatch.setattr(service_mod, "get_ip_info", lambda *args, **kwargs: {"country": "gb"})
|
||||
monkeypatch.setattr(service_mod, "verify_proxy_exit", lambda session: {"country": "gb"})
|
||||
monkeypatch.setattr(run_proxy, "watched", {})
|
||||
monkeypatch.setattr(run_proxy, "proxy_hosts", set())
|
||||
ctx = SimpleNamespace(
|
||||
obj=SimpleNamespace(config={}, proxy_providers=[]), parent=SimpleNamespace(params={"proxy": proxy})
|
||||
)
|
||||
assert code_of(lambda: Blocked(ctx)) == APIErrorCode.GEOFENCE # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_a_login_that_needs_an_absent_user_is_an_auth_error() -> None:
|
||||
assert code_of(lambda: NoUserBridge().request_input("Enter OTP")) == APIErrorCode.AUTH_FAILED
|
||||
assert code_of(NoUserBridge().ensure_active) == APIErrorCode.AUTH_FAILED
|
||||
assert code_of(lambda: InputBridge().request_input("Enter OTP", timeout=0.05)) == APIErrorCode.AUTH_FAILED
|
||||
|
||||
|
||||
def test_an_import_key_the_export_lacks_is_a_drm_error() -> None:
|
||||
assert ImportService.missing_key(SimpleNamespace(drm=None)).error_code == APIErrorCode.DRM_ERROR # type: ignore[arg-type,attr-defined]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
Widevine.Exceptions.PSSHNotFound,
|
||||
Widevine.Exceptions.KIDNotFound,
|
||||
PlayReady.Exceptions.PSSHNotFound,
|
||||
PlayReady.Exceptions.KIDNotFound,
|
||||
PlayReady.Exceptions.DeviceRevoked,
|
||||
ClearKeyCENC.Exceptions.KIDNotFound,
|
||||
MonaLisa.Exceptions.TicketNotFound,
|
||||
MonaLisa.Exceptions.KeyExtractionFailed,
|
||||
],
|
||||
)
|
||||
def test_a_drm_exception_class_is_a_drm_error(error: type[Exception]) -> None:
|
||||
assert categorize_exception(error("PSSH was not found in track data.")).error_code == APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
def test_a_missing_decrypter_is_a_drm_error(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(binaries, "Mp4decrypt", None)
|
||||
monkeypatch.setattr(binaries, "ShakaPackager", None)
|
||||
assert code_of(lambda: decrypters.mp4decrypt(Path("x.mp4"), lambda kids: [])) == APIErrorCode.DRM_ERROR
|
||||
assert code_of(lambda: decrypters.shaka_decrypt(Path("x.mp4"), "", "Widevine")) == APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
def http_failure(status: Any) -> requests.ConnectionError:
|
||||
return requests.ConnectionError("Failed to request the MPD document.", response=SimpleNamespace(status_code=status))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure, code",
|
||||
[
|
||||
(http_failure(404), APIErrorCode.NOT_FOUND),
|
||||
(http_failure(410), APIErrorCode.NOT_FOUND),
|
||||
(http_failure(429), APIErrorCode.RATE_LIMITED),
|
||||
(http_failure(503), APIErrorCode.SERVICE_UNAVAILABLE),
|
||||
(http_failure(403), None),
|
||||
(http_failure(SimpleNamespace()), None),
|
||||
(requests.ConnectionError("dns"), None),
|
||||
],
|
||||
ids=["404", "410", "429", "503", "403", "not-a-status", "no-answer"],
|
||||
)
|
||||
def test_a_manifest_fetch_failure_is_coded_from_an_unambiguous_status(
|
||||
failure: Exception, code: Optional[APIErrorCode]
|
||||
) -> None:
|
||||
error = manifest_fetch_error("DASH", "Example Movie", failure)
|
||||
assert isinstance(error, click.ClickException) and "may have expired" in error.message
|
||||
assert getattr(error, "error_code", None) == code
|
||||
|
||||
|
||||
def test_a_manifest_fetch_failure_names_the_http_status() -> None:
|
||||
assert "(HTTP 403)" in manifest_fetch_error("DASH", "Example Movie", http_failure(403)).message
|
||||
|
||||
|
||||
def test_a_manifest_status_behind_exhausted_retries_is_read_from_the_cause() -> None:
|
||||
exhausted = RuntimeError("Max retries exceeded")
|
||||
exhausted.__cause__ = http_failure(503)
|
||||
error = manifest_fetch_error("DASH", "Example Movie", exhausted)
|
||||
assert "(HTTP 503)" in error.message and getattr(error, "error_code", None) == APIErrorCode.SERVICE_UNAVAILABLE
|
||||
@@ -6,6 +6,7 @@ import pytest
|
||||
|
||||
from unshackle.core import console
|
||||
from unshackle.core.api.input_bridge import NO_USER_MESSAGE, InputBridge, NoUserBridge
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.service import Service
|
||||
|
||||
|
||||
@@ -19,8 +20,9 @@ def test_returns_the_first_value_check_gives():
|
||||
|
||||
|
||||
def test_times_out_when_check_never_gives_a_value():
|
||||
with pytest.raises(TimeoutError):
|
||||
with pytest.raises(TimeoutError) as caught:
|
||||
Service.wait_for_approval(_service(), "enter code", lambda: None, timeout=0.05, interval=0.01)
|
||||
assert caught.value.error_code is APIErrorCode.AUTH_FAILED
|
||||
|
||||
|
||||
def test_stops_when_the_remote_session_is_cancelled():
|
||||
@@ -58,7 +60,6 @@ def test_a_request_with_no_user_fails_at_once():
|
||||
|
||||
def test_no_user_message_is_an_authentication_error():
|
||||
from unshackle.core.api.errors import categorize_exception
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
assert categorize_exception(RuntimeError(NO_USER_MESSAGE)).error_code == APIErrorCode.AUTH_FAILED
|
||||
|
||||
|
||||
@@ -404,6 +404,7 @@ def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch:
|
||||
finally:
|
||||
set_prompt_handler(None)
|
||||
assert categorize_exception(exc_info.value).error_code is APIErrorCode.AUTH_FAILED
|
||||
assert exc_info.value.error_code is APIErrorCode.AUTH_FAILED # type: ignore[attr-defined]
|
||||
|
||||
|
||||
def test_concurrent_prompts_go_out_one_at_a_time(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api.errors import APIError, build_error_response, categorize_exception, handle_api_exception
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -225,3 +225,71 @@ def test_categorize_system_exit_is_a_service_error() -> None:
|
||||
err = categorize_exception(SystemExit(1), {"service": "EXAMPLE"})
|
||||
assert err.error_code == APIErrorCode.SERVICE_ERROR
|
||||
assert err.message == "Service EXAMPLE exited"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"code, message",
|
||||
[
|
||||
(APIErrorCode.GEOFENCE, "login token expired"),
|
||||
(APIErrorCode.INVALID_PROXY, "region not available in GB"),
|
||||
(APIErrorCode.AUTH_FAILED, "read timeout"),
|
||||
(APIErrorCode.NETWORK_ERROR, "license refused"),
|
||||
(APIErrorCode.NOT_FOUND, "the proxy failed"),
|
||||
(APIErrorCode.RATE_LIMITED, "not found"),
|
||||
(APIErrorCode.DRM_ERROR, "proxy check failed"),
|
||||
(APIErrorCode.SERVICE_UNAVAILABLE, "invalid input"),
|
||||
(APIErrorCode.SERVICE_ERROR, "Docker not found"),
|
||||
(APIErrorCode.INTERNAL_ERROR, "connection refused"),
|
||||
],
|
||||
)
|
||||
def test_a_coded_exception_keeps_its_code_whatever_its_message_says(code: APIErrorCode, message: str) -> None:
|
||||
err = categorize_exception(coded(RuntimeError(message), code), {"service": "EXAMPLE"})
|
||||
assert err.error_code == code
|
||||
assert err.retryable is (
|
||||
code in {APIErrorCode.NETWORK_ERROR, APIErrorCode.RATE_LIMITED, APIErrorCode.SERVICE_UNAVAILABLE}
|
||||
)
|
||||
assert err.message.endswith(message) and err.details["service"] == "EXAMPLE"
|
||||
|
||||
|
||||
def test_a_coded_exception_gets_the_message_prefix_of_its_keyword_twin() -> None:
|
||||
coded_err = categorize_exception(coded(ValueError("Service is not available in GB"), APIErrorCode.GEOFENCE))
|
||||
guessed = categorize_exception(ValueError("Service is not available in GB"))
|
||||
assert (coded_err.message, coded_err.details) == (guessed.message, guessed.details)
|
||||
|
||||
|
||||
def test_a_coded_cause_names_the_code_of_its_wrapper() -> None:
|
||||
try:
|
||||
try:
|
||||
raise coded(ValueError("bad"), APIErrorCode.INVALID_PROXY)
|
||||
except ValueError as e:
|
||||
raise RuntimeError("license step failed") from e
|
||||
except RuntimeError as wrapper:
|
||||
err = categorize_exception(wrapper)
|
||||
assert err.error_code == APIErrorCode.INVALID_PROXY
|
||||
assert err.message.endswith("bad")
|
||||
|
||||
|
||||
def test_the_wrapper_code_wins_over_the_cause_code() -> None:
|
||||
try:
|
||||
try:
|
||||
raise coded(ValueError("bad"), APIErrorCode.INVALID_PROXY)
|
||||
except ValueError as e:
|
||||
raise coded(RuntimeError("outer"), APIErrorCode.DRM_ERROR) from e
|
||||
except RuntimeError as wrapper:
|
||||
assert categorize_exception(wrapper).error_code == APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
def test_an_error_code_that_is_no_api_code_falls_back_to_the_keywords() -> None:
|
||||
exc = RuntimeError("Connection refused")
|
||||
exc.error_code = 104 # type: ignore[attr-defined]
|
||||
assert categorize_exception(exc).error_code == APIErrorCode.NETWORK_ERROR
|
||||
|
||||
|
||||
def test_a_system_exit_stays_a_service_error_whatever_its_cause_names() -> None:
|
||||
try:
|
||||
try:
|
||||
raise coded(ValueError("bad"), APIErrorCode.INVALID_PROXY)
|
||||
except ValueError as e:
|
||||
raise SystemExit(1) from e
|
||||
except SystemExit as exit_:
|
||||
assert categorize_exception(exit_).error_code == APIErrorCode.SERVICE_ERROR
|
||||
|
||||
@@ -18,6 +18,7 @@ from uuid import uuid4
|
||||
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
|
||||
from unshackle.core.console import set_notice_handler, set_prompt_handler
|
||||
from unshackle.core.downloaders import format_speed, set_speed_limit
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
|
||||
from .download_manager import perform_download
|
||||
|
||||
@@ -84,10 +85,10 @@ def relay_prompts(progress_callback: Callable[[Dict[str, Any]], None]) -> None:
|
||||
try:
|
||||
return answers.get(timeout=AUTH_INPUT_TIMEOUT)
|
||||
except queue.Empty:
|
||||
# "authentication" makes categorize_exception report AUTH_FAILED, not a retryable network
|
||||
# error: a retry only waits on another prompt.
|
||||
raise TimeoutError(
|
||||
f"No client answer to the authentication prompt within {AUTH_INPUT_TIMEOUT:.0f}s"
|
||||
# not a retryable NETWORK_ERROR: a retry only waits on another prompt
|
||||
raise coded(
|
||||
TimeoutError(f"No client answer to the authentication prompt within {AUTH_INPUT_TIMEOUT:.0f}s"),
|
||||
APIErrorCode.AUTH_FAILED,
|
||||
) from None
|
||||
finally:
|
||||
progress_callback({"input_prompt": None})
|
||||
|
||||
+80
-101
@@ -145,6 +145,79 @@ def build_error_response(
|
||||
return response
|
||||
|
||||
|
||||
CATEGORIES: dict[APIErrorCode, tuple[str, str]] = {
|
||||
APIErrorCode.GEOFENCE: ("Content not available in your region", "geofence_restriction"),
|
||||
APIErrorCode.INVALID_PROXY: ("The proxy for this session failed", "proxy_error"),
|
||||
APIErrorCode.AUTH_FAILED: ("Authentication failed", "authentication_error"),
|
||||
APIErrorCode.NETWORK_ERROR: ("Network error occurred", "network_connectivity"),
|
||||
APIErrorCode.NOT_FOUND: ("Resource not found", "not_found"),
|
||||
APIErrorCode.RATE_LIMITED: ("Rate limit exceeded", "rate_limited"),
|
||||
APIErrorCode.DRM_ERROR: ("DRM error", "drm_failure"),
|
||||
APIErrorCode.SERVICE_UNAVAILABLE: ("Service temporarily unavailable", "service_unavailable"),
|
||||
APIErrorCode.INVALID_INPUT: ("Invalid input", "validation_failed"),
|
||||
APIErrorCode.INTERNAL_ERROR: ("An unexpected error occurred", ""),
|
||||
}
|
||||
"""The message prefix and ``details.reason`` of each code that ``categorize_exception`` gives."""
|
||||
|
||||
RETRYABLE = {APIErrorCode.NETWORK_ERROR, APIErrorCode.RATE_LIMITED, APIErrorCode.SERVICE_UNAVAILABLE}
|
||||
|
||||
|
||||
def categorized(code: APIErrorCode, text: str, context: dict[str, Any]) -> APIError:
|
||||
"""The APIError of ``code`` for an exception with message ``text``."""
|
||||
prefix, reason = CATEGORIES.get(code, ("", ""))
|
||||
text = redact_secrets(text) or ""
|
||||
return APIError(
|
||||
error_code=code,
|
||||
message=f"{prefix}: {text}" if prefix else text,
|
||||
details={**context, "reason": reason} if reason else context,
|
||||
retryable=code in RETRYABLE,
|
||||
)
|
||||
|
||||
|
||||
def keyword_code(exc_str: str, root: BaseException) -> APIErrorCode:
|
||||
"""Guess the code of an exception that names none, from the words of its message and its type.
|
||||
|
||||
The fallback for exceptions from out-of-repo services; a core raiser names its code with ``coded``.
|
||||
"""
|
||||
exc_type = type(root).__name__
|
||||
if any(
|
||||
keyword in exc_str
|
||||
for keyword in ["geofence", "geoblock", "geo-block", "geolocation", "region", "not available in", "territory"]
|
||||
):
|
||||
return APIErrorCode.GEOFENCE
|
||||
if "proxy" in str(root).lower():
|
||||
return APIErrorCode.INVALID_PROXY
|
||||
if any(keyword in exc_str for keyword in ["auth", "login", "credential", "unauthorized", "forbidden", "token"]):
|
||||
return APIErrorCode.AUTH_FAILED
|
||||
if any(
|
||||
keyword in exc_str
|
||||
for keyword in [
|
||||
"connection",
|
||||
"timeout",
|
||||
"network",
|
||||
"unreachable",
|
||||
"socket",
|
||||
"dns",
|
||||
"resolve",
|
||||
]
|
||||
) or exc_type in ["ConnectionError", "TimeoutError", "URLError", "SSLError"]:
|
||||
return APIErrorCode.NETWORK_ERROR
|
||||
if any(keyword in exc_str for keyword in ["not found", "404", "does not exist", "invalid id"]):
|
||||
return APIErrorCode.NOT_FOUND
|
||||
if any(keyword in exc_str for keyword in ["rate limit", "too many requests", "429", "throttle"]):
|
||||
return APIErrorCode.RATE_LIMITED
|
||||
if any(keyword in exc_str for keyword in ["drm", "license", "widevine", "playready", "decrypt"]):
|
||||
return APIErrorCode.DRM_ERROR
|
||||
if any(keyword in exc_str for keyword in ["service unavailable", "503", "maintenance", "temporarily unavailable"]):
|
||||
return APIErrorCode.SERVICE_UNAVAILABLE
|
||||
if any(keyword in exc_str for keyword in ["invalid", "malformed", "validation"]) or exc_type in [
|
||||
"ValueError",
|
||||
"ValidationError",
|
||||
]:
|
||||
return APIErrorCode.INVALID_INPUT
|
||||
return APIErrorCode.INTERNAL_ERROR
|
||||
|
||||
|
||||
def categorize_exception(
|
||||
exc: BaseException,
|
||||
context: dict[str, Any] | None = None,
|
||||
@@ -152,8 +225,8 @@ def categorize_exception(
|
||||
"""
|
||||
Categorize a generic exception into a structured APIError; an APIError is returned as it is.
|
||||
|
||||
This function attempts to identify the type of error based on the exception
|
||||
type, message patterns, and optional context information.
|
||||
An exception that names its code (``coded``, or its cause's) gets that code. Any other gets the code
|
||||
that ``keyword_code`` guesses from its message.
|
||||
|
||||
Args:
|
||||
exc: The exception to categorize
|
||||
@@ -174,105 +247,11 @@ def categorize_exception(
|
||||
retryable=False,
|
||||
)
|
||||
root = exc.__cause__ or exc
|
||||
exc_str = f"{exc} {root}".lower()
|
||||
exc_type = type(root).__name__
|
||||
|
||||
if any(
|
||||
keyword in exc_str
|
||||
for keyword in ["geofence", "geoblock", "geo-block", "geolocation", "region", "not available in", "territory"]
|
||||
):
|
||||
return APIError(
|
||||
error_code=APIErrorCode.GEOFENCE,
|
||||
message=f"Content not available in your region: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "geofence_restriction"},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
if "proxy" in str(root).lower():
|
||||
return APIError(
|
||||
error_code=APIErrorCode.INVALID_PROXY,
|
||||
message=f"The proxy for this session failed: {redact_secrets(str(root))}",
|
||||
details={**context, "reason": "proxy_error"},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
if any(keyword in exc_str for keyword in ["auth", "login", "credential", "unauthorized", "forbidden", "token"]):
|
||||
return APIError(
|
||||
error_code=APIErrorCode.AUTH_FAILED,
|
||||
message=f"Authentication failed: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "authentication_error"},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
if any(
|
||||
keyword in exc_str
|
||||
for keyword in [
|
||||
"connection",
|
||||
"timeout",
|
||||
"network",
|
||||
"unreachable",
|
||||
"socket",
|
||||
"dns",
|
||||
"resolve",
|
||||
]
|
||||
) or exc_type in ["ConnectionError", "TimeoutError", "URLError", "SSLError"]:
|
||||
return APIError(
|
||||
error_code=APIErrorCode.NETWORK_ERROR,
|
||||
message=f"Network error occurred: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "network_connectivity"},
|
||||
retryable=True,
|
||||
)
|
||||
|
||||
if any(keyword in exc_str for keyword in ["not found", "404", "does not exist", "invalid id"]):
|
||||
return APIError(
|
||||
error_code=APIErrorCode.NOT_FOUND,
|
||||
message=f"Resource not found: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "not_found"},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
if any(keyword in exc_str for keyword in ["rate limit", "too many requests", "429", "throttle"]):
|
||||
return APIError(
|
||||
error_code=APIErrorCode.RATE_LIMITED,
|
||||
message=f"Rate limit exceeded: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "rate_limited"},
|
||||
retryable=True,
|
||||
http_status=429,
|
||||
)
|
||||
|
||||
if any(keyword in exc_str for keyword in ["drm", "license", "widevine", "playready", "decrypt"]):
|
||||
return APIError(
|
||||
error_code=APIErrorCode.DRM_ERROR,
|
||||
message=f"DRM error: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "drm_failure"},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
if any(keyword in exc_str for keyword in ["service unavailable", "503", "maintenance", "temporarily unavailable"]):
|
||||
return APIError(
|
||||
error_code=APIErrorCode.SERVICE_UNAVAILABLE,
|
||||
message=f"Service temporarily unavailable: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "service_unavailable"},
|
||||
retryable=True,
|
||||
)
|
||||
|
||||
if any(keyword in exc_str for keyword in ["invalid", "malformed", "validation"]) or exc_type in [
|
||||
"ValueError",
|
||||
"ValidationError",
|
||||
]:
|
||||
return APIError(
|
||||
error_code=APIErrorCode.INVALID_INPUT,
|
||||
message=f"Invalid input: {redact_secrets(str(exc))}",
|
||||
details={**context, "reason": "validation_failed"},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
return APIError(
|
||||
error_code=APIErrorCode.INTERNAL_ERROR,
|
||||
message=f"An unexpected error occurred: {redact_secrets(str(exc))}",
|
||||
details=context,
|
||||
retryable=False,
|
||||
)
|
||||
for carrier in (exc, root):
|
||||
if isinstance(code := getattr(carrier, "error_code", None), APIErrorCode):
|
||||
return categorized(code, str(carrier), context)
|
||||
code = keyword_code(f"{exc} {root}".lower(), root)
|
||||
return categorized(code, str(root if code == APIErrorCode.INVALID_PROXY else exc), context)
|
||||
|
||||
|
||||
def handle_api_exception(
|
||||
|
||||
@@ -14,7 +14,7 @@ import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, Optional
|
||||
|
||||
from unshackle.core.remote_protocol import AuthStatus
|
||||
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, coded
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.api.session_channel import SessionChannel
|
||||
@@ -92,7 +92,7 @@ class InputBridge:
|
||||
try:
|
||||
# cancel() and an answer both set the event, so a single wait returns on signal-or-cancel
|
||||
if not ask.answered.wait(timeout=timeout):
|
||||
raise TimeoutError(f"No client response for prompt within {timeout}s")
|
||||
raise coded(TimeoutError(f"No client response for prompt within {timeout}s"), APIErrorCode.AUTH_FAILED)
|
||||
with self._lock:
|
||||
if self._cancelled:
|
||||
raise RuntimeError("Session was cancelled")
|
||||
@@ -258,7 +258,7 @@ class NoUserBridge(InputBridge):
|
||||
"""Bridge for a request with no channel to the user: a login step that needs the user fails at once."""
|
||||
|
||||
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT) -> str:
|
||||
raise RuntimeError(NO_USER_MESSAGE)
|
||||
raise coded(RuntimeError(NO_USER_MESSAGE), APIErrorCode.AUTH_FAILED)
|
||||
|
||||
def ensure_active(self) -> None:
|
||||
raise RuntimeError(NO_USER_MESSAGE)
|
||||
raise coded(RuntimeError(NO_USER_MESSAGE), APIErrorCode.AUTH_FAILED)
|
||||
|
||||
@@ -12,6 +12,7 @@ from requests import Session
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.drm import key_args as drm_key_args
|
||||
from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utilities import log_event
|
||||
from unshackle.core.utils import run_proxy
|
||||
|
||||
@@ -193,11 +194,17 @@ class ClearKeyCENC:
|
||||
class KIDNotFound(Exception):
|
||||
"""KID (Encryption Key ID) was not found."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class CEKNotFound(click.ClickException):
|
||||
"""CEK (Content Encryption Key) for KID was not found in License."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class EmptyLicense(click.ClickException):
|
||||
"""License returned no Content Encryption Keys."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
__all__ = ("ClearKeyCENC",)
|
||||
|
||||
@@ -22,6 +22,7 @@ from unshackle.core.drm.verify import (
|
||||
kidless_track_kids,
|
||||
read_top_level_box,
|
||||
)
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.utilities import log_event
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -81,7 +82,7 @@ def decrypt_cenc(drm: Any, path: Path, drm_type: str) -> None:
|
||||
def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]]) -> None:
|
||||
"""Decrypt ``path`` in place with mp4decrypt, taking the ``--key`` arguments from ``key_args_for(track_kids)``."""
|
||||
if not binaries.Mp4decrypt:
|
||||
raise EnvironmentError("mp4decrypt executable not found but is required.")
|
||||
raise coded(EnvironmentError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR)
|
||||
|
||||
output_path = path.with_stem(f"{path.stem}_decrypted")
|
||||
key_args = key_args_for(kidless_track_kids(read_top_level_box(path, b"moov") or b""))
|
||||
@@ -116,7 +117,7 @@ def shaka_decrypt(path: Path, keys: str, label: str) -> None:
|
||||
Only a non-zero exit is a failure; its non-noise log lines go to the console under ``[label]``.
|
||||
"""
|
||||
if not binaries.ShakaPackager:
|
||||
raise EnvironmentError("Shaka Packager executable not found but is required.")
|
||||
raise coded(EnvironmentError("Shaka Packager executable not found but is required."), APIErrorCode.DRM_ERROR)
|
||||
|
||||
output_path = path.with_stem(f"{path.stem}_decrypted")
|
||||
config.directories.temp.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -13,6 +13,7 @@ from typing import Any, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.cdm.monalisa import MonaLisaCDM
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utils.subprocess import run_step
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -31,9 +32,13 @@ class MonaLisa:
|
||||
class TicketNotFound(Exception):
|
||||
"""Raised when the caller gives no PSSH/ticket data."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class KeyExtractionFailed(Exception):
|
||||
"""Raised when content key extraction from the ticket fails."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ticket: Union[str, bytes],
|
||||
|
||||
@@ -21,6 +21,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.drm import key_args as drm_key_args
|
||||
from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.session import AnySession, utf8_text
|
||||
from unshackle.core.utilities import call_licence, get_boxes, log_event
|
||||
from unshackle.core.utils import run_proxy
|
||||
@@ -559,19 +560,19 @@ class PlayReady:
|
||||
|
||||
class Exceptions:
|
||||
class PSSHNotFound(Exception):
|
||||
pass
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class KIDNotFound(Exception):
|
||||
pass
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class CEKNotFound(click.ClickException):
|
||||
pass
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class EmptyLicense(click.ClickException):
|
||||
pass
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class DeviceRevoked(Exception):
|
||||
pass
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
__all__ = ("PlayReady",)
|
||||
|
||||
@@ -14,6 +14,7 @@ from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
|
||||
from unshackle.core.drm.playready import PlayReady
|
||||
from unshackle.core.drm.verify import kidless_track_kids
|
||||
from unshackle.core.drm.widevine import Widevine
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
|
||||
SEGMENT_DRM_T = Union[Widevine, PlayReady, ClearKeyCENC]
|
||||
|
||||
@@ -48,7 +49,7 @@ class SegmentDecrypter:
|
||||
|
||||
def __init__(self, drm: SEGMENT_DRM_T, init_data: bytes, work_dir: Path, workers: Optional[int] = None) -> None:
|
||||
if not binaries.Mp4decrypt:
|
||||
raise EnvironmentError("mp4decrypt executable not found but is required.")
|
||||
raise coded(EnvironmentError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR)
|
||||
|
||||
self.drm = drm
|
||||
self.key_args = drm.mp4decrypt_key_args(kidless_track_kids(init_data))
|
||||
|
||||
@@ -17,6 +17,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.drm import key_args as drm_key_args
|
||||
from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.session import AnySession, utf8_text
|
||||
from unshackle.core.utilities import call_licence, get_boxes, log_event
|
||||
from unshackle.core.utils import run_proxy
|
||||
@@ -312,14 +313,22 @@ class Widevine:
|
||||
class PSSHNotFound(Exception):
|
||||
"""PSSH (Protection System Specific Header) was not found."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class KIDNotFound(Exception):
|
||||
"""KID (Encryption Key ID) was not found."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class CEKNotFound(click.ClickException):
|
||||
"""CEK (Content Encryption Key) for KID was not found in License."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
class EmptyLicense(click.ClickException):
|
||||
"""License returned no Content Encryption Keys."""
|
||||
|
||||
error_code = APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
__all__ = ("Widevine",)
|
||||
|
||||
@@ -18,8 +18,9 @@ from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.drm import ClearKey, MonaLisa, real_kids
|
||||
from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snapshot
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.remote_service import RemoteService, ServerKeySource, resolve_proxy_arg, segment_uri_filter
|
||||
from unshackle.core.session import utf8_text
|
||||
from unshackle.core.session import failure_response, utf8_text
|
||||
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles
|
||||
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks.attachment import Attachment
|
||||
@@ -98,6 +99,27 @@ def content_period_filter(manifest: Any, kept: Any, title: Any) -> Optional[Call
|
||||
return lambda period: period.get("id") not in kept
|
||||
|
||||
|
||||
def manifest_fetch_error(manifest_type: str, title: Any, error: Exception) -> click.ClickException:
|
||||
"""The error for a failed manifest fetch, with the API error code of an HTTP status that has only one cause.
|
||||
|
||||
An expired signed URL can also answer 200 with an error page, so every failure names a possible expiry.
|
||||
A 403 can be an expiry, a region or a proxy, so it and a failure with no answer keep the keyword code.
|
||||
"""
|
||||
status = getattr(failure_response(error), "status_code", None)
|
||||
status = status if isinstance(status, int) else None
|
||||
answered = f" (HTTP {status})" if status else ""
|
||||
failure = click.ClickException(
|
||||
f"Failed to fetch the {manifest_type} manifest for '{title}'{answered}, the URL may have expired: {error}"
|
||||
)
|
||||
if status in (404, 410):
|
||||
return coded(failure, APIErrorCode.NOT_FOUND)
|
||||
if status == 429:
|
||||
return coded(failure, APIErrorCode.RATE_LIMITED)
|
||||
if status and status >= 500:
|
||||
return coded(failure, APIErrorCode.SERVICE_UNAVAILABLE)
|
||||
return failure
|
||||
|
||||
|
||||
def resolve_import_manifest_data(
|
||||
tracks: Tracks,
|
||||
manifest_type: Optional[str],
|
||||
@@ -148,9 +170,7 @@ def resolve_import_manifest_data(
|
||||
except ValueError as e:
|
||||
raise click.ClickException(f"Failed to parse the {manifest_type} manifest for '{title}': {e}")
|
||||
except Exception as e:
|
||||
raise click.ClickException(
|
||||
f"Failed to fetch the {manifest_type} manifest for '{title}', the URL may have expired: {e}"
|
||||
)
|
||||
raise manifest_fetch_error(manifest_type, title, e)
|
||||
|
||||
local_tracks = [*parsed.videos, *parsed.audio, *parsed.subtitles]
|
||||
for track in pending:
|
||||
@@ -409,9 +429,7 @@ class ImportService:
|
||||
try:
|
||||
manifest = parser.from_url(url=manifest_url, session=self.session)
|
||||
except Exception as e:
|
||||
raise click.ClickException(
|
||||
f"Failed to fetch the {manifest_type} manifest for '{title}', the URL may have expired: {e}"
|
||||
)
|
||||
raise manifest_fetch_error(manifest_type, title, e)
|
||||
if language is None and isinstance(manifest, HLS):
|
||||
language = hls_audio_language(manifest)
|
||||
if language is None:
|
||||
@@ -825,7 +843,10 @@ class ImportService:
|
||||
}
|
||||
)
|
||||
subject = f"KID {', '.join(kids)}" if kids else f"track {track}"
|
||||
return click.ClickException(f"The export has no content key to decrypt {subject}, and no vault has it")
|
||||
return coded(
|
||||
click.ClickException(f"The export has no content key to decrypt {subject}, and no vault has it"),
|
||||
APIErrorCode.DRM_ERROR,
|
||||
)
|
||||
|
||||
def decrypts_samples(self, track: AnyTrack) -> bool:
|
||||
return False
|
||||
|
||||
@@ -13,6 +13,7 @@ import requests
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.proxies.proxy import Proxy
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.utilities import get_country_code, get_country_name, get_debug_logger, log_event
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.ip_info import get_ip_info
|
||||
@@ -191,7 +192,7 @@ class Gluetun(Proxy):
|
||||
verify_ip: Automatically make sure that the IP and region are correct after connection (default: True)
|
||||
"""
|
||||
if not binaries.Docker:
|
||||
raise RuntimeError("Docker not found, the Gluetun proxy needs it")
|
||||
raise coded(RuntimeError("Docker not found, the Gluetun proxy needs it"), APIErrorCode.INVALID_PROXY)
|
||||
|
||||
self.providers = providers or {}
|
||||
self.base_port = base_port
|
||||
@@ -365,7 +366,7 @@ class Gluetun(Proxy):
|
||||
self.remove_container(container_name)
|
||||
if query_key in self.active_containers:
|
||||
del self.active_containers[query_key]
|
||||
raise RuntimeError(f"Failed to create Gluetun container: {e}")
|
||||
raise coded(RuntimeError(f"Failed to create Gluetun container: {e}"), APIErrorCode.INVALID_PROXY)
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""Stop and remove all managed Gluetun containers."""
|
||||
|
||||
@@ -8,6 +8,7 @@ import requests
|
||||
|
||||
from unshackle.core.proxies.asn import describe, is_ip, mapped_query, select, split_selector
|
||||
from unshackle.core.proxies.proxy import Proxy, cached_catalogue
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.utilities import COUNTRY_CODE_ALIASES
|
||||
|
||||
|
||||
@@ -24,7 +25,10 @@ class NordVPN(Proxy):
|
||||
if not password:
|
||||
raise ValueError("No password for the NordVPN proxy provider")
|
||||
if not re.match(r"^[a-z0-9]{48}$", username + password, re.IGNORECASE) or "@" in username:
|
||||
raise ValueError("NordVPN needs its Service Credentials, not your login credentials")
|
||||
raise coded(
|
||||
ValueError("NordVPN needs its Service Credentials, not your login credentials"),
|
||||
APIErrorCode.INVALID_PROXY,
|
||||
)
|
||||
|
||||
if server_map is not None and not isinstance(server_map, dict):
|
||||
raise TypeError(f"Expected server_map to be a dict mapping a region to a server ID, not '{server_map!r}'.")
|
||||
|
||||
@@ -14,6 +14,7 @@ import requests
|
||||
from click.core import ParameterSource
|
||||
|
||||
from unshackle.core.proxies.proxy import Proxy
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.utils.redact import mask_proxy
|
||||
|
||||
log = logging.getLogger("proxies")
|
||||
@@ -46,12 +47,15 @@ def find_provider(proxy_providers: List[Any], name: str, hint: str = "") -> Any:
|
||||
for provider in proxy_providers:
|
||||
if isinstance(provider, Unavailable):
|
||||
if provider.name.lower() == name.lower():
|
||||
raise ValueError(f"The proxy provider {provider.name} could not load: {provider.error}")
|
||||
raise coded(
|
||||
ValueError(f"The proxy provider {provider.name} could not load: {provider.error}"),
|
||||
APIErrorCode.INVALID_PROXY,
|
||||
)
|
||||
elif provider.__class__.__name__.lower() == name.lower():
|
||||
return provider
|
||||
available = [x.__class__.__name__ for x in proxy_providers if not isinstance(x, Unavailable)]
|
||||
message = f"The proxy provider '{name}' was not found. Available: {available}"
|
||||
raise ValueError(f"{message}. {hint}" if hint else message)
|
||||
raise coded(ValueError(f"{message}. {hint}" if hint else message), APIErrorCode.INVALID_PROXY)
|
||||
|
||||
|
||||
def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = False, quiet: bool = False) -> List[Any]:
|
||||
@@ -166,9 +170,13 @@ def pick_proxy(proxy_providers: List[Any], query: str, provider_name: Optional[s
|
||||
except Exception as e:
|
||||
if isinstance(e, ValueError) and not isinstance(e, (json.JSONDecodeError, requests.RequestException)):
|
||||
raise
|
||||
raise ValueError(f"The proxy provider {provider_name} failed for {query}: {e}") from e
|
||||
raise coded(
|
||||
ValueError(f"The proxy provider {provider_name} failed for {query}: {e}"), APIErrorCode.INVALID_PROXY
|
||||
) from e
|
||||
if not uri:
|
||||
raise ValueError(f"The proxy provider {provider_name} had no proxy for {query}")
|
||||
raise coded(
|
||||
ValueError(f"The proxy provider {provider_name} had no proxy for {query}"), APIErrorCode.INVALID_PROXY
|
||||
)
|
||||
return provider, uri
|
||||
errors = []
|
||||
for provider in proxy_providers:
|
||||
@@ -182,7 +190,7 @@ def pick_proxy(proxy_providers: List[Any], query: str, provider_name: Optional[s
|
||||
if uri:
|
||||
return provider, uri
|
||||
detail = f" ({'; '.join(errors)})" if errors else ""
|
||||
raise ValueError(f"No proxy provider had a proxy for {query}{detail}")
|
||||
raise coded(ValueError(f"No proxy provider had a proxy for {query}{detail}"), APIErrorCode.INVALID_PROXY)
|
||||
|
||||
|
||||
def describe_proxy(provider: Any, uri: str, query: str, allow_debug: bool = True) -> str:
|
||||
|
||||
@@ -15,6 +15,7 @@ import requests
|
||||
from unshackle.core.proxies.asn import describe, fold, is_ip, mapped_query, select, split_selector
|
||||
from unshackle.core.proxies.controld import build_query, parse_a_records
|
||||
from unshackle.core.proxies.proxy import Proxy, cached_catalogue
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.utilities import COUNTRY_CODE_ALIASES
|
||||
|
||||
log = logging.getLogger("proxies.surfsharkvpn")
|
||||
@@ -95,7 +96,10 @@ class SurfsharkVPN(Proxy):
|
||||
if not password:
|
||||
raise ValueError("No password for the SurfsharkVPN proxy provider")
|
||||
if not re.match(r"^[a-z0-9]{48}$", username + password, re.IGNORECASE) or "@" in username:
|
||||
raise ValueError("SurfsharkVPN needs its Service Credentials, not your login credentials")
|
||||
raise coded(
|
||||
ValueError("SurfsharkVPN needs its Service Credentials, not your login credentials"),
|
||||
APIErrorCode.INVALID_PROXY,
|
||||
)
|
||||
|
||||
if server_map is not None and not isinstance(server_map, dict):
|
||||
raise TypeError(
|
||||
|
||||
@@ -9,7 +9,7 @@ older peer.
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum, StrEnum
|
||||
from typing import Any, NotRequired, Optional, TypedDict
|
||||
from typing import Any, NotRequired, Optional, TypedDict, TypeVar
|
||||
|
||||
HEALTH_ROUTE = "/api/health"
|
||||
SERVICES_ROUTE = "/api/services"
|
||||
@@ -74,6 +74,15 @@ class APIErrorCode(str, Enum):
|
||||
WORKER_ERROR = "WORKER_ERROR"
|
||||
|
||||
|
||||
E = TypeVar("E", bound=BaseException)
|
||||
|
||||
|
||||
def coded(exc: E, code: APIErrorCode) -> E:
|
||||
"""``exc`` with the API error code that ``categorize_exception`` reports for it, whatever its message says."""
|
||||
exc.error_code = code # type: ignore[attr-defined]
|
||||
return exc
|
||||
|
||||
|
||||
class ClientErrorKind(StrEnum):
|
||||
"""The error kinds a remote client gives a failure of its own. The server never sends them.
|
||||
|
||||
|
||||
@@ -84,6 +84,7 @@ from unshackle.core.remote_protocol import (
|
||||
TrackKeys,
|
||||
TracksReply,
|
||||
TracksRequest,
|
||||
coded,
|
||||
)
|
||||
from unshackle.core.search_result import SearchResult
|
||||
from unshackle.core.session import MAX_BACKOFF
|
||||
@@ -1680,7 +1681,9 @@ class RemoteService:
|
||||
why = "The server CDM refused this track"
|
||||
cdm = self.local_cdm
|
||||
if cdm is None:
|
||||
raise click.ClickException(f"{why}, and {track} needs a local CDM to license it")
|
||||
raise coded(
|
||||
click.ClickException(f"{why}, and {track} needs a local CDM to license it"), APIErrorCode.DRM_ERROR
|
||||
)
|
||||
drm_class = "PlayReady" if is_playready_cdm(cdm) else "Widevine"
|
||||
height = getattr(track, "height", None)
|
||||
systems = {d.__class__.__name__ for d in track.drm or ()}
|
||||
|
||||
@@ -27,6 +27,7 @@ from unshackle.core.drm import DRM_T
|
||||
from unshackle.core.launch import launch_keys
|
||||
from unshackle.core.proxies.basic import Basic
|
||||
from unshackle.core.proxies.resolve import pick_proxy
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.search_result import SearchResult
|
||||
from unshackle.core.session import (
|
||||
BACKOFF_FACTOR,
|
||||
@@ -251,8 +252,11 @@ class Service(metaclass=ABCMeta):
|
||||
elif self.is_region_allowed(current_region):
|
||||
self.log.info("Service is not Geoblocked in your region")
|
||||
elif not (fence_targets := [x for x in self.GEOFENCE if self.is_region_allowed(x)]):
|
||||
raise click.ClickException(
|
||||
f"Service is not available in {whose} region ({current_region.upper()})"
|
||||
raise coded(
|
||||
click.ClickException(
|
||||
f"Service is not available in {whose} region ({current_region.upper()})"
|
||||
),
|
||||
APIErrorCode.GEOFENCE,
|
||||
)
|
||||
else:
|
||||
requested_proxy = fence_targets[0] # first is likely main region
|
||||
@@ -285,8 +289,11 @@ class Service(metaclass=ABCMeta):
|
||||
self.current_region = exit_region
|
||||
# Only GEOBLOCK applies here: an explicit --proxy outside GEOFENCE stays the user's call.
|
||||
if exit_region and any(x.lower() == exit_region.lower() for x in self.GEOBLOCK):
|
||||
raise click.ClickException(
|
||||
f"Service is not available in {whose} proxy's region ({exit_region.upper()})"
|
||||
raise coded(
|
||||
click.ClickException(
|
||||
f"Service is not available in {whose} proxy's region ({exit_region.upper()})"
|
||||
),
|
||||
APIErrorCode.GEOFENCE,
|
||||
)
|
||||
else:
|
||||
# No proxy, use cached IP info for title caching (non-critical)
|
||||
@@ -492,7 +499,7 @@ class Service(metaclass=ABCMeta):
|
||||
if result is not None:
|
||||
return result
|
||||
if time.monotonic() + interval >= deadline:
|
||||
raise TimeoutError(f"No approval within {timeout:.0f}s")
|
||||
raise coded(TimeoutError(f"No approval within {timeout:.0f}s"), APIErrorCode.AUTH_FAILED)
|
||||
time.sleep(interval)
|
||||
finally:
|
||||
show_notice(None)
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import Any, Callable, Optional
|
||||
import requests
|
||||
|
||||
from unshackle.core.cacher import Cacher
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.utils import run_proxy
|
||||
|
||||
CACHE_KEY = "ip_info_v4"
|
||||
@@ -288,13 +289,19 @@ def verify_proxy_exit(session: requests.Session) -> dict:
|
||||
if len(errors) < len(build_providers()):
|
||||
log.warning("No geolocation API returned the proxy exit IP, so the exit IP check does not occur")
|
||||
return {}
|
||||
raise ConnectionError(f"Proxy check failed: no IP lookup got through the proxy ({type(errors[-1]).__name__})")
|
||||
raise coded(
|
||||
ConnectionError(f"Proxy check failed: no IP lookup got through the proxy ({type(errors[-1]).__name__})"),
|
||||
APIErrorCode.INVALID_PROXY,
|
||||
)
|
||||
exit_ip = info.get("ip")
|
||||
server_ip = (get_ip_info(cached=True) or {}).get("ip")
|
||||
# The cached IP can be up to 24h old: a machine that was on a VPN when it cached its IP,
|
||||
# and now uses that VPN as a proxy, matches the old IP. A live lookup runs only on a match.
|
||||
if exit_ip and server_ip == exit_ip and (get_ip_info() or {}).get("ip") == exit_ip:
|
||||
raise ConnectionError(
|
||||
"Proxy check failed: the proxy exit IP is the IP of this machine, so traffic does not go through the proxy."
|
||||
raise coded(
|
||||
ConnectionError(
|
||||
"Proxy check failed: the proxy exit IP is the IP of this machine, so traffic does not go through the proxy."
|
||||
),
|
||||
APIErrorCode.INVALID_PROXY,
|
||||
)
|
||||
return info
|
||||
|
||||
Reference in New Issue
Block a user