mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 20:45:11 +00:00
fix(proxies): skip a proxy provider that fails to load
A bare --proxy query moves past it; naming it (--proxy nordvpn:us) fails with the load error. dl, search and the REST path share one loader.
This commit is contained in:
@@ -163,7 +163,9 @@ class NordVPN(Proxy):
|
||||
Note: There may not always be more than one recommended server.
|
||||
"""
|
||||
res = requests.get(
|
||||
url="https://api.nordvpn.com/v1/servers/recommendations", params={"filters[country_id]": country_id}
|
||||
url="https://api.nordvpn.com/v1/servers/recommendations",
|
||||
params={"filters[country_id]": country_id},
|
||||
timeout=10,
|
||||
)
|
||||
if not res.ok:
|
||||
raise ValueError(f"Failed to get a list of NordVPN countries [{res.status_code}]")
|
||||
@@ -176,9 +178,7 @@ class NordVPN(Proxy):
|
||||
@staticmethod
|
||||
def get_countries() -> list[dict]:
|
||||
"""Get a list of available Countries and their metadata."""
|
||||
res = requests.get(
|
||||
url="https://api.nordvpn.com/v1/servers/countries",
|
||||
)
|
||||
res = requests.get(url="https://api.nordvpn.com/v1/servers/countries", timeout=10)
|
||||
if not res.ok:
|
||||
raise ValueError(f"Failed to get a list of NordVPN countries [{res.status_code}]")
|
||||
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
"""Shared proxy provider initialization and resolution.
|
||||
|
||||
Used by both the REST API handlers and the remote service client.
|
||||
"""
|
||||
"""Shared proxy provider loading, lookup and resolution for dl, search, the REST API and the remote client."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -11,6 +8,7 @@ import re
|
||||
from typing import Any, List, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from unshackle.core.proxies.proxy import Proxy
|
||||
from unshackle.core.utils.redact import mask_proxy
|
||||
|
||||
log = logging.getLogger("proxies")
|
||||
@@ -18,58 +16,106 @@ log = logging.getLogger("proxies")
|
||||
REGION = r"[a-z]{2,4}(?:_[a-z0-9]{2,4})?(?:-[a-z0-9]+|:[a-z][a-z0-9]*)*\d*"
|
||||
|
||||
|
||||
def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False) -> List[Any]:
|
||||
"""Initialise and return available proxy providers from config.
|
||||
class Unavailable(Proxy):
|
||||
"""Stands in for a proxy provider that failed to load: a bare query skips it, a query that names it fails."""
|
||||
|
||||
A proxy provider that fails to build is logged and skipped, unless *raise_errors* is set.
|
||||
*quiet* drops the per-provider summary lines: rendering a proxy provider asks some of them
|
||||
for their server catalogue over the network, which a repeated caller must not pay for.
|
||||
def __init__(self, name: str, error: Exception) -> None:
|
||||
self.name = name
|
||||
# The message only: the exception's traceback would keep the failed build's frames alive.
|
||||
self.error = str(error)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"failed to load ({self.error})"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def find_provider(proxy_providers: List[Any], name: str) -> Any:
|
||||
"""
|
||||
Find a proxy provider by its class name, case-insensitive.
|
||||
|
||||
Raises ValueError when no proxy provider has that name, or when it failed to load.
|
||||
"""
|
||||
for provider in proxy_providers:
|
||||
if isinstance(provider, Unavailable):
|
||||
if provider.name.lower() == name.lower():
|
||||
raise ValueError(f"The proxy provider {provider.name} could not load: {provider.error}")
|
||||
elif provider.__class__.__name__.lower() == name.lower():
|
||||
return provider
|
||||
available = [x.__class__.__name__ for x in proxy_providers if not isinstance(x, Unavailable)]
|
||||
raise ValueError(f"The proxy provider '{name}' was not found. Available: {available}")
|
||||
|
||||
|
||||
def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = False, quiet: bool = False) -> List[Any]:
|
||||
"""
|
||||
Build the proxy providers set in config, in the order a bare query tries them.
|
||||
|
||||
Each proxy provider loads on its own. One that fails is logged and kept as Unavailable, so a bare
|
||||
query skips it and a query that names it reports why. *raise_errors* raises the failure instead.
|
||||
*exclude* holds lowercase class names to leave out.
|
||||
"""
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.proxies import (
|
||||
Basic,
|
||||
ControlD,
|
||||
ExpressVPN,
|
||||
Gluetun,
|
||||
Hola,
|
||||
NordVPN,
|
||||
ProtonVPN,
|
||||
SurfsharkVPN,
|
||||
WindscribeVPN,
|
||||
)
|
||||
|
||||
settings = config.proxy_providers
|
||||
# Control D is last: a bare region reaches it only when nothing else answers, since it changes the account.
|
||||
classes = (Basic, ExpressVPN, NordVPN, ProtonVPN, SurfsharkVPN, WindscribeVPN, Gluetun, Hola, ControlD)
|
||||
|
||||
def build(cls: type) -> Any:
|
||||
key = cls.__name__.lower()
|
||||
if cls is Hola:
|
||||
return Hola() if binaries.HolaProxy else None
|
||||
if cls is ExpressVPN or cls is ProtonVPN:
|
||||
# These also load with no config when their default cookie file exists.
|
||||
provider = cls(**(settings.get(key) or {}))
|
||||
cookie = provider.cache_path if cls is ExpressVPN else provider.cookie_path
|
||||
return provider if settings.get(key) or cookie.is_file() else None
|
||||
return cls(**settings[key]) if settings.get(key) else None
|
||||
|
||||
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.controld import ControlD
|
||||
from unshackle.core.proxies.expressvpn import ExpressVPN
|
||||
from unshackle.core.proxies.hola import Hola
|
||||
from unshackle.core.proxies.nordvpn import NordVPN
|
||||
from unshackle.core.proxies.proton import ProtonVPN
|
||||
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
|
||||
for cls in classes:
|
||||
name = cls.__name__
|
||||
if name.lower() in exclude:
|
||||
continue
|
||||
try:
|
||||
provider = build(cls)
|
||||
if provider is None:
|
||||
continue
|
||||
if not quiet:
|
||||
log.info(f"Loaded {name}: {provider}")
|
||||
except Exception as e:
|
||||
if raise_errors:
|
||||
raise
|
||||
log.warning(f"The {name} proxy provider could not load, so a bare --proxy query skips it: {e}")
|
||||
provider = Unavailable(name, e)
|
||||
proxy_providers.append(provider)
|
||||
|
||||
proxy_config = getattr(main_config, "proxy_providers", {})
|
||||
return proxy_providers
|
||||
|
||||
if proxy_config.get("basic"):
|
||||
proxy_providers.append(Basic(**proxy_config["basic"]))
|
||||
# ExpressVPN/ProtonVPN auto-load when their default cookie file exists (no yaml needed)
|
||||
expressvpn = ExpressVPN(**(proxy_config.get("expressvpn") or {}))
|
||||
if proxy_config.get("expressvpn") or expressvpn.cache_path.is_file():
|
||||
proxy_providers.append(expressvpn)
|
||||
if proxy_config.get("nordvpn"):
|
||||
proxy_providers.append(NordVPN(**proxy_config["nordvpn"]))
|
||||
proton = ProtonVPN(**(proxy_config.get("protonvpn") or {}))
|
||||
if proxy_config.get("protonvpn") or proton.cookie_path.is_file():
|
||||
proxy_providers.append(proton)
|
||||
if proxy_config.get("surfsharkvpn"):
|
||||
proxy_providers.append(SurfsharkVPN(**proxy_config["surfsharkvpn"]))
|
||||
if hasattr(binaries, "HolaProxy") and binaries.HolaProxy:
|
||||
proxy_providers.append(Hola())
|
||||
# last: a bare region reaches it only when nothing else answers, since it changes the account
|
||||
if proxy_config.get("controld"):
|
||||
proxy_providers.append(ControlD(**proxy_config["controld"]))
|
||||
|
||||
if not quiet:
|
||||
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:
|
||||
if raise_errors:
|
||||
raise
|
||||
log.warning(f"Failed to initialize some proxy providers: {e}")
|
||||
def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False) -> List[Any]:
|
||||
"""
|
||||
Load the proxy providers for the REST API and the remote service client.
|
||||
|
||||
WindscribeVPN and Gluetun are not offered on this path. *quiet* drops the per-provider summary
|
||||
lines: rendering a proxy provider asks some of them for their server catalogue over the network,
|
||||
which a repeated caller must not pay for.
|
||||
"""
|
||||
proxy_providers = load_proxy_providers(("windscribevpn", "gluetun"), raise_errors, quiet)
|
||||
if not quiet and not proxy_providers:
|
||||
log.warning("No proxy providers were loaded. Check your proxy provider configuration in unshackle.yaml")
|
||||
return proxy_providers
|
||||
|
||||
|
||||
@@ -99,13 +145,7 @@ def resolve_proxy(proxy: str, proxy_providers: List[Any]) -> Optional[str]:
|
||||
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}")
|
||||
provider = find_provider(proxy_providers, requested_provider)
|
||||
proxy_uri = provider.get_proxy(query)
|
||||
if not proxy_uri:
|
||||
raise ValueError(f"Proxy provider {requested_provider} had no proxy for {query}")
|
||||
|
||||
@@ -160,6 +160,7 @@ class WindscribeVPN(Proxy):
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
timeout=10,
|
||||
)
|
||||
if not res.ok:
|
||||
raise ValueError(f"Failed to get a list of WindscribeVPN locations [{res.status_code}]")
|
||||
|
||||
Reference in New Issue
Block a user