forked from kenzuya/unshackle
refactor(remote): deduplicate CDM loading, proxy resolution, and license handling
This commit is contained in:
@@ -24,15 +24,8 @@ from uuid import UUID
|
|||||||
import click
|
import click
|
||||||
import jsonpickle
|
import jsonpickle
|
||||||
import yaml
|
import yaml
|
||||||
from construct import ConstError
|
|
||||||
from langcodes import Language
|
from langcodes import Language
|
||||||
from pymediainfo import MediaInfo
|
from pymediainfo import MediaInfo
|
||||||
from pyplayready.cdm import Cdm as PlayReadyCdm
|
|
||||||
from pyplayready.device import Device as PlayReadyDevice
|
|
||||||
from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm
|
|
||||||
from pywidevine.cdm import Cdm as WidevineCdm
|
|
||||||
from pywidevine.device import Device
|
|
||||||
from pywidevine.remotecdm import RemoteCdm
|
|
||||||
from rich.console import Group
|
from rich.console import Group
|
||||||
from rich.live import Live
|
from rich.live import Live
|
||||||
from rich.padding import Padding
|
from rich.padding import Padding
|
||||||
@@ -44,7 +37,7 @@ from rich.text import Text
|
|||||||
from rich.tree import Tree
|
from rich.tree import Tree
|
||||||
|
|
||||||
from unshackle.core import binaries, providers
|
from unshackle.core import binaries, providers
|
||||||
from unshackle.core.cdm import CustomRemoteCDM, DecryptLabsRemoteCDM
|
from unshackle.core.cdm import DecryptLabsRemoteCDM
|
||||||
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.console import console
|
from unshackle.core.console import console
|
||||||
@@ -3077,70 +3070,6 @@ class dl:
|
|||||||
if not cdm_name:
|
if not cdm_name:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
cdm_api = next(iter(x.copy() for x in config.remote_cdm if x["name"] == cdm_name), None)
|
from unshackle.core.cdm import load_cdm
|
||||||
if cdm_api:
|
|
||||||
cdm_type = cdm_api.get("type")
|
|
||||||
|
|
||||||
if cdm_type == "decrypt_labs":
|
return load_cdm(cdm_name, service_name=service, vaults=self.vaults)
|
||||||
del cdm_api["name"]
|
|
||||||
del cdm_api["type"]
|
|
||||||
|
|
||||||
if "secret" not in cdm_api or not cdm_api["secret"]:
|
|
||||||
if config.decrypt_labs_api_key:
|
|
||||||
cdm_api["secret"] = config.decrypt_labs_api_key
|
|
||||||
else:
|
|
||||||
raise ValueError(
|
|
||||||
f"No secret provided for DecryptLabs CDM '{cdm_name}' and no global "
|
|
||||||
"decrypt_labs_api_key configured"
|
|
||||||
)
|
|
||||||
|
|
||||||
# All DecryptLabs CDMs use DecryptLabsRemoteCDM
|
|
||||||
return DecryptLabsRemoteCDM(service_name=service, vaults=self.vaults, **cdm_api)
|
|
||||||
|
|
||||||
elif cdm_type == "custom_api":
|
|
||||||
del cdm_api["name"]
|
|
||||||
del cdm_api["type"]
|
|
||||||
|
|
||||||
# All Custom API CDMs use CustomRemoteCDM
|
|
||||||
return CustomRemoteCDM(service_name=service, vaults=self.vaults, **cdm_api)
|
|
||||||
|
|
||||||
else:
|
|
||||||
device_type = cdm_api.get("Device Type", cdm_api.get("device_type", ""))
|
|
||||||
if str(device_type).upper() == "PLAYREADY":
|
|
||||||
return PlayReadyRemoteCdm(
|
|
||||||
security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3000)),
|
|
||||||
host=cdm_api.get("Host", cdm_api.get("host")),
|
|
||||||
secret=cdm_api.get("Secret", cdm_api.get("secret")),
|
|
||||||
device_name=cdm_api.get("Device Name", cdm_api.get("device_name")),
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return RemoteCdm(
|
|
||||||
device_type=cdm_api.get("Device Type", cdm_api.get("device_type", "")),
|
|
||||||
system_id=cdm_api.get("System ID", cdm_api.get("system_id", "")),
|
|
||||||
security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3000)),
|
|
||||||
host=cdm_api.get("Host", cdm_api.get("host")),
|
|
||||||
secret=cdm_api.get("Secret", cdm_api.get("secret")),
|
|
||||||
device_name=cdm_api.get("Device Name", cdm_api.get("device_name")),
|
|
||||||
)
|
|
||||||
|
|
||||||
prd_path = config.directories.prds / f"{cdm_name}.prd"
|
|
||||||
if not prd_path.is_file():
|
|
||||||
prd_path = config.directories.wvds / f"{cdm_name}.prd"
|
|
||||||
if prd_path.is_file():
|
|
||||||
device = PlayReadyDevice.load(prd_path)
|
|
||||||
return PlayReadyCdm.from_device(device)
|
|
||||||
|
|
||||||
cdm_path = config.directories.wvds / f"{cdm_name}.wvd"
|
|
||||||
if not cdm_path.is_file():
|
|
||||||
raise ValueError(f"{cdm_name} does not exist or is not a file")
|
|
||||||
|
|
||||||
try:
|
|
||||||
device = Device.load(cdm_path)
|
|
||||||
except ConstError as e:
|
|
||||||
if "expected 2 but parsed 1" in str(e):
|
|
||||||
raise ValueError(
|
|
||||||
f"{cdm_name}.wvd seems to be a v1 WVD file, use `pywidevine migrate --help` to migrate it to v2."
|
|
||||||
)
|
|
||||||
raise ValueError(f"{cdm_name}.wvd is an invalid or corrupt Widevine Device file, {e}")
|
|
||||||
|
|
||||||
return WidevineCdm.from_device(device)
|
|
||||||
|
|||||||
+231
-429
@@ -6,10 +6,7 @@ from aiohttp import web
|
|||||||
|
|
||||||
from unshackle.core.api.errors import APIError, APIErrorCode, handle_api_exception
|
from unshackle.core.api.errors import APIError, APIErrorCode, handle_api_exception
|
||||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||||
from unshackle.core.proxies.basic import Basic
|
from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_proxy
|
||||||
from unshackle.core.proxies.hola import Hola
|
|
||||||
from unshackle.core.proxies.nordvpn import NordVPN
|
|
||||||
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
|
|
||||||
from unshackle.core.services import Services
|
from unshackle.core.services import Services
|
||||||
from unshackle.core.titles import Episode, Movie, Title_T
|
from unshackle.core.titles import Episode, Movie, Title_T
|
||||||
from unshackle.core.tracks import Audio, Subtitle, Video
|
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||||
@@ -65,97 +62,6 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def initialize_proxy_providers() -> List[Any]:
|
|
||||||
"""Initialize and return available proxy providers."""
|
|
||||||
proxy_providers = []
|
|
||||||
try:
|
|
||||||
from unshackle.core import binaries
|
|
||||||
# Load the main unshackle config to get proxy provider settings
|
|
||||||
from unshackle.core.config import config as main_config
|
|
||||||
|
|
||||||
log.debug(f"Main config proxy providers: {getattr(main_config, 'proxy_providers', {})}")
|
|
||||||
log.debug(f"Available proxy provider configs: {list(getattr(main_config, 'proxy_providers', {}).keys())}")
|
|
||||||
|
|
||||||
# Use main_config instead of the service-specific config for proxy providers
|
|
||||||
proxy_config = getattr(main_config, "proxy_providers", {})
|
|
||||||
|
|
||||||
if proxy_config.get("basic"):
|
|
||||||
log.debug("Loading Basic proxy provider")
|
|
||||||
proxy_providers.append(Basic(**proxy_config["basic"]))
|
|
||||||
if proxy_config.get("nordvpn"):
|
|
||||||
log.debug("Loading NordVPN proxy provider")
|
|
||||||
proxy_providers.append(NordVPN(**proxy_config["nordvpn"]))
|
|
||||||
if proxy_config.get("surfsharkvpn"):
|
|
||||||
log.debug("Loading SurfsharkVPN proxy provider")
|
|
||||||
proxy_providers.append(SurfsharkVPN(**proxy_config["surfsharkvpn"]))
|
|
||||||
if hasattr(binaries, "HolaProxy") and binaries.HolaProxy:
|
|
||||||
log.debug("Loading Hola proxy provider")
|
|
||||||
proxy_providers.append(Hola())
|
|
||||||
|
|
||||||
for proxy_provider in proxy_providers:
|
|
||||||
log.info(f"Loaded {proxy_provider.__class__.__name__}: {proxy_provider}")
|
|
||||||
|
|
||||||
if not proxy_providers:
|
|
||||||
log.warning("No proxy providers were loaded. Check your proxy provider configuration in unshackle.yaml")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
log.warning(f"Failed to initialize some proxy providers: {e}")
|
|
||||||
|
|
||||||
return proxy_providers
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_proxy(proxy: str, proxy_providers: List[Any]) -> str:
|
|
||||||
"""Resolve proxy parameter to actual proxy URI."""
|
|
||||||
import re
|
|
||||||
|
|
||||||
if not proxy:
|
|
||||||
return proxy
|
|
||||||
|
|
||||||
# Check if explicit proxy URI
|
|
||||||
if re.match(r"^https?://", proxy):
|
|
||||||
return proxy
|
|
||||||
|
|
||||||
# Handle provider:country format (e.g., "nordvpn:us")
|
|
||||||
requested_provider = None
|
|
||||||
if re.match(r"^[a-z]+:.+$", proxy, re.IGNORECASE):
|
|
||||||
requested_provider, proxy = proxy.split(":", maxsplit=1)
|
|
||||||
|
|
||||||
# Handle country code format (e.g., "us", "uk")
|
|
||||||
if re.match(r"^[a-z]{2}(?:\d+)?$", proxy, re.IGNORECASE):
|
|
||||||
proxy = proxy.lower()
|
|
||||||
|
|
||||||
if requested_provider:
|
|
||||||
# Find specific provider (case-insensitive matching)
|
|
||||||
proxy_provider = next(
|
|
||||||
(x for x in proxy_providers if x.__class__.__name__.lower() == requested_provider.lower()),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
if not proxy_provider:
|
|
||||||
available_providers = [x.__class__.__name__ for x in proxy_providers]
|
|
||||||
raise ValueError(
|
|
||||||
f"The proxy provider '{requested_provider}' was not recognized. Available providers: {available_providers}"
|
|
||||||
)
|
|
||||||
|
|
||||||
proxy_uri = proxy_provider.get_proxy(proxy)
|
|
||||||
if not proxy_uri:
|
|
||||||
raise ValueError(f"The proxy provider {requested_provider} had no proxy for {proxy}")
|
|
||||||
|
|
||||||
log.info(f"Using {proxy_provider.__class__.__name__} Proxy: {proxy_uri}")
|
|
||||||
return proxy_uri
|
|
||||||
else:
|
|
||||||
# Try all providers
|
|
||||||
for proxy_provider in proxy_providers:
|
|
||||||
proxy_uri = proxy_provider.get_proxy(proxy)
|
|
||||||
if proxy_uri:
|
|
||||||
log.info(f"Using {proxy_provider.__class__.__name__} Proxy: {proxy_uri}")
|
|
||||||
return proxy_uri
|
|
||||||
|
|
||||||
raise ValueError(f"No proxy provider had a proxy for {proxy}")
|
|
||||||
|
|
||||||
# Return as-is if not recognized format
|
|
||||||
log.info(f"Using explicit Proxy: {proxy}")
|
|
||||||
return proxy
|
|
||||||
|
|
||||||
|
|
||||||
def validate_service(service_tag: str) -> Optional[str]:
|
def validate_service(service_tag: str) -> Optional[str]:
|
||||||
"""Validate and normalize service tag."""
|
"""Validate and normalize service tag."""
|
||||||
@@ -233,18 +139,6 @@ def _extract_manifests(tracks) -> List[Dict[str, Any]]:
|
|||||||
"data": base64.b64encode(xml_bytes).decode("ascii"),
|
"data": base64.b64encode(xml_bytes).decode("ascii"),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
elif track.data.get("hls"):
|
|
||||||
seen.add(manifest_url)
|
|
||||||
# m3u8 master playlist — serialize as text
|
|
||||||
hls_obj = track.data["hls"].get("playlist") or track.data["hls"].get("media")
|
|
||||||
if hls_obj and hasattr(hls_obj, "uri"):
|
|
||||||
manifests.append(
|
|
||||||
{
|
|
||||||
"type": "hls",
|
|
||||||
"url": manifest_url,
|
|
||||||
"data": base64.b64encode(manifest_url.encode()).decode("ascii"),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
elif track.data.get("ism") and track.data["ism"].get("manifest"):
|
elif track.data.get("ism") and track.data["ism"].get("manifest"):
|
||||||
seen.add(manifest_url)
|
seen.add(manifest_url)
|
||||||
xml_bytes = etree.tostring(track.data["ism"]["manifest"], xml_declaration=True, encoding="UTF-8")
|
xml_bytes = etree.tostring(track.data["ism"]["manifest"], xml_declaration=True, encoding="UTF-8")
|
||||||
@@ -1436,42 +1330,7 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Resolve proxy
|
proxy_param, proxy_providers = _resolve_handler_proxy(data, normalized_service)
|
||||||
proxy_param = data.get("proxy")
|
|
||||||
no_proxy = data.get("no_proxy", False)
|
|
||||||
proxy_providers: list = []
|
|
||||||
|
|
||||||
if not no_proxy:
|
|
||||||
proxy_providers = initialize_proxy_providers()
|
|
||||||
|
|
||||||
if proxy_param and not no_proxy:
|
|
||||||
try:
|
|
||||||
proxy_param = resolve_proxy(proxy_param, proxy_providers)
|
|
||||||
except ValueError as e:
|
|
||||||
raise APIError(
|
|
||||||
APIErrorCode.INVALID_PROXY,
|
|
||||||
f"Proxy error: {e}",
|
|
||||||
details={"proxy": data.get("proxy"), "service": normalized_service},
|
|
||||||
)
|
|
||||||
|
|
||||||
client_region = data.get("client_region")
|
|
||||||
if not proxy_param and not no_proxy and client_region and proxy_providers:
|
|
||||||
try:
|
|
||||||
from unshackle.core.utilities import get_cached_ip_info
|
|
||||||
|
|
||||||
server_ip_info = get_cached_ip_info(None)
|
|
||||||
server_region = server_ip_info.get("country", "").lower() if server_ip_info else None
|
|
||||||
except Exception:
|
|
||||||
server_region = None
|
|
||||||
|
|
||||||
if server_region and server_region == client_region.lower():
|
|
||||||
log.info(f"Server already in client region '{client_region}', no proxy needed")
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
proxy_param = resolve_proxy(client_region, proxy_providers)
|
|
||||||
log.info(f"Using server proxy for client region '{client_region}'")
|
|
||||||
except ValueError:
|
|
||||||
log.debug(f"No server proxy available for client region '{client_region}'")
|
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import uuid as uuid_mod
|
import uuid as uuid_mod
|
||||||
@@ -1812,6 +1671,209 @@ async def session_segments_handler(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_handler_proxy(
|
||||||
|
data: Dict[str, Any], normalized_service: str
|
||||||
|
) -> tuple[Optional[str], list]:
|
||||||
|
"""Resolve proxy and initialize providers from API request data.
|
||||||
|
|
||||||
|
Handles explicit proxy param, provider:country format, and
|
||||||
|
client_region-based auto-proxy when server region differs.
|
||||||
|
"""
|
||||||
|
proxy_param = data.get("proxy")
|
||||||
|
no_proxy = data.get("no_proxy", False)
|
||||||
|
proxy_providers: list = []
|
||||||
|
|
||||||
|
if not no_proxy:
|
||||||
|
proxy_providers = initialize_proxy_providers()
|
||||||
|
|
||||||
|
if proxy_param and not no_proxy:
|
||||||
|
try:
|
||||||
|
proxy_param = resolve_proxy(proxy_param, proxy_providers)
|
||||||
|
except ValueError as e:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.INVALID_PROXY,
|
||||||
|
f"Proxy error: {e}",
|
||||||
|
details={"proxy": data.get("proxy"), "service": normalized_service},
|
||||||
|
)
|
||||||
|
|
||||||
|
client_region = data.get("client_region")
|
||||||
|
if not proxy_param and not no_proxy and client_region and proxy_providers:
|
||||||
|
try:
|
||||||
|
from unshackle.core.utilities import get_cached_ip_info
|
||||||
|
|
||||||
|
server_ip_info = get_cached_ip_info(None)
|
||||||
|
server_region = server_ip_info.get("country", "").lower() if server_ip_info else None
|
||||||
|
except Exception:
|
||||||
|
server_region = None
|
||||||
|
|
||||||
|
if server_region and server_region == client_region.lower():
|
||||||
|
log.info(f"Server already in client region '{client_region}', no proxy needed")
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
proxy_param = resolve_proxy(client_region, proxy_providers)
|
||||||
|
log.info(f"Using server proxy for client region '{client_region}'")
|
||||||
|
except ValueError:
|
||||||
|
log.debug(f"No server proxy available for client region '{client_region}'")
|
||||||
|
|
||||||
|
return proxy_param, proxy_providers
|
||||||
|
|
||||||
|
|
||||||
|
def _find_title_for_track(track_id: str, session: Any) -> Any:
|
||||||
|
"""Find the title object that owns a given track."""
|
||||||
|
for t_id, tracks_dict in session.tracks_by_title.items():
|
||||||
|
if track_id in tracks_dict:
|
||||||
|
return session.title_map.get(t_id)
|
||||||
|
if session.title_map:
|
||||||
|
return next(iter(session.title_map.values()))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_pssh_from_track(track: Any, drm_type: str) -> Optional[str]:
|
||||||
|
"""Extract PSSH base64 string from a track's DRM objects."""
|
||||||
|
if not track.drm:
|
||||||
|
return None
|
||||||
|
pssh_b64 = None
|
||||||
|
for drm_obj in track.drm:
|
||||||
|
drm_class = drm_obj.__class__.__name__
|
||||||
|
if drm_class == "Widevine" and hasattr(drm_obj, "_pssh") and drm_obj._pssh:
|
||||||
|
if hasattr(drm_obj._pssh, "dumps"):
|
||||||
|
pssh_b64 = drm_obj._pssh.dumps()
|
||||||
|
if drm_type == "widevine":
|
||||||
|
break
|
||||||
|
elif drm_class == "PlayReady":
|
||||||
|
if hasattr(drm_obj, "data") and drm_obj.data.get("pssh_b64"):
|
||||||
|
pssh_b64 = drm_obj.data["pssh_b64"]
|
||||||
|
if drm_type == "playready":
|
||||||
|
break
|
||||||
|
return pssh_b64
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_track_drm(track: Any) -> None:
|
||||||
|
"""Extract DRM from manifest ContentProtection if track has none."""
|
||||||
|
if not track.drm and track.data.get("dash"):
|
||||||
|
from unshackle.core.manifests import DASH as DASHManifest
|
||||||
|
|
||||||
|
rep = track.data["dash"].get("representation")
|
||||||
|
ada = track.data["dash"].get("adaptation_set")
|
||||||
|
if rep is not None and ada is not None:
|
||||||
|
track.drm = DASHManifest.get_drm(
|
||||||
|
rep.findall("ContentProtection") + ada.findall("ContentProtection")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_device_name(user_config: dict, drm_type: str) -> str:
|
||||||
|
"""Get the configured device name for a DRM type from user config."""
|
||||||
|
if drm_type == "playready":
|
||||||
|
device_name = (user_config.get("playready_devices") or [None])[0]
|
||||||
|
if not device_name:
|
||||||
|
raise APIError(APIErrorCode.INVALID_INPUT, "No PlayReady device configured for this API key")
|
||||||
|
else:
|
||||||
|
device_name = (user_config.get("devices") or [None])[0]
|
||||||
|
if not device_name:
|
||||||
|
raise APIError(APIErrorCode.INVALID_INPUT, "No Widevine device configured for this API key")
|
||||||
|
return device_name
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_single_server_cdm(
|
||||||
|
service: Any,
|
||||||
|
title: Any,
|
||||||
|
track: Any,
|
||||||
|
pssh_b64: Optional[str],
|
||||||
|
drm_type: str,
|
||||||
|
request: Optional[web.Request],
|
||||||
|
) -> Dict[str, str]:
|
||||||
|
"""Handle single-track server_cdm licensing using the DRM class get_content_keys() flow."""
|
||||||
|
import base64
|
||||||
|
|
||||||
|
from unshackle.core.cdm import load_cdm
|
||||||
|
from unshackle.core.config import config as app_config
|
||||||
|
|
||||||
|
_ensure_track_drm(track)
|
||||||
|
|
||||||
|
if not pssh_b64:
|
||||||
|
pssh_b64 = _extract_pssh_from_track(track, drm_type)
|
||||||
|
if not pssh_b64:
|
||||||
|
raise APIError(APIErrorCode.INVALID_INPUT, "No PSSH available for server_cdm licensing")
|
||||||
|
|
||||||
|
api_key = request.headers.get("X-Secret-Key", "anonymous") if request else "anonymous"
|
||||||
|
user_config = app_config.serve.get("users", {}).get(api_key, {})
|
||||||
|
device_name = _resolve_device_name(user_config, drm_type)
|
||||||
|
cdm = load_cdm(device_name, service_name=service.__class__.__name__)
|
||||||
|
|
||||||
|
if drm_type == "playready":
|
||||||
|
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
||||||
|
|
||||||
|
from unshackle.core.drm import PlayReady
|
||||||
|
|
||||||
|
pr_pssh = PlayReadyPSSH(base64.b64decode(pssh_b64))
|
||||||
|
pr_drm = PlayReady(pssh=pr_pssh, pssh_b64=pssh_b64)
|
||||||
|
pr_drm.get_content_keys(
|
||||||
|
cdm=cdm,
|
||||||
|
certificate=lambda challenge, **_: None,
|
||||||
|
licence=lambda challenge, **_: service.get_playready_license(
|
||||||
|
challenge=challenge, title=title, track=track
|
||||||
|
),
|
||||||
|
)
|
||||||
|
keys = {kid.hex: key for kid, key in pr_drm.content_keys.items()}
|
||||||
|
elif drm_type == "widevine":
|
||||||
|
from pywidevine.pssh import PSSH as WvPSSH
|
||||||
|
|
||||||
|
from unshackle.core.drm import Widevine
|
||||||
|
|
||||||
|
wv_drm = Widevine(pssh=WvPSSH(pssh_b64))
|
||||||
|
wv_drm.get_content_keys(
|
||||||
|
cdm=cdm,
|
||||||
|
certificate=lambda challenge, **_: service.get_widevine_service_certificate(
|
||||||
|
challenge=challenge, title=title, track=track
|
||||||
|
),
|
||||||
|
licence=lambda challenge, **_: service.get_widevine_license(
|
||||||
|
challenge=challenge, title=title, track=track
|
||||||
|
),
|
||||||
|
)
|
||||||
|
keys = {kid.hex: key for kid, key in wv_drm.content_keys.items()}
|
||||||
|
else:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.INVALID_PARAMETERS,
|
||||||
|
f"Unsupported DRM type for server_cdm: {drm_type}",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not keys:
|
||||||
|
raise APIError(APIErrorCode.NO_CONTENT, "Server CDM returned no content keys")
|
||||||
|
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_proxy_license(
|
||||||
|
service: Any,
|
||||||
|
title: Any,
|
||||||
|
track: Any,
|
||||||
|
challenge_b64: Optional[str],
|
||||||
|
drm_type: str,
|
||||||
|
) -> web.Response:
|
||||||
|
"""Forward a client CDM challenge to the service license endpoint."""
|
||||||
|
import base64
|
||||||
|
|
||||||
|
if not challenge_b64:
|
||||||
|
raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: challenge")
|
||||||
|
challenge_bytes = base64.b64decode(challenge_b64)
|
||||||
|
|
||||||
|
if drm_type == "widevine":
|
||||||
|
license_response = service.get_widevine_license(challenge=challenge_bytes, title=title, track=track)
|
||||||
|
elif drm_type == "playready":
|
||||||
|
license_response = service.get_playready_license(challenge=challenge_bytes, title=title, track=track)
|
||||||
|
else:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.INVALID_PARAMETERS,
|
||||||
|
f"Unsupported DRM type: {drm_type}",
|
||||||
|
details={"drm_type": drm_type, "supported": ["widevine", "playready"]},
|
||||||
|
)
|
||||||
|
|
||||||
|
if isinstance(license_response, str):
|
||||||
|
license_response = license_response.encode("utf-8")
|
||||||
|
|
||||||
|
return web.json_response({"license": base64.b64encode(license_response).decode("ascii")})
|
||||||
|
|
||||||
|
|
||||||
async def session_license_handler(
|
async def session_license_handler(
|
||||||
data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None
|
data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None
|
||||||
) -> web.Response:
|
) -> web.Response:
|
||||||
@@ -1844,13 +1906,13 @@ async def session_license_handler(
|
|||||||
mode = data.get("mode", "proxy")
|
mode = data.get("mode", "proxy")
|
||||||
|
|
||||||
if mode == "server_cdm" and track_ids:
|
if mode == "server_cdm" and track_ids:
|
||||||
import base64
|
|
||||||
|
|
||||||
from unshackle.core.config import config as app_config
|
from unshackle.core.config import config as app_config
|
||||||
|
|
||||||
api_key = request.headers.get("X-Secret-Key", "anonymous") if request else "anonymous"
|
api_key = request.headers.get("X-Secret-Key", "anonymous") if request else "anonymous"
|
||||||
user_config = app_config.serve.get("users", {}).get(api_key, {})
|
user_config = app_config.serve.get("users", {}).get(api_key, {})
|
||||||
service = session.service_instance
|
service = session.service_instance
|
||||||
|
has_wv_device = bool(user_config.get("devices"))
|
||||||
|
has_pr_device = bool(user_config.get("playready_devices"))
|
||||||
|
|
||||||
all_keys: Dict[str, Dict[str, str]] = {}
|
all_keys: Dict[str, Dict[str, str]] = {}
|
||||||
seen_pssh: set[str] = set()
|
seen_pssh: set[str] = set()
|
||||||
@@ -1860,69 +1922,39 @@ async def session_license_handler(
|
|||||||
if not track:
|
if not track:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# If track has no DRM yet, extract it from manifest ContentProtection
|
_ensure_track_drm(track)
|
||||||
if not track.drm and track.data.get("dash"):
|
|
||||||
from unshackle.core.manifests import DASH as DASHManifest
|
|
||||||
|
|
||||||
rep = track.data["dash"].get("representation")
|
|
||||||
ada = track.data["dash"].get("adaptation_set")
|
|
||||||
if rep is not None and ada is not None:
|
|
||||||
track.drm = DASHManifest.get_drm(
|
|
||||||
rep.findall("ContentProtection") + ada.findall("ContentProtection")
|
|
||||||
)
|
|
||||||
|
|
||||||
if not track.drm:
|
if not track.drm:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
title = None
|
title = _find_title_for_track(tid, session)
|
||||||
for t_id, tracks_dict in session.tracks_by_title.items():
|
|
||||||
if tid in tracks_dict:
|
|
||||||
title = session.title_map.get(t_id)
|
|
||||||
break
|
|
||||||
if title is None and session.title_map:
|
|
||||||
title = next(iter(session.title_map.values()))
|
|
||||||
|
|
||||||
has_wv_device = bool(user_config.get("devices"))
|
# Detect DRM type and extract PSSH based on available devices
|
||||||
has_pr_device = bool(user_config.get("playready_devices"))
|
|
||||||
pssh_str = None
|
|
||||||
track_drm_type = None
|
track_drm_type = None
|
||||||
|
pssh_str = None
|
||||||
if has_wv_device:
|
if has_wv_device:
|
||||||
for drm_obj in track.drm:
|
pssh_str = _extract_pssh_from_track(track, "widevine")
|
||||||
if drm_obj.__class__.__name__ == "Widevine" and hasattr(drm_obj, "_pssh") and drm_obj._pssh:
|
if pssh_str:
|
||||||
pssh_str = drm_obj._pssh.dumps() if hasattr(drm_obj._pssh, "dumps") else None
|
track_drm_type = "widevine"
|
||||||
track_drm_type = "widevine"
|
|
||||||
break
|
|
||||||
if not pssh_str and has_pr_device:
|
if not pssh_str and has_pr_device:
|
||||||
for drm_obj in track.drm:
|
pssh_str = _extract_pssh_from_track(track, "playready")
|
||||||
if drm_obj.__class__.__name__ == "PlayReady" and hasattr(drm_obj, "data"):
|
if pssh_str:
|
||||||
pssh_str = drm_obj.data.get("pssh_b64")
|
track_drm_type = "playready"
|
||||||
track_drm_type = "playready"
|
|
||||||
break
|
|
||||||
|
|
||||||
if not pssh_str or pssh_str in seen_pssh:
|
if not pssh_str or not track_drm_type:
|
||||||
if pssh_str in seen_pssh:
|
continue
|
||||||
for prev_tid, prev_keys in all_keys.items():
|
|
||||||
if prev_keys:
|
if pssh_str in seen_pssh:
|
||||||
all_keys[tid] = prev_keys
|
for prev_keys in all_keys.values():
|
||||||
break
|
if prev_keys:
|
||||||
|
all_keys[tid] = prev_keys
|
||||||
|
break
|
||||||
continue
|
continue
|
||||||
seen_pssh.add(pssh_str)
|
seen_pssh.add(pssh_str)
|
||||||
|
|
||||||
if not track_drm_type:
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
single_data = {
|
keys = _handle_single_server_cdm(service, title, track, pssh_str, track_drm_type, request)
|
||||||
"track_id": tid,
|
if keys:
|
||||||
"drm_type": track_drm_type,
|
all_keys[tid] = keys
|
||||||
"mode": "server_cdm",
|
|
||||||
"pssh": pssh_str,
|
|
||||||
}
|
|
||||||
single_resp = await session_license_handler(single_data, session_id, request)
|
|
||||||
resp_json = __import__("json").loads(single_resp.body)
|
|
||||||
if resp_json.get("keys"):
|
|
||||||
all_keys[tid] = resp_json["keys"]
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning(f"Failed to resolve keys for track {tid[:12]}: {e}")
|
log.warning(f"Failed to resolve keys for track {tid[:12]}: {e}")
|
||||||
|
|
||||||
@@ -1940,16 +1972,7 @@ async def session_license_handler(
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
title = None
|
title = _find_title_for_track(track_id, session)
|
||||||
for tid, tracks_dict in session.tracks_by_title.items():
|
|
||||||
if track_id in tracks_dict:
|
|
||||||
title = session.title_map.get(tid)
|
|
||||||
break
|
|
||||||
|
|
||||||
if title is None:
|
|
||||||
if session.title_map:
|
|
||||||
title = next(iter(session.title_map.values()))
|
|
||||||
|
|
||||||
service = session.service_instance
|
service = session.service_instance
|
||||||
|
|
||||||
pssh_b64 = data.get("pssh")
|
pssh_b64 = data.get("pssh")
|
||||||
@@ -1975,232 +1998,11 @@ async def session_license_handler(
|
|||||||
track.drm.append(wv_drm)
|
track.drm.append(wv_drm)
|
||||||
|
|
||||||
if mode == "server_cdm":
|
if mode == "server_cdm":
|
||||||
if not track.drm and track.data.get("dash"):
|
keys = _handle_single_server_cdm(service, title, track, pssh_b64, drm_type, request)
|
||||||
from unshackle.core.manifests import DASH as DASHManifest
|
|
||||||
|
|
||||||
rep = track.data["dash"].get("representation")
|
|
||||||
ada = track.data["dash"].get("adaptation_set")
|
|
||||||
if rep is not None and ada is not None:
|
|
||||||
track.drm = DASHManifest.get_drm(
|
|
||||||
rep.findall("ContentProtection") + ada.findall("ContentProtection")
|
|
||||||
)
|
|
||||||
|
|
||||||
if not pssh_b64 and track.drm:
|
|
||||||
for drm_obj in track.drm:
|
|
||||||
drm_class = drm_obj.__class__.__name__
|
|
||||||
if drm_class == "Widevine" and hasattr(drm_obj, "_pssh") and drm_obj._pssh:
|
|
||||||
if hasattr(drm_obj._pssh, "dumps"):
|
|
||||||
pssh_b64 = drm_obj._pssh.dumps()
|
|
||||||
if drm_type == "widevine":
|
|
||||||
break
|
|
||||||
elif drm_class == "PlayReady":
|
|
||||||
if hasattr(drm_obj, "data") and drm_obj.data.get("pssh_b64"):
|
|
||||||
pssh_b64 = drm_obj.data["pssh_b64"]
|
|
||||||
if drm_type == "playready":
|
|
||||||
break
|
|
||||||
|
|
||||||
if not pssh_b64:
|
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "No PSSH available for server_cdm licensing")
|
|
||||||
|
|
||||||
from unshackle.core.config import config as app_config
|
|
||||||
|
|
||||||
api_key = request.headers.get("X-Secret-Key", "anonymous") if request else "anonymous"
|
|
||||||
user_config = app_config.serve.get("users", {}).get(api_key, {})
|
|
||||||
|
|
||||||
if drm_type == "playready":
|
|
||||||
from pyplayready.cdm import Cdm as PlayReadyCdm
|
|
||||||
from pyplayready.device import Device as PlayReadyDevice
|
|
||||||
from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm
|
|
||||||
|
|
||||||
device_name = (user_config.get("playready_devices") or [None])[0]
|
|
||||||
if not device_name:
|
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "No PlayReady device configured for this API key")
|
|
||||||
|
|
||||||
cdm_api = next((x.copy() for x in app_config.remote_cdm if x.get("name") == device_name), None)
|
|
||||||
if cdm_api:
|
|
||||||
cdm_type_api = cdm_api.get("type")
|
|
||||||
if cdm_type_api == "decrypt_labs":
|
|
||||||
from unshackle.core.cdm import DecryptLabsRemoteCDM
|
|
||||||
del cdm_api["name"]
|
|
||||||
del cdm_api["type"]
|
|
||||||
if "secret" not in cdm_api or not cdm_api["secret"]:
|
|
||||||
if app_config.decrypt_labs_api_key:
|
|
||||||
cdm_api["secret"] = app_config.decrypt_labs_api_key
|
|
||||||
cdm = DecryptLabsRemoteCDM(service_name=service.__class__.__name__, **cdm_api)
|
|
||||||
elif cdm_type_api == "custom_api":
|
|
||||||
from unshackle.core.cdm import CustomRemoteCDM
|
|
||||||
del cdm_api["name"]
|
|
||||||
del cdm_api["type"]
|
|
||||||
cdm = CustomRemoteCDM(service_name=service.__class__.__name__, **cdm_api)
|
|
||||||
else:
|
|
||||||
device_type = cdm_api.get("Device Type", cdm_api.get("device_type", ""))
|
|
||||||
if str(device_type).upper() == "PLAYREADY":
|
|
||||||
cdm = PlayReadyRemoteCdm(
|
|
||||||
security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3000)),
|
|
||||||
host=cdm_api.get("Host", cdm_api.get("host")),
|
|
||||||
secret=cdm_api.get("Secret", cdm_api.get("secret")),
|
|
||||||
device_name=cdm_api.get("Device Name", cdm_api.get("device_name")),
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
raise APIError(
|
|
||||||
APIErrorCode.INVALID_INPUT,
|
|
||||||
f"CDM '{device_name}' is not a PlayReady device",
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
prd_path = app_config.directories.prds / f"{device_name}.prd"
|
|
||||||
if not prd_path.exists():
|
|
||||||
prd_path = app_config.directories.wvds / f"{device_name}.prd"
|
|
||||||
if not prd_path.exists():
|
|
||||||
raise APIError(
|
|
||||||
APIErrorCode.INVALID_INPUT,
|
|
||||||
f"PlayReady device '{device_name}' not found",
|
|
||||||
)
|
|
||||||
cdm = PlayReadyCdm.from_device(PlayReadyDevice.load(prd_path))
|
|
||||||
|
|
||||||
pr_pssh = PlayReadyPSSH(base64.b64decode(pssh_b64))
|
|
||||||
wrm_header = pr_pssh.wrm_headers[0]
|
|
||||||
session_id_cdm = cdm.open()
|
|
||||||
try:
|
|
||||||
challenge = cdm.get_license_challenge(session_id_cdm, wrm_header)
|
|
||||||
license_response = service.get_playready_license(
|
|
||||||
challenge=challenge,
|
|
||||||
title=title,
|
|
||||||
track=track,
|
|
||||||
)
|
|
||||||
if isinstance(license_response, bytes):
|
|
||||||
license_str = license_response.decode(errors="ignore")
|
|
||||||
else:
|
|
||||||
license_str = str(license_response)
|
|
||||||
if "<License>" not in license_str:
|
|
||||||
try:
|
|
||||||
license_str = base64.b64decode(license_str + "===").decode()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
cdm.parse_license(session_id_cdm, license_str)
|
|
||||||
keys = {}
|
|
||||||
for key in cdm.get_keys(session_id_cdm):
|
|
||||||
kid = getattr(key, "key_id", None) or getattr(key, "kid", None)
|
|
||||||
key_val = getattr(key, "key", None)
|
|
||||||
if kid and key_val:
|
|
||||||
kid_hex = kid.hex if hasattr(kid, "hex") else str(kid).replace("-", "")
|
|
||||||
key_hex = key_val.hex() if hasattr(key_val, "hex") else str(key_val)
|
|
||||||
keys[kid_hex] = key_hex
|
|
||||||
finally:
|
|
||||||
cdm.close(session_id_cdm)
|
|
||||||
|
|
||||||
elif drm_type == "widevine":
|
|
||||||
from pywidevine.cdm import Cdm as WidevineCdm
|
|
||||||
from pywidevine.device import Device as WidevineDevice
|
|
||||||
from pywidevine.pssh import PSSH as WvPSSH
|
|
||||||
from pywidevine.remotecdm import RemoteCdm as WidevineRemoteCdm
|
|
||||||
|
|
||||||
device_name = (user_config.get("devices") or [None])[0]
|
|
||||||
if not device_name:
|
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "No Widevine device configured for this API key")
|
|
||||||
|
|
||||||
cdm_api = next((x.copy() for x in app_config.remote_cdm if x.get("name") == device_name), None)
|
|
||||||
if cdm_api:
|
|
||||||
cdm_type_api = cdm_api.get("type")
|
|
||||||
if cdm_type_api == "decrypt_labs":
|
|
||||||
from unshackle.core.cdm import DecryptLabsRemoteCDM
|
|
||||||
del cdm_api["name"]
|
|
||||||
del cdm_api["type"]
|
|
||||||
if "secret" not in cdm_api or not cdm_api["secret"]:
|
|
||||||
if app_config.decrypt_labs_api_key:
|
|
||||||
cdm_api["secret"] = app_config.decrypt_labs_api_key
|
|
||||||
cdm = DecryptLabsRemoteCDM(service_name=service.__class__.__name__, **cdm_api)
|
|
||||||
elif cdm_type_api == "custom_api":
|
|
||||||
from unshackle.core.cdm import CustomRemoteCDM
|
|
||||||
del cdm_api["name"]
|
|
||||||
del cdm_api["type"]
|
|
||||||
cdm = CustomRemoteCDM(service_name=service.__class__.__name__, **cdm_api)
|
|
||||||
else:
|
|
||||||
cdm = WidevineRemoteCdm(
|
|
||||||
device_type=cdm_api.get("Device Type", cdm_api.get("device_type", "")),
|
|
||||||
system_id=cdm_api.get("System ID", cdm_api.get("system_id", "")),
|
|
||||||
security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3)),
|
|
||||||
host=cdm_api.get("Host", cdm_api.get("host")),
|
|
||||||
secret=cdm_api.get("Secret", cdm_api.get("secret")),
|
|
||||||
device_name=cdm_api.get("Device Name", cdm_api.get("device_name")),
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
wvd_path = app_config.directories.wvds / f"{device_name}.wvd"
|
|
||||||
if not wvd_path.exists():
|
|
||||||
raise APIError(
|
|
||||||
APIErrorCode.INVALID_INPUT,
|
|
||||||
f"Widevine device '{device_name}' not found",
|
|
||||||
)
|
|
||||||
cdm = WidevineCdm.from_device(WidevineDevice.load(wvd_path))
|
|
||||||
|
|
||||||
wv_pssh = WvPSSH(pssh_b64)
|
|
||||||
session_id_cdm = cdm.open()
|
|
||||||
try:
|
|
||||||
if hasattr(cdm, "service_certificate_challenge"):
|
|
||||||
try:
|
|
||||||
cert = service.get_widevine_service_certificate(
|
|
||||||
challenge=cdm.service_certificate_challenge,
|
|
||||||
title=title,
|
|
||||||
track=track,
|
|
||||||
)
|
|
||||||
if cert and hasattr(cdm, "set_service_certificate"):
|
|
||||||
cdm.set_service_certificate(session_id_cdm, cert)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
challenge = cdm.get_license_challenge(session_id_cdm, wv_pssh)
|
|
||||||
license_response = service.get_widevine_license(
|
|
||||||
challenge=challenge,
|
|
||||||
title=title,
|
|
||||||
track=track,
|
|
||||||
)
|
|
||||||
cdm.parse_license(session_id_cdm, license_response)
|
|
||||||
keys = {key.kid.hex: key.key.hex() for key in cdm.get_keys(session_id_cdm, "CONTENT")}
|
|
||||||
finally:
|
|
||||||
cdm.close(session_id_cdm)
|
|
||||||
else:
|
|
||||||
raise APIError(
|
|
||||||
APIErrorCode.INVALID_PARAMETERS,
|
|
||||||
f"Unsupported DRM type for server_cdm: {drm_type}",
|
|
||||||
)
|
|
||||||
|
|
||||||
if not keys:
|
|
||||||
raise APIError(APIErrorCode.NO_CONTENT, "Server CDM returned no content keys")
|
|
||||||
|
|
||||||
log.info(f"Server CDM resolved {len(keys)} key(s) for track {track_id[:12]}")
|
log.info(f"Server CDM resolved {len(keys)} key(s) for track {track_id[:12]}")
|
||||||
return web.json_response({"keys": keys})
|
return web.json_response({"keys": keys})
|
||||||
|
|
||||||
if not challenge_b64:
|
return _handle_proxy_license(service, title, track, challenge_b64, drm_type)
|
||||||
raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: challenge")
|
|
||||||
challenge_bytes = base64.b64decode(challenge_b64)
|
|
||||||
|
|
||||||
if drm_type == "widevine":
|
|
||||||
license_response = service.get_widevine_license(
|
|
||||||
challenge=challenge_bytes,
|
|
||||||
title=title,
|
|
||||||
track=track,
|
|
||||||
)
|
|
||||||
elif drm_type == "playready":
|
|
||||||
license_response = service.get_playready_license(
|
|
||||||
challenge=challenge_bytes,
|
|
||||||
title=title,
|
|
||||||
track=track,
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
raise APIError(
|
|
||||||
APIErrorCode.INVALID_PARAMETERS,
|
|
||||||
f"Unsupported DRM type: {drm_type}",
|
|
||||||
details={"drm_type": drm_type, "supported": ["widevine", "playready"]},
|
|
||||||
)
|
|
||||||
|
|
||||||
# Ensure response is bytes for base64 encoding
|
|
||||||
if isinstance(license_response, str):
|
|
||||||
license_response = license_response.encode("utf-8")
|
|
||||||
|
|
||||||
return web.json_response(
|
|
||||||
{
|
|
||||||
"license": base64.b64encode(license_response).decode("ascii"),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
except APIError:
|
except APIError:
|
||||||
raise
|
raise
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ __all__ = [
|
|||||||
"DecryptLabsRemoteCDM",
|
"DecryptLabsRemoteCDM",
|
||||||
"CustomRemoteCDM",
|
"CustomRemoteCDM",
|
||||||
"MonaLisaCDM",
|
"MonaLisaCDM",
|
||||||
|
"load_cdm",
|
||||||
"is_remote_cdm",
|
"is_remote_cdm",
|
||||||
"is_local_cdm",
|
"is_local_cdm",
|
||||||
"cdm_location",
|
"cdm_location",
|
||||||
@@ -36,6 +37,10 @@ def __getattr__(name: str) -> Any:
|
|||||||
from .monalisa import MonaLisaCDM
|
from .monalisa import MonaLisaCDM
|
||||||
|
|
||||||
return MonaLisaCDM
|
return MonaLisaCDM
|
||||||
|
if name == "load_cdm":
|
||||||
|
from .loader import load_cdm
|
||||||
|
|
||||||
|
return load_cdm
|
||||||
|
|
||||||
if name in {
|
if name in {
|
||||||
"is_remote_cdm",
|
"is_remote_cdm",
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""Shared CDM loading utility.
|
||||||
|
|
||||||
|
Instantiates a CDM object (local or remote) given a resolved device name.
|
||||||
|
Name resolution (quality-based, profile-based, DRM-type) is the caller's
|
||||||
|
responsibility — this module only handles the instantiation step.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
log = logging.getLogger("cdm")
|
||||||
|
|
||||||
|
|
||||||
|
def load_cdm(
|
||||||
|
cdm_name: str,
|
||||||
|
*,
|
||||||
|
service_name: str = "",
|
||||||
|
vaults: Optional[Any] = None,
|
||||||
|
) -> Any:
|
||||||
|
"""Instantiate a CDM by device name.
|
||||||
|
|
||||||
|
Looks up the name in config.remote_cdm first (for remote/API CDMs),
|
||||||
|
then falls back to local .prd / .wvd files.
|
||||||
|
|
||||||
|
Returns a CDM object (WidevineCdm, PlayReadyCdm, RemoteCdm,
|
||||||
|
DecryptLabsRemoteCDM, CustomRemoteCDM, or PlayReadyRemoteCdm).
|
||||||
|
|
||||||
|
Raises ValueError if the device cannot be found or loaded.
|
||||||
|
"""
|
||||||
|
from unshackle.core.config import config
|
||||||
|
|
||||||
|
cdm_api = next(iter(x.copy() for x in config.remote_cdm if x["name"] == cdm_name), None)
|
||||||
|
if cdm_api:
|
||||||
|
return _load_remote_cdm(cdm_api, cdm_name, service_name, vaults)
|
||||||
|
|
||||||
|
return _load_local_cdm(cdm_name)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_remote_cdm(
|
||||||
|
cdm_api: dict,
|
||||||
|
cdm_name: str,
|
||||||
|
service_name: str,
|
||||||
|
vaults: Optional[Any],
|
||||||
|
) -> Any:
|
||||||
|
"""Instantiate a remote CDM from a config.remote_cdm entry."""
|
||||||
|
from unshackle.core.config import config
|
||||||
|
|
||||||
|
cdm_type = cdm_api.get("type")
|
||||||
|
|
||||||
|
if cdm_type == "decrypt_labs":
|
||||||
|
from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM
|
||||||
|
|
||||||
|
del cdm_api["name"]
|
||||||
|
del cdm_api["type"]
|
||||||
|
|
||||||
|
if "secret" not in cdm_api or not cdm_api["secret"]:
|
||||||
|
if config.decrypt_labs_api_key:
|
||||||
|
cdm_api["secret"] = config.decrypt_labs_api_key
|
||||||
|
else:
|
||||||
|
raise ValueError(
|
||||||
|
f"No secret provided for DecryptLabs CDM '{cdm_name}' and no global "
|
||||||
|
"decrypt_labs_api_key configured"
|
||||||
|
)
|
||||||
|
|
||||||
|
return DecryptLabsRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api)
|
||||||
|
|
||||||
|
if cdm_type == "custom_api":
|
||||||
|
from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM
|
||||||
|
|
||||||
|
del cdm_api["name"]
|
||||||
|
del cdm_api["type"]
|
||||||
|
return CustomRemoteCDM(service_name=service_name, vaults=vaults, **cdm_api)
|
||||||
|
|
||||||
|
device_type = cdm_api.get("Device Type", cdm_api.get("device_type", ""))
|
||||||
|
if str(device_type).upper() == "PLAYREADY":
|
||||||
|
from pyplayready.remote.remotecdm import RemoteCdm as PlayReadyRemoteCdm
|
||||||
|
|
||||||
|
return PlayReadyRemoteCdm(
|
||||||
|
security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3000)),
|
||||||
|
host=cdm_api.get("Host", cdm_api.get("host")),
|
||||||
|
secret=cdm_api.get("Secret", cdm_api.get("secret")),
|
||||||
|
device_name=cdm_api.get("Device Name", cdm_api.get("device_name")),
|
||||||
|
)
|
||||||
|
|
||||||
|
from pywidevine.remotecdm import RemoteCdm
|
||||||
|
|
||||||
|
return RemoteCdm(
|
||||||
|
device_type=cdm_api.get("Device Type", cdm_api.get("device_type", "")),
|
||||||
|
system_id=cdm_api.get("System ID", cdm_api.get("system_id", "")),
|
||||||
|
security_level=cdm_api.get("Security Level", cdm_api.get("security_level", 3000)),
|
||||||
|
host=cdm_api.get("Host", cdm_api.get("host")),
|
||||||
|
secret=cdm_api.get("Secret", cdm_api.get("secret")),
|
||||||
|
device_name=cdm_api.get("Device Name", cdm_api.get("device_name")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_local_cdm(cdm_name: str) -> Any:
|
||||||
|
"""Instantiate a local CDM from a .prd or .wvd file."""
|
||||||
|
from unshackle.core.config import config
|
||||||
|
|
||||||
|
prd_path = config.directories.prds / f"{cdm_name}.prd"
|
||||||
|
if not prd_path.is_file():
|
||||||
|
prd_path = config.directories.wvds / f"{cdm_name}.prd"
|
||||||
|
if prd_path.is_file():
|
||||||
|
from pyplayready.cdm import Cdm as PlayReadyCdm
|
||||||
|
from pyplayready.device import Device as PlayReadyDevice
|
||||||
|
|
||||||
|
return PlayReadyCdm.from_device(PlayReadyDevice.load(prd_path))
|
||||||
|
|
||||||
|
cdm_path = config.directories.wvds / f"{cdm_name}.wvd"
|
||||||
|
if not cdm_path.is_file():
|
||||||
|
raise ValueError(f"{cdm_name} does not exist or is not a file")
|
||||||
|
|
||||||
|
from construct import ConstError
|
||||||
|
from pywidevine.cdm import Cdm as WidevineCdm
|
||||||
|
from pywidevine.device import Device
|
||||||
|
|
||||||
|
try:
|
||||||
|
device = Device.load(cdm_path)
|
||||||
|
except ConstError as e:
|
||||||
|
if "expected 2 but parsed 1" in str(e):
|
||||||
|
raise ValueError(
|
||||||
|
f"{cdm_name}.wvd seems to be a v1 WVD file, use `pywidevine migrate --help` to migrate it to v2."
|
||||||
|
)
|
||||||
|
raise ValueError(f"{cdm_name}.wvd is an invalid or corrupt Widevine Device file, {e}")
|
||||||
|
|
||||||
|
return WidevineCdm.from_device(device)
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""Shared proxy provider initialization and resolution.
|
||||||
|
|
||||||
|
Used by both the REST API handlers and the remote service client.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
|
log = logging.getLogger("proxies")
|
||||||
|
|
||||||
|
|
||||||
|
def initialize_proxy_providers() -> List[Any]:
|
||||||
|
"""Initialize and return available proxy providers from config."""
|
||||||
|
proxy_providers: list = []
|
||||||
|
try:
|
||||||
|
from unshackle.core import binaries
|
||||||
|
from unshackle.core.config import config as main_config
|
||||||
|
from unshackle.core.proxies.basic import Basic
|
||||||
|
from unshackle.core.proxies.hola import Hola
|
||||||
|
from unshackle.core.proxies.nordvpn import NordVPN
|
||||||
|
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
|
||||||
|
|
||||||
|
proxy_config = getattr(main_config, "proxy_providers", {})
|
||||||
|
|
||||||
|
if proxy_config.get("basic"):
|
||||||
|
proxy_providers.append(Basic(**proxy_config["basic"]))
|
||||||
|
if proxy_config.get("nordvpn"):
|
||||||
|
proxy_providers.append(NordVPN(**proxy_config["nordvpn"]))
|
||||||
|
if proxy_config.get("surfsharkvpn"):
|
||||||
|
proxy_providers.append(SurfsharkVPN(**proxy_config["surfsharkvpn"]))
|
||||||
|
if hasattr(binaries, "HolaProxy") and binaries.HolaProxy:
|
||||||
|
proxy_providers.append(Hola())
|
||||||
|
|
||||||
|
for provider in proxy_providers:
|
||||||
|
log.info(f"Loaded {provider.__class__.__name__}: {provider}")
|
||||||
|
|
||||||
|
if not proxy_providers:
|
||||||
|
log.warning("No proxy providers were loaded. Check your proxy provider configuration in unshackle.yaml")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
log.warning(f"Failed to initialize some proxy providers: {e}")
|
||||||
|
|
||||||
|
return proxy_providers
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_proxy(proxy: str, proxy_providers: List[Any]) -> Optional[str]:
|
||||||
|
"""Resolve a proxy parameter to an actual proxy URI.
|
||||||
|
|
||||||
|
Accepts:
|
||||||
|
- Direct URI: "https://...", "socks5://..."
|
||||||
|
- Country code: "us", "uk"
|
||||||
|
- Provider:country: "nordvpn:us"
|
||||||
|
"""
|
||||||
|
if not proxy:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if re.match(r"^(https?://|socks)", proxy):
|
||||||
|
return proxy
|
||||||
|
|
||||||
|
requested_provider = None
|
||||||
|
query = proxy
|
||||||
|
if re.match(r"^[a-z]+:.+$", proxy, re.IGNORECASE):
|
||||||
|
requested_provider, query = proxy.split(":", maxsplit=1)
|
||||||
|
|
||||||
|
if requested_provider:
|
||||||
|
provider = next(
|
||||||
|
(x for x in proxy_providers if x.__class__.__name__.lower() == requested_provider.lower()),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if not provider:
|
||||||
|
available = [x.__class__.__name__ for x in proxy_providers]
|
||||||
|
raise ValueError(f"Proxy provider '{requested_provider}' not found. Available: {available}")
|
||||||
|
proxy_uri = provider.get_proxy(query)
|
||||||
|
if not proxy_uri:
|
||||||
|
raise ValueError(f"Proxy provider {requested_provider} had no proxy for {query}")
|
||||||
|
log.info(f"Using {provider.__class__.__name__} Proxy: {proxy_uri}")
|
||||||
|
return proxy_uri
|
||||||
|
|
||||||
|
for provider in proxy_providers:
|
||||||
|
proxy_uri = provider.get_proxy(query)
|
||||||
|
if proxy_uri:
|
||||||
|
log.info(f"Using {provider.__class__.__name__} Proxy: {proxy_uri}")
|
||||||
|
return proxy_uri
|
||||||
|
|
||||||
|
raise ValueError(f"No proxy provider had a proxy for {proxy}")
|
||||||
@@ -9,7 +9,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import base64
|
import base64
|
||||||
import logging
|
import logging
|
||||||
import re
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from http.cookiejar import CookieJar
|
from http.cookiejar import CookieJar
|
||||||
from typing import Any, Dict, Optional, Union
|
from typing import Any, Dict, Optional, Union
|
||||||
@@ -94,7 +93,6 @@ def _deserialize_video(data: Dict[str, Any]) -> Video:
|
|||||||
fps=data.get("fps"),
|
fps=data.get("fps"),
|
||||||
id_=data.get("id"),
|
id_=data.get("id"),
|
||||||
)
|
)
|
||||||
v.data["remote"] = True
|
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
@@ -110,7 +108,6 @@ def _deserialize_audio(data: Dict[str, Any]) -> Audio:
|
|||||||
descriptive=data.get("descriptive", False),
|
descriptive=data.get("descriptive", False),
|
||||||
id_=data.get("id"),
|
id_=data.get("id"),
|
||||||
)
|
)
|
||||||
a.data["remote"] = True
|
|
||||||
return a
|
return a
|
||||||
|
|
||||||
|
|
||||||
@@ -210,46 +207,30 @@ def _resolve_manifest_data(tracks: Tracks, manifests: list, session: Any) -> Non
|
|||||||
from unshackle.core.manifests import DASH
|
from unshackle.core.manifests import DASH
|
||||||
|
|
||||||
xml_tree = etree.fromstring(raw)
|
xml_tree = etree.fromstring(raw)
|
||||||
dash = DASH(xml_tree, m_url)
|
|
||||||
fallback_lang = next(
|
fallback_lang = next(
|
||||||
(t.language for t in all_tracks if t.language and str(t.language) != "und"),
|
(t.language for t in all_tracks if t.language and str(t.language) != "und"),
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
local_tracks = dash.to_tracks(language=fallback_lang)
|
local_tracks = DASH(xml_tree, m_url).to_tracks(language=fallback_lang)
|
||||||
local_all = list(local_tracks.videos) + list(local_tracks.audio) + list(local_tracks.subtitles)
|
|
||||||
|
|
||||||
for remote_track in all_tracks:
|
|
||||||
if remote_track.data.get("dash"):
|
|
||||||
continue
|
|
||||||
matched = _match_track(remote_track, local_all)
|
|
||||||
if matched and matched.data.get("dash"):
|
|
||||||
remote_track.data.update(matched.data)
|
|
||||||
remote_track.descriptor = matched.descriptor
|
|
||||||
if matched.drm and not remote_track.drm:
|
|
||||||
remote_track.drm = matched.drm
|
|
||||||
|
|
||||||
elif m_type == "hls":
|
|
||||||
pass
|
|
||||||
|
|
||||||
elif m_type == "ism":
|
elif m_type == "ism":
|
||||||
from lxml import etree
|
from lxml import etree
|
||||||
|
|
||||||
from unshackle.core.manifests import ISM
|
from unshackle.core.manifests import ISM
|
||||||
|
|
||||||
xml_el = etree.fromstring(raw)
|
local_tracks = ISM(etree.fromstring(raw), m_url).to_tracks()
|
||||||
ism = ISM(xml_el, m_url)
|
else:
|
||||||
local_tracks = ism.to_tracks()
|
continue
|
||||||
local_all = list(local_tracks.videos) + list(local_tracks.audio) + list(local_tracks.subtitles)
|
|
||||||
|
|
||||||
for remote_track in all_tracks:
|
local_all = list(local_tracks.videos) + list(local_tracks.audio) + list(local_tracks.subtitles)
|
||||||
if remote_track.data.get("ism"):
|
for remote_track in all_tracks:
|
||||||
continue
|
if remote_track.data.get(m_type):
|
||||||
matched = _match_track(remote_track, local_all)
|
continue
|
||||||
if matched and matched.data.get("ism"):
|
matched = _match_track(remote_track, local_all)
|
||||||
remote_track.data.update(matched.data)
|
if matched and matched.data.get(m_type):
|
||||||
remote_track.descriptor = matched.descriptor
|
remote_track.data.update(matched.data)
|
||||||
if matched.drm and not remote_track.drm:
|
remote_track.descriptor = matched.descriptor
|
||||||
remote_track.drm = matched.drm
|
if matched.drm and not remote_track.drm:
|
||||||
|
remote_track.drm = matched.drm
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log_m.warning("Failed to re-parse %s manifest from %s: %s", m_type, m_url, e)
|
log_m.warning("Failed to re-parse %s manifest from %s: %s", m_type, m_url, e)
|
||||||
@@ -358,44 +339,14 @@ def _load_cookies_for_transport(service_tag: str, profile: Optional[str]) -> Opt
|
|||||||
def _resolve_proxy(proxy_arg: Optional[str]) -> Optional[str]:
|
def _resolve_proxy(proxy_arg: Optional[str]) -> Optional[str]:
|
||||||
if not proxy_arg:
|
if not proxy_arg:
|
||||||
return None
|
return None
|
||||||
if re.match(r"^(https?://|socks)", proxy_arg):
|
|
||||||
return proxy_arg
|
|
||||||
|
|
||||||
from unshackle.core.proxies.basic import Basic
|
from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_proxy
|
||||||
from unshackle.core.proxies.nordvpn import NordVPN
|
|
||||||
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
|
|
||||||
|
|
||||||
providers: list = []
|
try:
|
||||||
proxy_config = config.proxy_providers
|
providers = initialize_proxy_providers()
|
||||||
if proxy_config.get("basic"):
|
return resolve_proxy(proxy_arg, providers)
|
||||||
providers.append(Basic(**proxy_config["basic"]))
|
except ValueError as e:
|
||||||
if proxy_config.get("nordvpn"):
|
raise click.ClickException(str(e))
|
||||||
providers.append(NordVPN(**proxy_config["nordvpn"]))
|
|
||||||
if proxy_config.get("surfsharkvpn"):
|
|
||||||
providers.append(SurfsharkVPN(**proxy_config["surfsharkvpn"]))
|
|
||||||
|
|
||||||
requested_provider = None
|
|
||||||
query = proxy_arg
|
|
||||||
if re.match(r"^[a-z]+:.+$", proxy_arg, re.IGNORECASE):
|
|
||||||
requested_provider, query = proxy_arg.split(":", maxsplit=1)
|
|
||||||
|
|
||||||
if requested_provider:
|
|
||||||
provider = next(
|
|
||||||
(x for x in providers if x.__class__.__name__.lower() == requested_provider.lower()),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
if not provider:
|
|
||||||
raise click.ClickException(f"Proxy provider '{requested_provider}' not found.")
|
|
||||||
proxy_uri = provider.get_proxy(query)
|
|
||||||
if not proxy_uri:
|
|
||||||
raise click.ClickException(f"Proxy provider {requested_provider} had no proxy for {query}")
|
|
||||||
return proxy_uri
|
|
||||||
|
|
||||||
for provider in providers:
|
|
||||||
proxy_uri = provider.get_proxy(query)
|
|
||||||
if proxy_uri:
|
|
||||||
return proxy_uri
|
|
||||||
raise click.ClickException(f"No proxy provider had a proxy for {proxy_arg}")
|
|
||||||
|
|
||||||
|
|
||||||
class RemoteService:
|
class RemoteService:
|
||||||
|
|||||||
Reference in New Issue
Block a user