feat(remote): add zlib compression for API payloads and gzip transport

Compress manifest XML, cache files, and cookies with zlib before base64 encoding, reducing /tracks payload by 83-95%. Add configurable compression_level in serve config (default: 1, fast).

Enable aiohttp gzip middleware for transport-level compression on all JSON responses. Set User-Agent to unshackle/<version> for remote client requests. Add remote-aware status messages for auth, titles, and tracks.
This commit is contained in:
Andy
2026-03-18 23:47:06 -06:00
parent b420e2bd08
commit 61ee5cb10a
5 changed files with 90 additions and 21 deletions
+7 -4
View File
@@ -700,9 +700,11 @@ class dl:
if self.profile:
self.log.info(f"Using profile: '{self.profile}'")
self.is_remote = bool(ctx.params.get("remote"))
with console.status("Loading Service Config...", spinner="dots"):
self.service_config = {}
if not ctx.params.get("remote"):
if not self.is_remote:
try:
service_config_path = Services.get_path(self.service) / config.filenames.config
if service_config_path.exists():
@@ -1065,7 +1067,7 @@ class dl:
},
)
with console.status("Authenticating with Service...", spinner="dots"):
with console.status("Authenticating with Remote Service..." if self.is_remote else "Authenticating with Service...", spinner="dots"):
try:
cookies = self.get_cookie_jar(self.service, self.profile)
credential = self.get_credentials(self.service, self.profile)
@@ -1090,7 +1092,7 @@ class dl:
)
raise
with console.status("Fetching Title Metadata...", spinner="dots"):
with console.status("Fetching Remote Title Metadata..." if self.is_remote else "Fetching Title Metadata...", spinner="dots"):
try:
titles = service.get_titles_cached()
if not titles:
@@ -1370,7 +1372,8 @@ class dl:
console.log("Skipped chapters as --no-chapters was used...")
title.tracks.chapters = []
with console.status("Getting tracks...", spinner="dots"):
tracks_label = "Getting Remote Tracks..." if self.is_remote else "Getting Tracks..."
with console.status(tracks_label, spinner="dots"):
try:
title.tracks.add(service.get_tracks(title), warn_only=True)
title.tracks.chapters = service.get_chapters(title)
+5 -4
View File
@@ -6,6 +6,7 @@ from aiohttp import web
from unshackle.core import binaries
from unshackle.core.api import cors_middleware, setup_routes, setup_swagger
from unshackle.core.api.compression import compression_middleware
from unshackle.core.config import config
from unshackle.core.constants import context_settings
@@ -132,10 +133,10 @@ def serve(
if api_only:
log.info("Starting REST API server (pywidevine/pyplayready CDM disabled)")
if no_key:
app = web.Application(middlewares=[cors_middleware])
app = web.Application(middlewares=[cors_middleware, compression_middleware])
app["config"] = {"users": {}}
else:
app = web.Application(middlewares=[cors_middleware, api_key_authentication])
app = web.Application(middlewares=[cors_middleware, api_key_authentication, compression_middleware])
app["config"] = {"users": {api_secret: {"devices": [], "username": "api_user"}}}
app["debug_api"] = debug_api
@@ -211,10 +212,10 @@ def serve(
return serve_authentication
if no_key:
app = web.Application(middlewares=[cors_middleware])
app = web.Application(middlewares=[cors_middleware, compression_middleware])
else:
serve_auth = create_serve_authentication(serve_playready and bool(prd_devices))
app = web.Application(middlewares=[cors_middleware, serve_auth])
app = web.Application(middlewares=[cors_middleware, serve_auth, compression_middleware])
app["config"] = serve_config
app["debug_api"] = debug_api
+40
View File
@@ -0,0 +1,40 @@
"""aiohttp middleware for gzip transport compression."""
from __future__ import annotations
import gzip
from aiohttp import web
@web.middleware
async def compression_middleware(request: web.Request, handler) -> web.Response:
"""Compress JSON responses with gzip when the client supports it."""
response = await handler(request)
accept_encoding = request.headers.get("Accept-Encoding", "")
if "gzip" not in accept_encoding:
return response
if response.content_type and "json" not in response.content_type:
return response
body = response.body
if body is None or len(body) < 256:
return response
from unshackle.core.config import config
level = config.serve.get("compression_level", 1)
if not level:
return response
compressed = gzip.compress(body, compresslevel=level)
headers = dict(response.headers)
headers["Content-Encoding"] = "gzip"
headers["Content-Length"] = str(len(compressed))
return web.Response(
body=compressed,
status=response.status,
headers=headers,
)
+21 -7
View File
@@ -113,14 +113,19 @@ def serialize_title(title: Title_T) -> Dict[str, Any]:
def _extract_manifests(tracks) -> List[Dict[str, Any]]:
"""Extract manifest data from tracks for client-side re-parsing.
Serializes DASH and ISM manifest XML as base64 strings so the client
can reconstruct track.data locally. HLS tracks download directly from
their URL so no manifest serialization is needed.
Serializes DASH and ISM manifest XML as zlib-compressed base64 strings
so the client can reconstruct track.data locally. HLS tracks download
directly from their URL so no manifest serialization is needed.
"""
import base64
import zlib
from lxml import etree
from unshackle.core.config import config as app_config
compression_level = app_config.serve.get("compression_level", 1)
seen: set[str] = set()
manifests: List[Dict[str, Any]] = []
@@ -132,21 +137,23 @@ def _extract_manifests(tracks) -> List[Dict[str, Any]]:
if track.data.get("dash") and track.data["dash"].get("manifest"):
seen.add(manifest_url)
xml_bytes = etree.tostring(track.data["dash"]["manifest"], xml_declaration=True, encoding="UTF-8")
compressed = zlib.compress(xml_bytes, compression_level) if compression_level else xml_bytes
manifests.append(
{
"type": "dash",
"url": manifest_url,
"data": base64.b64encode(xml_bytes).decode("ascii"),
"data": base64.b64encode(compressed).decode("ascii"),
}
)
elif track.data.get("ism") and track.data["ism"].get("manifest"):
seen.add(manifest_url)
xml_bytes = etree.tostring(track.data["ism"]["manifest"], xml_declaration=True, encoding="UTF-8")
compressed = zlib.compress(xml_bytes, compression_level) if compression_level else xml_bytes
manifests.append(
{
"type": "ism",
"url": manifest_url,
"data": base64.b64encode(xml_bytes).decode("ascii"),
"data": base64.b64encode(compressed).decode("ascii"),
}
)
@@ -1284,11 +1291,14 @@ def _create_service_instance(
# Resolve cookies: client-sent > server-local
cookie_text = data.get("cookies")
if cookie_text and isinstance(cookie_text, str):
import base64
import tempfile
import zlib
from http.cookiejar import MozillaCookieJar
cookie_str = zlib.decompress(base64.b64decode(cookie_text)).decode("utf-8")
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False, encoding="utf-8") as f:
f.write(cookie_text)
f.write(cookie_str)
tmp_path = f.name
try:
cookies = MozillaCookieJar(tmp_path)
@@ -1356,10 +1366,14 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
cache_data = data.get("cache", {})
if cache_data:
import base64
import zlib
cache_dir = app_config.directories.cache / session_cache_tag
cache_dir.mkdir(parents=True, exist_ok=True)
for key, content in cache_data.items():
(cache_dir / key).with_suffix(".json").write_text(content, encoding="utf-8")
decompressed = zlib.decompress(base64.b64decode(content)).decode("utf-8")
(cache_dir / key).with_suffix(".json").write_text(decompressed, encoding="utf-8")
service_instance.authenticate(cookies, credential)
+17 -6
View File
@@ -45,7 +45,10 @@ class RemoteClient:
@property
def session(self) -> requests.Session:
if self._session is None:
from unshackle.core import __version__
self._session = requests.Session()
self._session.headers["User-Agent"] = f"unshackle/{__version__}"
if self.api_key:
self._session.headers["X-Secret-Key"] = self.api_key
return self._session
@@ -179,11 +182,13 @@ def _build_tracks(data: Dict[str, Any]) -> Tracks:
def _resolve_manifest_data(tracks: Tracks, manifests: list, session: Any) -> None:
"""Re-parse serialized manifests and populate track.data for downloading.
The server serializes DASH and ISM manifest XML as base64. We decode and
re-parse locally, then match each remote track to the locally-parsed track
by ID to copy track.data. HLS is skipped as it re-fetches from track.url.
The server serializes DASH and ISM manifest XML as zlib-compressed base64.
We decode and decompress locally, re-parse with the appropriate manifest
parser, then match each remote track to the locally-parsed track by ID
to copy track.data. HLS is skipped as it re-fetches from track.url.
"""
import base64 as b64
import zlib
if not manifests:
return
@@ -199,7 +204,7 @@ def _resolve_manifest_data(tracks: Tracks, manifests: list, session: Any) -> Non
continue
try:
raw = b64.b64decode(m_data)
raw = zlib.decompress(b64.b64decode(m_data))
if m_type == "dash":
from lxml import etree
@@ -328,11 +333,13 @@ def _load_credentials_for_transport(service_tag: str, profile: Optional[str]) ->
def _load_cookies_for_transport(service_tag: str, profile: Optional[str]) -> Optional[str]:
import zlib
from unshackle.commands.dl import dl
cookie_path = dl.get_cookie_path(service_tag, profile)
if cookie_path and cookie_path.exists():
return cookie_path.read_text(encoding="utf-8")
return base64.b64encode(zlib.compress(cookie_path.read_bytes())).decode("ascii")
return None
@@ -685,11 +692,15 @@ class RemoteService:
self._session_id = None
def _load_cache_files(self) -> Dict[str, str]:
import zlib
cache_dir = config.directories.cache / self.service_tag
if not cache_dir.is_dir():
return {}
return {
f.stem: f.read_text(encoding="utf-8") for f in cache_dir.glob("*.json") if not f.stem.startswith("titles_")
f.stem: base64.b64encode(zlib.compress(f.read_bytes())).decode("ascii")
for f in cache_dir.glob("*.json")
if not f.stem.startswith("titles_")
}