forked from kenzuya/unshackle
fix(api): let a core failure name its own API error code
This commit is contained in:
@@ -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