refactor(proxies): apply a service proxy_map before the proxy resolves

This commit is contained in:
imSp4rky
2026-11-27 11:53:06 -07:00
parent 387ce53e84
commit 84751b1f9e
11 changed files with 138 additions and 83 deletions
+4 -2
View File
@@ -1351,14 +1351,16 @@ class dl:
if proxy:
try:
resolved = resolve_proxy_value(
proxy, self.proxy_providers, status=partial(console.status, spinner="dots")
proxy,
self.proxy_providers,
status=partial(console.status, spinner="dots"),
proxy_map=None if self.is_remote else service_config.get("proxy_map"),
)
except ValueError as e:
raise coded(PlanError(str(e)), APIErrorCode.INVALID_PROXY) from None
ctx.params["proxy"] = resolved.uri
self.log.info(resolved.line)
keys["proxy_query"] = resolved.query
keys["proxy_provider"] = resolved.provider
launch(
ctx,
+8 -2
View File
@@ -11,6 +11,7 @@ from rich.rule import Rule
from rich.tree import Tree
from unshackle.core import login
from unshackle.core.config import config
from unshackle.core.console import console
from unshackle.core.constants import context_settings
from unshackle.core.launch import LaunchKeys, launch, load_service_config
@@ -19,6 +20,7 @@ from unshackle.core.proxies.resolve import load_proxy_providers, require_alone_l
from unshackle.core.service import Service
from unshackle.core.services import Services
from unshackle.core.utils.click_types import ContextData
from unshackle.core.utils.collections import ci_get
@click.command(
@@ -96,14 +98,18 @@ def search(
keys["proxy_arg"] = proxy
if proxy:
try:
resolved = resolve_proxy_value(proxy, proxy_providers, status=partial(console.status, spinner="dots"))
resolved = resolve_proxy_value(
proxy,
proxy_providers,
status=partial(console.status, spinner="dots"),
proxy_map=None if remote else (ci_get(config.services, service) or {}).get("proxy_map"),
)
except ValueError as e:
log.error(str(e))
sys.exit(1)
ctx.params["proxy"] = resolved.uri
log.info(resolved.line)
keys["proxy_query"] = resolved.query
keys["proxy_provider"] = resolved.provider
launch(ctx, keys, ContextData(config=service_config, cdm=None, proxy_providers=proxy_providers, profile=profile))
+1 -3
View File
@@ -20,8 +20,7 @@ class LaunchKeys(TypedDict, total=False):
- ``client_identity``: the service config holds the device identity that the remote client sent.
- ``client_argv``: the command line that the remote server's dashboard shows for this client.
- ``proxy_arg``: the ``--proxy`` value as given, before it resolves to a URI.
- ``proxy_query``: the region part of ``--proxy``, which a service ``proxy_map`` keys on.
- ``proxy_provider``: the proxy provider that ``--proxy`` names, or None.
- ``proxy_query``: the region part of ``--proxy``.
"""
served: bool
@@ -31,7 +30,6 @@ class LaunchKeys(TypedDict, total=False):
client_argv: str
proxy_arg: str | None
proxy_query: str | None
proxy_provider: str | None
def launch(ctx: click.Context, keys: LaunchKeys, obj: ContextData | None = None) -> None:
+26 -10
View File
@@ -18,6 +18,7 @@ from click.core import ParameterSource
from unshackle.core.proxies.proxy import Proxy
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.utils.collections import ci_get
from unshackle.core.utils.redact import mask_proxy
log = logging.getLogger("proxies")
@@ -255,12 +256,10 @@ def describe_explicit_proxy(uri: str) -> str:
class ResolvedProxy:
"""A ``--proxy`` value resolved to a proxy URI.
*provider* and *query* are the proxy provider that the value names and its lowercase region query.
Both are None for a proxy URI, a ``host:port`` value or a Control D resolver.
*query* is the lowercase region query, or None for a proxy URI, a ``host:port`` value or a Control D resolver.
"""
uri: str
provider: str | None
query: str | None
line: str
@@ -270,29 +269,46 @@ def resolve_proxy_value(
proxy_providers: list[Any],
allow_debug: bool = True,
status: Callable[[str], AbstractContextManager[Any]] | None = None,
proxy_map: dict[str, str] | None = None,
) -> ResolvedProxy:
"""Resolve a ``--proxy`` value: a Control D resolver, a region query for a proxy provider, or a proxy URI.
*proxy_map* is a service's ``proxy_map``: it swaps a region query, keyed ``provider:query`` else ``query``,
for the query to ask instead, in any case. When no proxy provider answers the swapped query, it asks the original query.
*status* wraps the proxy provider lookup, for a console spinner. Raises a coded ValueError.
"""
if value.startswith("controld://"):
from unshackle.core.proxies.controld import local_proxy
uri = local_proxy(value)
return ResolvedProxy(uri, None, None, describe_explicit_proxy(uri))
return ResolvedProxy(uri, None, describe_explicit_proxy(uri))
provider_name, query = split_proxy_query(value, proxy_providers)
if not REGION_QUERY.fullmatch(query):
return ResolvedProxy(value, None, None, describe_explicit_proxy(value))
return ResolvedProxy(value, None, describe_explicit_proxy(value))
query = query.lower()
key = f"{provider_name}:{query}" if provider_name else query
mapped = ci_get(proxy_map or {}, key)
if mapped:
log.info(f"Found service-specific proxy mapping: {key} -> {mask_proxy(mapped, allow_debug=False)}")
asked = mapped or query
message = (
f"Connecting to VPN ({query})..."
f"Connecting to VPN ({asked})..."
if (provider_name or "").lower() == "gluetun"
else f"Getting a Proxy to {query}..."
else f"Getting a Proxy to {asked}..."
)
with status(message) if status else nullcontext():
provider, uri = pick_proxy(proxy_providers, query, provider_name)
line = describe_proxy(provider, uri, query, allow_debug)
return ResolvedProxy(uri, provider_name, query, line)
try:
provider, uri = pick_proxy(proxy_providers, asked, provider_name)
except ValueError as e:
if not mapped:
raise
log.warning(
f"The mapped proxy query {mask_proxy(mapped, allow_debug=False)} failed, so {query} is used: {e}"
)
asked = query
provider, uri = pick_proxy(proxy_providers, asked, provider_name)
line = describe_proxy(provider, uri, asked, allow_debug)
return ResolvedProxy(uri, query, line)
def resolve_proxy(proxy: str | None, proxy_providers: list[Any]) -> str | None:
-47
View File
@@ -20,7 +20,6 @@ from unshackle.core.config import config
from unshackle.core.console import console, prompt_user, show_notice, show_qr
from unshackle.core.credential import Credential
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
@@ -40,9 +39,7 @@ from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.tracks.video import Video
from unshackle.core.utils import run_proxy
from unshackle.core.utils.collections import ci_get
from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit
from unshackle.core.utils.redact import mask_proxy
# Default (connect, read) timeout for the requests path, mirroring RnetSession's
# connect_timeout / read_timeout construction defaults. A per-request timeout= wins.
@@ -127,21 +124,6 @@ class TrackRequest:
generate_dv: bool = False
def sanitize_proxy_for_log(uri: str | None, mask_host: bool = False) -> str | None:
"""
Sanitise a proxy URI for logs by masking any embedded userinfo (username/password).
``serve`` sends these log lines to the client of a remote session, so the mask is
unconditional and debug mode never lifts it. ``mask_host`` hides the hostname as
well, for a proxy that came from the user-supplied ``Basic`` proxy provider.
"""
if uri is None:
return None
if not isinstance(uri, str):
return str(uri)
return mask_proxy(uri, mask_host=mask_host, allow_debug=False)
T = TypeVar("T")
@@ -207,35 +189,6 @@ class Service(TitleSource):
whose = "the server's" if keys.get("served") else "your"
if not ctx.parent or not ctx.parent.params.get("no_proxy"):
proxy = ctx.parent.params["proxy"] if ctx.parent else None
proxy_query = keys.get("proxy_query")
proxy_provider_name = keys.get("proxy_provider")
service_name = self.__class__.__name__
service_config_dict = ci_get(config.services, service_name) or {}
proxy_map = service_config_dict.get("proxy_map", {})
if proxy_map and proxy_query:
if proxy_provider_name:
full_proxy_key = f"{proxy_provider_name}:{proxy_query}"
else:
full_proxy_key = proxy_query
mapped_value = proxy_map.get(full_proxy_key)
if mapped_value:
self.log.info(
f"Found service-specific proxy mapping: {full_proxy_key} -> {sanitize_proxy_for_log(mapped_value)}"
)
try:
proxy_provider, proxy = pick_proxy(ctx.obj.proxy_providers, mapped_value, proxy_provider_name)
self.log.info(
f"Using mapped proxy from {proxy_provider.__class__.__name__}: "
f"{sanitize_proxy_for_log(proxy, mask_host=isinstance(proxy_provider, Basic))}"
)
except ValueError:
self.log.warning(
f"No provider could resolve mapped value '{sanitize_proxy_for_log(mapped_value)}', using default"
)
if not proxy:
# don't override the explicit proxy set by the user, even if they may be geoblocked
with console.status("Checking if current region is Geoblocked...", spinner="dots"):