mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 19:35:06 +00:00
refactor(proxies): apply a service proxy_map before the proxy resolves
This commit is contained in:
@@ -116,9 +116,8 @@ up the objects your methods rely on:
|
|||||||
| `self.credential` | The active `Credential`, or `None` until authenticated. |
|
| `self.credential` | The active `Credential`, or `None` until authenticated. |
|
||||||
| `self.track_request` | A `TrackRequest` describing the requested codecs, ranges, and best-available flag (see below). |
|
| `self.track_request` | A `TrackRequest` describing the requested codecs, ranges, and best-available flag (see below). |
|
||||||
|
|
||||||
The constructor also resolves proxies: it reads `--proxy` and the `proxy_query` and
|
The constructor also resolves proxies: it reads `--proxy`, which `dl` and `search` have already
|
||||||
`proxy_provider` context params that `dl` and `search` derive from it, consults the per-service
|
resolved through the per-service `proxy_map`, and, if `GEOFENCE` is set and you did not give an explicit proxy, does a live
|
||||||
`proxy_map`, and, if `GEOFENCE` is set and you did not give an explicit proxy, does a live
|
|
||||||
IP check and auto-fetches a proxy to `GEOFENCE[0]` when it detects a geoblock. A
|
IP check and auto-fetches a proxy to `GEOFENCE[0]` when it detects a geoblock. A
|
||||||
`GEOBLOCK` hit with no `GEOFENCE` stops the run with a "not available in your region"
|
`GEOBLOCK` hit with no `GEOFENCE` stops the run with a "not available in your region"
|
||||||
error, because there is no main region to fetch a proxy for; pass `--proxy` yourself.
|
error, because there is no main region to fetch a proxy for; pass `--proxy` yourself.
|
||||||
|
|||||||
@@ -7,9 +7,10 @@
|
|||||||
Per-service configuration, keyed by the service tag in any case (for example `EXAMPLE1`, `EXAMPLE2`,
|
Per-service configuration, keyed by the service tag in any case (for example `EXAMPLE1`, `EXAMPLE2`,
|
||||||
`EXAMPLE3`). unshackle reads several well-known sub-keys out of each service's block:
|
`EXAMPLE3`). unshackle reads several well-known sub-keys out of each service's block:
|
||||||
|
|
||||||
- **`proxy_map`**: remaps the region query you passed to `-p/--proxy` for this service.
|
- **`proxy_map`**: remaps the region query you passed to `--proxy` for this service.
|
||||||
A config key is that query, or `"provider:query"` when the flag also named a proxy provider. The value is
|
A config key is that query, or `"provider:query"` when the flag also named a proxy provider, in any case. The value is
|
||||||
the query asked of the proxy provider instead. It has no effect when you give `-p` a full proxy URL.
|
the query asked of the proxy provider instead. When no proxy provider answers it, unshackle logs a warning and asks
|
||||||
|
the original query. It has no effect when you give `--proxy` a full proxy URL.
|
||||||
`dl`, `search` and a REST API download job apply it. The other REST API routes and a `--remote` remote session do not.
|
`dl`, `search` and a REST API download job apply it. The other REST API routes and a `--remote` remote session do not.
|
||||||
- **`title_map`**: an exact-match rename map applied to fetched titles (source name →
|
- **`title_map`**: an exact-match rename map applied to fetched titles (source name →
|
||||||
desired name), so a service that names a title differently from your library still matches.
|
desired name), so a service that names a title differently from your library still matches.
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ from unshackle.core.remote_protocol import APIErrorCode
|
|||||||
pytestmark = pytest.mark.unit
|
pytestmark = pytest.mark.unit
|
||||||
|
|
||||||
|
|
||||||
def run_dl(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> click.Context:
|
def run_dl(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str, providers: list | None = None, remote: bool = False
|
||||||
|
) -> click.Context:
|
||||||
from unshackle.commands import dl as dl_module
|
from unshackle.commands import dl as dl_module
|
||||||
|
|
||||||
monkeypatch.setattr(dl_module.config, "key_vaults", [])
|
monkeypatch.setattr(dl_module.config, "key_vaults", [])
|
||||||
@@ -22,7 +24,8 @@ def run_dl(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, proxy: str) -> click
|
|||||||
monkeypatch.setattr(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback)
|
monkeypatch.setattr(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback)
|
||||||
ctx = click.Context(dl_module.dl.cli)
|
ctx = click.Context(dl_module.dl.cli)
|
||||||
ctx.invoked_subcommand = "EXAMPLE"
|
ctx.invoked_subcommand = "EXAMPLE"
|
||||||
dl_module.dl(ctx=ctx, no_proxy=False, proxy=proxy, proxy_providers=[])
|
ctx.params["remote"] = remote
|
||||||
|
dl_module.dl(ctx=ctx, no_proxy=False, proxy=proxy, proxy_providers=providers or [])
|
||||||
return ctx
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
@@ -33,7 +36,7 @@ def test_dl_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.Monk
|
|||||||
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
|
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
|
||||||
params = run_dl(monkeypatch, tmp_path, "controld://efgh456@dns.controld.com").params
|
params = run_dl(monkeypatch, tmp_path, "controld://efgh456@dns.controld.com").params
|
||||||
assert params["proxy"] == "http://127.0.0.1:4000"
|
assert params["proxy"] == "http://127.0.0.1:4000"
|
||||||
assert (params["proxy_query"], params["proxy_provider"]) == (None, None)
|
assert params["proxy_query"] is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.usefixtures("example_service")
|
@pytest.mark.usefixtures("example_service")
|
||||||
@@ -49,3 +52,25 @@ def test_a_dl_proxy_error_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch, tmp_
|
|||||||
with pytest.raises(PlanError) as raised:
|
with pytest.raises(PlanError) as raised:
|
||||||
run_dl(monkeypatch, tmp_path, proxy)
|
run_dl(monkeypatch, tmp_path, proxy)
|
||||||
assert getattr(raised.value, "error_code", None) == APIErrorCode.INVALID_PROXY
|
assert getattr(raised.value, "error_code", None) == APIErrorCode.INVALID_PROXY
|
||||||
|
|
||||||
|
|
||||||
|
class Recorder:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.asked: list[str] = []
|
||||||
|
|
||||||
|
def get_proxy(self, query: str) -> str:
|
||||||
|
self.asked.append(query)
|
||||||
|
return f"http://{query}.proxy.example:8080"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("example_service")
|
||||||
|
@pytest.mark.parametrize(("remote", "asked"), [(False, ["ca"]), (True, ["us"])])
|
||||||
|
def test_dl_resolves_a_mapped_query_once_and_only_on_a_local_run(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, remote: bool, asked: list
|
||||||
|
) -> None:
|
||||||
|
from unshackle.commands import dl as dl_module
|
||||||
|
|
||||||
|
monkeypatch.setattr(dl_module.config, "services", {"example": {"proxy_map": {"us": "ca"}}})
|
||||||
|
recorder = Recorder()
|
||||||
|
params = run_dl(monkeypatch, tmp_path, "us", [recorder], remote).params
|
||||||
|
assert (recorder.asked, params["proxy"]) == (asked, f"http://{asked[0]}.proxy.example:8080")
|
||||||
|
|||||||
@@ -30,3 +30,33 @@ def test_search_starts_a_forwarder_for_a_control_d_resolver(monkeypatch: pytest.
|
|||||||
assert ctx.params["proxy"] == "http://127.0.0.1:4000"
|
assert ctx.params["proxy"] == "http://127.0.0.1:4000"
|
||||||
assert ctx.params["proxy_arg"] == SENT
|
assert ctx.params["proxy_arg"] == SENT
|
||||||
assert ctx.params.get("proxy_query") is None
|
assert ctx.params.get("proxy_query") is None
|
||||||
|
|
||||||
|
|
||||||
|
class Recorder:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.asked: list[str] = []
|
||||||
|
|
||||||
|
def get_proxy(self, query: str) -> str:
|
||||||
|
self.asked.append(query)
|
||||||
|
return f"http://{query}.proxy.example:8080"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("example_service")
|
||||||
|
@pytest.mark.parametrize(("remote", "asked"), [(False, ["ca"]), (True, ["us"])])
|
||||||
|
def test_search_resolves_a_mapped_query_once_and_only_on_a_local_run(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, remote: bool, asked: list
|
||||||
|
) -> None:
|
||||||
|
from unshackle.commands import search as search_module
|
||||||
|
|
||||||
|
recorder = Recorder()
|
||||||
|
monkeypatch.setattr(search_module.config, "services", {"example": {"proxy_map": {"us": "ca"}}})
|
||||||
|
monkeypatch.setattr(search_module, "load_proxy_providers", lambda: [recorder])
|
||||||
|
monkeypatch.setattr(search_module.Services, "get_path", staticmethod(lambda tag: tmp_path))
|
||||||
|
ctx = click.Context(search_module.search)
|
||||||
|
ctx.invoked_subcommand = "EXAMPLE"
|
||||||
|
ctx.params = {"proxy": "us", "no_proxy": False, "remote": remote}
|
||||||
|
with ctx:
|
||||||
|
assert search_module.search.callback
|
||||||
|
search_module.search.callback(no_proxy=False, proxy="us", remote=remote)
|
||||||
|
|
||||||
|
assert (recorder.asked, ctx.params["proxy"]) == (asked, f"http://{asked[0]}.proxy.example:8080")
|
||||||
|
|||||||
@@ -127,8 +127,8 @@ SERVED_LOGIN: LaunchKeys = {"served": True, "cookies_supplied": False}
|
|||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
("build", "expected"),
|
("build", "expected"),
|
||||||
[
|
[
|
||||||
(cli_dl, {"proxy_arg": "us", "proxy_query": "us", "proxy_provider": None}),
|
(cli_dl, {"proxy_arg": "us", "proxy_query": "us"}),
|
||||||
(cli_search, {"proxy_arg": "us", "proxy_query": "us", "proxy_provider": None}),
|
(cli_search, {"proxy_arg": "us", "proxy_query": "us"}),
|
||||||
(rest_relay, {"served": True, "client_argv": "serve (REST API)"}),
|
(rest_relay, {"served": True, "client_argv": "serve (REST API)"}),
|
||||||
(rest_list, SERVED_LOGIN),
|
(rest_list, SERVED_LOGIN),
|
||||||
(rest_search, SERVED_LOGIN),
|
(rest_search, SERVED_LOGIN),
|
||||||
|
|||||||
@@ -230,18 +230,17 @@ class Gluetun(Alpha):
|
|||||||
(
|
(
|
||||||
"US",
|
"US",
|
||||||
ResolvedProxy(
|
ResolvedProxy(
|
||||||
"http://a:b@alpha.example:80", None, "us", "Using Alpha Proxy: http://xxxxx:xxxxx@alpha.example:80"
|
"http://a:b@alpha.example:80", "us", "Using Alpha Proxy: http://xxxxx:xxxxx@alpha.example:80"
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"Beta:CA",
|
"Beta:CA",
|
||||||
ResolvedProxy("http://c:d@beta-ca.example:80", "Beta", "ca", "Using Beta Proxy via Dallas (server 12)"),
|
ResolvedProxy("http://c:d@beta-ca.example:80", "ca", "Using Beta Proxy via Dallas (server 12)"),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"alpha:beta:ca",
|
"alpha:beta:ca",
|
||||||
ResolvedProxy(
|
ResolvedProxy(
|
||||||
"http://a:b@alpha-beta.example:80",
|
"http://a:b@alpha-beta.example:80",
|
||||||
"alpha",
|
|
||||||
"beta:ca",
|
"beta:ca",
|
||||||
"Using Alpha Proxy: http://xxxxx:xxxxx@alpha-beta.example:80",
|
"Using Alpha Proxy: http://xxxxx:xxxxx@alpha-beta.example:80",
|
||||||
),
|
),
|
||||||
@@ -251,13 +250,12 @@ class Gluetun(Alpha):
|
|||||||
ResolvedProxy(
|
ResolvedProxy(
|
||||||
"http://user:pass@proxy.example:8080",
|
"http://user:pass@proxy.example:8080",
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
"Using explicit Proxy: http://xxxxx:xxxxx@proxy.example:8080",
|
"Using explicit Proxy: http://xxxxx:xxxxx@proxy.example:8080",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
("localhost:8080", ResolvedProxy("localhost:8080", None, None, "Using a local proxy on port 8080")),
|
("localhost:8080", ResolvedProxy("localhost:8080", None, "Using a local proxy on port 8080")),
|
||||||
("1.2.3.4:3128", ResolvedProxy("1.2.3.4:3128", None, None, "Using explicit Proxy: 1.2.3.4:3128")),
|
("1.2.3.4:3128", ResolvedProxy("1.2.3.4:3128", None, "Using explicit Proxy: 1.2.3.4:3128")),
|
||||||
("us:1080", ResolvedProxy("us:1080", None, None, "Using explicit Proxy: us:1080")),
|
("us:1080", ResolvedProxy("us:1080", None, "Using explicit Proxy: us:1080")),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_resolve_proxy_value_reads_each_form(providers: list, value: str, expected: ResolvedProxy) -> None:
|
def test_resolve_proxy_value_reads_each_form(providers: list, value: str, expected: ResolvedProxy) -> None:
|
||||||
@@ -270,7 +268,7 @@ def test_resolve_proxy_value_starts_a_forwarder_for_a_control_d_resolver(monkeyp
|
|||||||
|
|
||||||
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
|
monkeypatch.setattr(controld, "local_proxy", lambda uri: "http://127.0.0.1:4000")
|
||||||
resolved = resolve_proxy_value("controld://efgh456@dns.controld.com", [])
|
resolved = resolve_proxy_value("controld://efgh456@dns.controld.com", [])
|
||||||
assert resolved == ResolvedProxy("http://127.0.0.1:4000", None, None, "Using a local proxy on port 4000")
|
assert resolved == ResolvedProxy("http://127.0.0.1:4000", None, "Using a local proxy on port 4000")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
@@ -292,3 +290,30 @@ def test_the_status_wraps_only_the_provider_lookup(providers: list, value: str,
|
|||||||
@pytest.mark.parametrize("value", ["localhost:8080", "1.2.3.4:3128"])
|
@pytest.mark.parametrize("value", ["localhost:8080", "1.2.3.4:3128"])
|
||||||
def test_resolve_proxy_passes_a_host_and_port_through(providers: list, value: str) -> None:
|
def test_resolve_proxy_passes_a_host_and_port_through(providers: list, value: str) -> None:
|
||||||
assert resolve_proxy(value, providers) == value
|
assert resolve_proxy(value, providers) == value
|
||||||
|
|
||||||
|
|
||||||
|
class Recorder(Alpha):
|
||||||
|
def __init__(self, **answers: str) -> None:
|
||||||
|
super().__init__(**answers)
|
||||||
|
self.asked: list[str] = []
|
||||||
|
|
||||||
|
def get_proxy(self, query: str) -> str | None:
|
||||||
|
self.asked.append(query)
|
||||||
|
return super().get_proxy(query)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("value", "asked", "uri"),
|
||||||
|
[
|
||||||
|
("us", ["ca"], "http://ca.example:8080"),
|
||||||
|
("recorder:us", ["uk"], "http://uk.example:8080"),
|
||||||
|
("US", ["ca"], "http://ca.example:8080"),
|
||||||
|
("Recorder:US", ["uk"], "http://uk.example:8080"),
|
||||||
|
("fr", ["zz", "fr"], "http://fr.example:8080"),
|
||||||
|
("de", ["de"], "http://de.example:8080"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_a_proxy_map_swaps_the_query_and_falls_back_to_it(value: str, asked: list, uri: str) -> None:
|
||||||
|
recorder = Recorder(**{x: f"http://{x}.example:8080" for x in ("ca", "uk", "fr", "de")})
|
||||||
|
resolved = resolve_proxy_value(value, [recorder], proxy_map={"US": "ca", "recorder:us": "uk", "fr": "zz"})
|
||||||
|
assert (recorder.asked, resolved.uri) == (asked, uri)
|
||||||
|
|||||||
@@ -1351,14 +1351,16 @@ class dl:
|
|||||||
if proxy:
|
if proxy:
|
||||||
try:
|
try:
|
||||||
resolved = resolve_proxy_value(
|
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:
|
except ValueError as e:
|
||||||
raise coded(PlanError(str(e)), APIErrorCode.INVALID_PROXY) from None
|
raise coded(PlanError(str(e)), APIErrorCode.INVALID_PROXY) from None
|
||||||
ctx.params["proxy"] = resolved.uri
|
ctx.params["proxy"] = resolved.uri
|
||||||
self.log.info(resolved.line)
|
self.log.info(resolved.line)
|
||||||
keys["proxy_query"] = resolved.query
|
keys["proxy_query"] = resolved.query
|
||||||
keys["proxy_provider"] = resolved.provider
|
|
||||||
|
|
||||||
launch(
|
launch(
|
||||||
ctx,
|
ctx,
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from rich.rule import Rule
|
|||||||
from rich.tree import Tree
|
from rich.tree import Tree
|
||||||
|
|
||||||
from unshackle.core import login
|
from unshackle.core import login
|
||||||
|
from unshackle.core.config import config
|
||||||
from unshackle.core.console import console
|
from unshackle.core.console import console
|
||||||
from unshackle.core.constants import context_settings
|
from unshackle.core.constants import context_settings
|
||||||
from unshackle.core.launch import LaunchKeys, launch, load_service_config
|
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.service import Service
|
||||||
from unshackle.core.services import Services
|
from unshackle.core.services import Services
|
||||||
from unshackle.core.utils.click_types import ContextData
|
from unshackle.core.utils.click_types import ContextData
|
||||||
|
from unshackle.core.utils.collections import ci_get
|
||||||
|
|
||||||
|
|
||||||
@click.command(
|
@click.command(
|
||||||
@@ -96,14 +98,18 @@ def search(
|
|||||||
keys["proxy_arg"] = proxy
|
keys["proxy_arg"] = proxy
|
||||||
if proxy:
|
if proxy:
|
||||||
try:
|
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:
|
except ValueError as e:
|
||||||
log.error(str(e))
|
log.error(str(e))
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
ctx.params["proxy"] = resolved.uri
|
ctx.params["proxy"] = resolved.uri
|
||||||
log.info(resolved.line)
|
log.info(resolved.line)
|
||||||
keys["proxy_query"] = resolved.query
|
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))
|
launch(ctx, keys, ContextData(config=service_config, cdm=None, proxy_providers=proxy_providers, profile=profile))
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,7 @@ class LaunchKeys(TypedDict, total=False):
|
|||||||
- ``client_identity``: the service config holds the device identity that the remote client sent.
|
- ``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.
|
- ``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_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_query``: the region part of ``--proxy``.
|
||||||
- ``proxy_provider``: the proxy provider that ``--proxy`` names, or None.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
served: bool
|
served: bool
|
||||||
@@ -31,7 +30,6 @@ class LaunchKeys(TypedDict, total=False):
|
|||||||
client_argv: str
|
client_argv: str
|
||||||
proxy_arg: str | None
|
proxy_arg: str | None
|
||||||
proxy_query: str | None
|
proxy_query: str | None
|
||||||
proxy_provider: str | None
|
|
||||||
|
|
||||||
|
|
||||||
def launch(ctx: click.Context, keys: LaunchKeys, obj: ContextData | None = None) -> None:
|
def launch(ctx: click.Context, keys: LaunchKeys, obj: ContextData | None = None) -> None:
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from click.core import ParameterSource
|
|||||||
|
|
||||||
from unshackle.core.proxies.proxy import Proxy
|
from unshackle.core.proxies.proxy import Proxy
|
||||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||||
|
from unshackle.core.utils.collections import ci_get
|
||||||
from unshackle.core.utils.redact import mask_proxy
|
from unshackle.core.utils.redact import mask_proxy
|
||||||
|
|
||||||
log = logging.getLogger("proxies")
|
log = logging.getLogger("proxies")
|
||||||
@@ -255,12 +256,10 @@ def describe_explicit_proxy(uri: str) -> str:
|
|||||||
class ResolvedProxy:
|
class ResolvedProxy:
|
||||||
"""A ``--proxy`` value resolved to a proxy URI.
|
"""A ``--proxy`` value resolved to a proxy URI.
|
||||||
|
|
||||||
*provider* and *query* are the proxy provider that the value names and its lowercase region query.
|
*query* is the lowercase region query, or None for a proxy URI, a ``host:port`` value or a Control D resolver.
|
||||||
Both are None for a proxy URI, a ``host:port`` value or a Control D resolver.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
uri: str
|
uri: str
|
||||||
provider: str | None
|
|
||||||
query: str | None
|
query: str | None
|
||||||
line: str
|
line: str
|
||||||
|
|
||||||
@@ -270,29 +269,46 @@ def resolve_proxy_value(
|
|||||||
proxy_providers: list[Any],
|
proxy_providers: list[Any],
|
||||||
allow_debug: bool = True,
|
allow_debug: bool = True,
|
||||||
status: Callable[[str], AbstractContextManager[Any]] | None = None,
|
status: Callable[[str], AbstractContextManager[Any]] | None = None,
|
||||||
|
proxy_map: dict[str, str] | None = None,
|
||||||
) -> ResolvedProxy:
|
) -> ResolvedProxy:
|
||||||
"""Resolve a ``--proxy`` value: a Control D resolver, a region query for a proxy provider, or a proxy URI.
|
"""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.
|
*status* wraps the proxy provider lookup, for a console spinner. Raises a coded ValueError.
|
||||||
"""
|
"""
|
||||||
if value.startswith("controld://"):
|
if value.startswith("controld://"):
|
||||||
from unshackle.core.proxies.controld import local_proxy
|
from unshackle.core.proxies.controld import local_proxy
|
||||||
|
|
||||||
uri = local_proxy(value)
|
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)
|
provider_name, query = split_proxy_query(value, proxy_providers)
|
||||||
if not REGION_QUERY.fullmatch(query):
|
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()
|
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 = (
|
message = (
|
||||||
f"Connecting to VPN ({query})..."
|
f"Connecting to VPN ({asked})..."
|
||||||
if (provider_name or "").lower() == "gluetun"
|
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():
|
with status(message) if status else nullcontext():
|
||||||
provider, uri = pick_proxy(proxy_providers, query, provider_name)
|
try:
|
||||||
line = describe_proxy(provider, uri, query, allow_debug)
|
provider, uri = pick_proxy(proxy_providers, asked, provider_name)
|
||||||
return ResolvedProxy(uri, provider_name, query, line)
|
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:
|
def resolve_proxy(proxy: str | None, proxy_providers: list[Any]) -> str | None:
|
||||||
|
|||||||
@@ -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.console import console, prompt_user, show_notice, show_qr
|
||||||
from unshackle.core.credential import Credential
|
from unshackle.core.credential import Credential
|
||||||
from unshackle.core.launch import launch_keys
|
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.proxies.resolve import pick_proxy
|
||||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||||
from unshackle.core.search_result import SearchResult
|
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 import Chapters, Tracks
|
||||||
from unshackle.core.tracks.video import Video
|
from unshackle.core.tracks.video import Video
|
||||||
from unshackle.core.utils import run_proxy
|
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.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
|
# Default (connect, read) timeout for the requests path, mirroring RnetSession's
|
||||||
# connect_timeout / read_timeout construction defaults. A per-request timeout= wins.
|
# connect_timeout / read_timeout construction defaults. A per-request timeout= wins.
|
||||||
@@ -127,21 +124,6 @@ class TrackRequest:
|
|||||||
generate_dv: bool = False
|
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")
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
|
||||||
@@ -207,35 +189,6 @@ class Service(TitleSource):
|
|||||||
whose = "the server's" if keys.get("served") else "your"
|
whose = "the server's" if keys.get("served") else "your"
|
||||||
if not ctx.parent or not ctx.parent.params.get("no_proxy"):
|
if not ctx.parent or not ctx.parent.params.get("no_proxy"):
|
||||||
proxy = ctx.parent.params["proxy"] if ctx.parent else None
|
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:
|
if not proxy:
|
||||||
# don't override the explicit proxy set by the user, even if they may be geoblocked
|
# 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"):
|
with console.status("Checking if current region is Geoblocked...", spinner="dots"):
|
||||||
|
|||||||
Reference in New Issue
Block a user