forked from kenzuya/unshackle
style: turn on ruff UP and B rules and fix every finding
This commit is contained in:
@@ -5,24 +5,24 @@ from __future__ import annotations
|
||||
import ipaddress
|
||||
import re
|
||||
import socket
|
||||
from collections.abc import Iterable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from unidecode import unidecode
|
||||
|
||||
WHOIS = ("whois.cymru.com", 43)
|
||||
TIMEOUT = 3
|
||||
NETWORKS: dict[str, str] = {}
|
||||
FAILED: Optional[str] = None
|
||||
FAILED: str | None = None
|
||||
|
||||
|
||||
def split_selector(query: str) -> tuple[str, Optional[str]]:
|
||||
def split_selector(query: str) -> tuple[str, str | None]:
|
||||
"""Split "fr:paris@-datacamp" into the region query and the network selector after "@"."""
|
||||
query, _, selector = query.partition("@")
|
||||
return query, selector or None
|
||||
|
||||
|
||||
def mapped_query(region: str, value: object) -> Optional[str]:
|
||||
def mapped_query(region: str, value: object) -> str | None:
|
||||
"""
|
||||
Get the query that a server_map value stands for, or None for a plain server value.
|
||||
|
||||
@@ -102,7 +102,7 @@ def select(servers: dict[str, str], selector: str) -> list[str]:
|
||||
def resolve_all(hostnames: Iterable[str]) -> dict[str, str]:
|
||||
"""Resolve hostnames to an IPv4 address each, in parallel. A hostname that does not resolve is left out."""
|
||||
|
||||
def resolve(hostname: str) -> Optional[str]:
|
||||
def resolve(hostname: str) -> str | None:
|
||||
try:
|
||||
return socket.gethostbyname(hostname)
|
||||
except OSError:
|
||||
@@ -110,10 +110,10 @@ def resolve_all(hostnames: Iterable[str]) -> dict[str, str]:
|
||||
|
||||
hostnames = list(dict.fromkeys(hostnames))
|
||||
with ThreadPoolExecutor(16) as pool:
|
||||
return {x: ip for x, ip in zip(hostnames, pool.map(resolve, hostnames)) if ip}
|
||||
return {x: ip for x, ip in zip(hostnames, pool.map(resolve, hostnames), strict=True) if ip}
|
||||
|
||||
|
||||
def describe(hostname: str, ip: Optional[str] = None) -> str:
|
||||
def describe(hostname: str, ip: str | None = None) -> str:
|
||||
"""Name a server with its IP and network, for the line that says which proxy is in use. This never raises."""
|
||||
try:
|
||||
ip = ip or socket.gethostbyname(hostname)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import random
|
||||
import re
|
||||
from typing import Optional, Union
|
||||
|
||||
from requests.utils import prepend_scheme_if_needed
|
||||
from urllib3.util import parse_url
|
||||
@@ -10,7 +9,7 @@ from unshackle.core.utils.redact import mask_proxy
|
||||
|
||||
|
||||
class Basic(Proxy):
|
||||
def __init__(self, **countries: Union[str, list[str]]) -> None:
|
||||
def __init__(self, **countries: str | list[str]) -> None:
|
||||
"""Basic proxy provider that uses the proxies given in the configuration file."""
|
||||
self.countries = {k.lower(): v for k, v in countries.items()}
|
||||
|
||||
@@ -20,7 +19,7 @@ class Basic(Proxy):
|
||||
|
||||
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""Get a proxy URI from the config. A query for a region or an entry number not in the config returns None."""
|
||||
query = query.lower()
|
||||
|
||||
@@ -31,7 +30,7 @@ class Basic(Proxy):
|
||||
country_code = match.group(1)
|
||||
entry = match.group(2)
|
||||
|
||||
servers: Optional[Union[str, list[str]]] = self.countries.get(country_code)
|
||||
servers: str | list[str] | None = self.countries.get(country_code)
|
||||
if not servers:
|
||||
return None
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import socketserver
|
||||
import threading
|
||||
import time
|
||||
from functools import cached_property
|
||||
from typing import Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import requests
|
||||
@@ -328,9 +327,9 @@ class ControlD(Proxy):
|
||||
self,
|
||||
*,
|
||||
token: str,
|
||||
profile: Optional[str] = None,
|
||||
resolver: Optional[str] = None,
|
||||
profiles: Optional[list[dict]] = None,
|
||||
profile: str | None = None,
|
||||
resolver: str | None = None,
|
||||
profiles: list[dict] | None = None,
|
||||
max_profiles: int = 4,
|
||||
) -> None:
|
||||
"""
|
||||
@@ -360,7 +359,7 @@ class ControlD(Proxy):
|
||||
self.configured = {x["profile"]: resolver_id(x["resolver"]) for x in pairs}
|
||||
self.max_profiles = max_profiles
|
||||
self.resolvers = dict(self.configured)
|
||||
self.last_profile: Optional[str] = None
|
||||
self.last_profile: str | None = None
|
||||
|
||||
@cached_property
|
||||
def catalogue(self) -> list[dict]:
|
||||
@@ -385,7 +384,7 @@ class ControlD(Proxy):
|
||||
log.warning(f"Could not read Control D's locations: {e}")
|
||||
return []
|
||||
|
||||
def location(self, query: str) -> Optional[str]:
|
||||
def location(self, query: str) -> str | None:
|
||||
"""Get the identifier of a Control D proxy location for a country or location code."""
|
||||
if not self.catalogue:
|
||||
self.catalogue = self.get_locations()
|
||||
@@ -470,7 +469,7 @@ class ControlD(Proxy):
|
||||
log.info(f"Created profile {name} ({profile}) on the Control D account")
|
||||
return profile
|
||||
|
||||
def claim(self, query: str) -> Optional[str]:
|
||||
def claim(self, query: str) -> str | None:
|
||||
"""Point a profile at this region, unless one already is, and get its resolver ID. Hold STATE."""
|
||||
location = self.location(query)
|
||||
if not location:
|
||||
@@ -492,13 +491,13 @@ class ControlD(Proxy):
|
||||
self.last_profile = profile
|
||||
return resolver
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""Get the local HTTP proxy URI that resolves through Control D for this region."""
|
||||
with STATE:
|
||||
resolver = self.claim(query.lower())
|
||||
return forwarder(resolver).uri if resolver else None
|
||||
|
||||
def last_connection_display(self) -> Optional[str]:
|
||||
def last_connection_display(self) -> str | None:
|
||||
"""Name the location of the last claim, with the resolver ID masked, in place of the loopback URI."""
|
||||
location = LOCATIONS.get(self.last_profile or "")
|
||||
if not location:
|
||||
@@ -507,7 +506,7 @@ class ControlD(Proxy):
|
||||
label = f"{location} - {city}" if city else location
|
||||
return f"({label}): {self.resolvers[self.last_profile][:4]}{REDACTED}@dns.controld.com"
|
||||
|
||||
def get_remote_proxy(self, query: str) -> Optional[str]:
|
||||
def get_remote_proxy(self, query: str) -> str | None:
|
||||
"""Get the `controld://` proxy URI for this region, for a server on another machine."""
|
||||
with STATE:
|
||||
resolver = self.claim(query.lower())
|
||||
|
||||
@@ -9,7 +9,7 @@ import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
@@ -45,13 +45,13 @@ class ExpressVPN(Proxy):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
region_map: Optional[dict[str, str]] = None,
|
||||
server_map: Optional[dict[str, str]] = None,
|
||||
refresh_token: Optional[str] = None,
|
||||
access_token: Optional[str] = None,
|
||||
connection_token: Optional[str] = None,
|
||||
account_json: Optional[str] = None,
|
||||
cache_path: Optional[str] = None,
|
||||
region_map: dict[str, str] | None = None,
|
||||
server_map: dict[str, str] | None = None,
|
||||
refresh_token: str | None = None,
|
||||
access_token: str | None = None,
|
||||
connection_token: str | None = None,
|
||||
account_json: str | None = None,
|
||||
cache_path: str | None = None,
|
||||
timeout: float = 10.0,
|
||||
enable: bool = False,
|
||||
) -> None:
|
||||
@@ -81,13 +81,13 @@ class ExpressVPN(Proxy):
|
||||
self.timeout = timeout
|
||||
self.enable = enable
|
||||
|
||||
self.tokens: Optional[dict] = None
|
||||
self.srt: Optional[str] = None
|
||||
self.locations: Optional[list[dict]] = None
|
||||
self.last_name: Optional[str] = None
|
||||
self.last_index: Optional[int] = None
|
||||
self.last_total: Optional[int] = None
|
||||
self.last_host: Optional[str] = None
|
||||
self.tokens: dict | None = None
|
||||
self.srt: str | None = None
|
||||
self.locations: list[dict] | None = None
|
||||
self.last_name: str | None = None
|
||||
self.last_index: int | None = None
|
||||
self.last_total: int | None = None
|
||||
self.last_host: str | None = None
|
||||
|
||||
self.cache_path = Path(cache_path).expanduser() if cache_path else self.default_cache_path()
|
||||
|
||||
@@ -120,7 +120,7 @@ class ExpressVPN(Proxy):
|
||||
or self.load_cache()
|
||||
)
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
endpoint = self.resolve_endpoint(query.strip().lower())
|
||||
if not endpoint:
|
||||
return None
|
||||
@@ -133,7 +133,7 @@ class ExpressVPN(Proxy):
|
||||
log.debug("ExpressVPN proxy ready: %s", self.last_connection_display() or endpoint)
|
||||
return f"https://cat:{connection_token}@{endpoint}:443"
|
||||
|
||||
def last_connection_display(self) -> Optional[str]:
|
||||
def last_connection_display(self) -> str | None:
|
||||
if not self.last_name or not self.last_host:
|
||||
return None
|
||||
parts = [self.last_name]
|
||||
@@ -141,7 +141,7 @@ class ExpressVPN(Proxy):
|
||||
parts.append(f"#{self.last_index} of {self.last_total}")
|
||||
return f"({', '.join(parts)}): {self.last_host.replace('.expressprovider.com', '')}"
|
||||
|
||||
def resolve_endpoint(self, query: str) -> Optional[str]:
|
||||
def resolve_endpoint(self, query: str) -> str | None:
|
||||
self.last_name = self.last_index = self.last_total = self.last_host = None
|
||||
query = self.server_map.get(query) or query
|
||||
|
||||
@@ -168,7 +168,7 @@ class ExpressVPN(Proxy):
|
||||
return None
|
||||
return self.pick_endpoint(endpoints, server_num)
|
||||
|
||||
def parse_query(self, query: str) -> tuple[Optional[str], Optional[str], Optional[int]]:
|
||||
def parse_query(self, query: str) -> tuple[str | None, str | None, int | None]:
|
||||
"""Parse "us", "us-ny", "us-ny-2"/"us-ny2" into (country, city, server number)."""
|
||||
server_num = None
|
||||
num_match = re.match(r"^(.+?)[-]?(\d+)$", query)
|
||||
@@ -185,7 +185,7 @@ class ExpressVPN(Proxy):
|
||||
# not a country[-city] pattern; caller falls back to slug resolution
|
||||
return None, None, None
|
||||
|
||||
def resolve_location(self, country_code: str, city_query: Optional[str] = None) -> Optional[dict]:
|
||||
def resolve_location(self, country_code: str, city_query: str | None = None) -> dict | None:
|
||||
pool = [x for x in self.get_locations() if str(x.get("country_code") or "").lower() == country_code]
|
||||
if not pool:
|
||||
log.warning("ExpressVPN: no locations found for country '%s'", country_code.upper())
|
||||
@@ -194,7 +194,7 @@ class ExpressVPN(Proxy):
|
||||
return random.choice(pool)
|
||||
return self.match_city(pool, city_query)
|
||||
|
||||
def match_city(self, locations: list[dict], city_query: str) -> Optional[dict]:
|
||||
def match_city(self, locations: list[dict], city_query: str) -> dict | None:
|
||||
"""Find the city that matches the query by abbreviation ("ny"), exact slug, slug prefix, then substring."""
|
||||
city_query = city_query.strip().lower()
|
||||
abbrev, exact, prefix, substring = [], [], [], []
|
||||
@@ -220,7 +220,7 @@ class ExpressVPN(Proxy):
|
||||
log.debug("ExpressVPN: city '%s' matched %d locations", city_query, len(candidates))
|
||||
return candidates[0]
|
||||
|
||||
def resolve_slug(self, query: str) -> Optional[dict]:
|
||||
def resolve_slug(self, query: str) -> dict | None:
|
||||
for loc in self.get_locations():
|
||||
name = str(loc.get("name") or "").lower()
|
||||
keys = (str(loc.get("id") or "").lower(), name, str(loc.get("country_code") or "").lower(), slugify(name))
|
||||
@@ -228,7 +228,7 @@ class ExpressVPN(Proxy):
|
||||
return loc
|
||||
return None
|
||||
|
||||
def pick_endpoint(self, endpoints: list[dict], server_num: Optional[int] = None) -> Optional[str]:
|
||||
def pick_endpoint(self, endpoints: list[dict], server_num: int | None = None) -> str | None:
|
||||
hosts = [str(x.get("host") or "").lower() for x in endpoints if x.get("host")]
|
||||
if not hosts:
|
||||
return None
|
||||
@@ -328,7 +328,7 @@ class ExpressVPN(Proxy):
|
||||
self.tokens = {k: v for k, v in tokens.items() if v}
|
||||
return self.tokens
|
||||
|
||||
def refresh_access_token(self, refresh_token: str) -> Optional[dict]:
|
||||
def refresh_access_token(self, refresh_token: str) -> dict | None:
|
||||
response = self.request(
|
||||
"POST",
|
||||
f"{self.AUTH_BASE}/token",
|
||||
@@ -341,7 +341,7 @@ class ExpressVPN(Proxy):
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def device_login(self) -> Optional[dict]:
|
||||
def device_login(self) -> dict | None:
|
||||
"""One-time interactive bootstrap through the OAuth 2.0 device authorization grant (RFC 8628)."""
|
||||
response = self.request(
|
||||
"POST",
|
||||
@@ -387,7 +387,7 @@ class ExpressVPN(Proxy):
|
||||
log.error("ExpressVPN: device authorization timed out before approval")
|
||||
return None
|
||||
|
||||
def get_srt(self) -> Optional[str]:
|
||||
def get_srt(self) -> str | None:
|
||||
if self.srt and not jwt_expired(self.srt):
|
||||
return self.srt
|
||||
|
||||
@@ -413,7 +413,7 @@ class ExpressVPN(Proxy):
|
||||
self.save_cache(tokens)
|
||||
return srt
|
||||
|
||||
def get_connection_token(self) -> Optional[str]:
|
||||
def get_connection_token(self) -> str | None:
|
||||
tokens = self.get_tokens()
|
||||
connection_token = tokens.get("connection_token")
|
||||
if connection_token and not jwt_expired(connection_token):
|
||||
@@ -434,7 +434,7 @@ class ExpressVPN(Proxy):
|
||||
self.save_cache(tokens)
|
||||
return connection_token
|
||||
|
||||
def select_srt(self, receipts: list[dict], subscription_id: Optional[str]) -> Optional[str]:
|
||||
def select_srt(self, receipts: list[dict], subscription_id: str | None) -> str | None:
|
||||
for receipt in receipts:
|
||||
srt = receipt.get("srt")
|
||||
if "xv.vpn" in jwt_payload(srt).get("entitlements", {}):
|
||||
@@ -496,7 +496,7 @@ def slugify(value: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
|
||||
|
||||
|
||||
def jwt_payload(token: Optional[str]) -> dict:
|
||||
def jwt_payload(token: str | None) -> dict:
|
||||
if not token:
|
||||
return {}
|
||||
try:
|
||||
@@ -509,7 +509,7 @@ def jwt_payload(token: Optional[str]) -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def jwt_expired(token: Optional[str]) -> bool:
|
||||
def jwt_expired(token: str | None) -> bool:
|
||||
"""Treat tokens without an exp claim (proprietary SRT/connection tokens) as non-expiring."""
|
||||
if not token:
|
||||
return True
|
||||
|
||||
@@ -7,7 +7,7 @@ import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
@@ -162,12 +162,12 @@ class Gluetun(Proxy):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
providers: Optional[dict] = None,
|
||||
providers: dict | None = None,
|
||||
base_port: int = 8888,
|
||||
auto_cleanup: bool = True,
|
||||
container_prefix: str = "unshackle-gluetun",
|
||||
auth_user: Optional[str] = None,
|
||||
auth_password: Optional[str] = None,
|
||||
auth_user: str | None = None,
|
||||
auth_password: str | None = None,
|
||||
verify_ip: bool = True,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
@@ -231,7 +231,7 @@ class Gluetun(Proxy):
|
||||
provider_count = len(self.providers)
|
||||
return f"Gluetun ({provider_count} provider{['s', ''][provider_count == 1]})"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""
|
||||
Get an HTTP proxy URI for a Gluetun VPN connection.
|
||||
|
||||
@@ -366,7 +366,7 @@ class Gluetun(Proxy):
|
||||
self.remove_container(container_name)
|
||||
if query_key in self.active_containers:
|
||||
del self.active_containers[query_key]
|
||||
raise coded(RuntimeError(f"Failed to create Gluetun container: {e}"), APIErrorCode.INVALID_PROXY)
|
||||
raise coded(RuntimeError(f"Failed to create Gluetun container: {e}"), APIErrorCode.INVALID_PROXY) from e
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""Stop and remove all managed Gluetun containers."""
|
||||
@@ -408,7 +408,7 @@ class Gluetun(Proxy):
|
||||
success=True,
|
||||
)
|
||||
|
||||
def get_connection_info(self, query: str) -> Optional[dict]:
|
||||
def get_connection_info(self, query: str) -> dict | None:
|
||||
"""
|
||||
Get connection info for a proxy query.
|
||||
|
||||
@@ -590,7 +590,7 @@ class Gluetun(Proxy):
|
||||
log.error(f"Docker pull failed: {result.stderr}")
|
||||
return False
|
||||
except subprocess.TimeoutExpired:
|
||||
raise RuntimeError(f"Timed out pulling Docker image '{image}'")
|
||||
raise RuntimeError(f"Timed out pulling Docker image '{image}'") from None
|
||||
|
||||
def create_container(
|
||||
self,
|
||||
@@ -598,9 +598,9 @@ class Gluetun(Proxy):
|
||||
port: int,
|
||||
provider_name: str,
|
||||
provider_config: dict,
|
||||
country: Optional[str] = None,
|
||||
city: Optional[str] = None,
|
||||
hostname: Optional[str] = None,
|
||||
country: str | None = None,
|
||||
city: str | None = None,
|
||||
hostname: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Make and start a Gluetun Docker container.
|
||||
@@ -766,7 +766,7 @@ class Gluetun(Proxy):
|
||||
success=False,
|
||||
duration_ms=(time.time() - start_time) * 1000,
|
||||
)
|
||||
raise RuntimeError("Docker run command timed out")
|
||||
raise RuntimeError("Docker run command timed out") from None
|
||||
|
||||
if result.returncode != 0:
|
||||
error_msg = result.stderr or "unknown error"
|
||||
@@ -850,7 +850,7 @@ class Gluetun(Proxy):
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||||
return False
|
||||
|
||||
def get_existing_container_info(self, container_name: str) -> Optional[dict]:
|
||||
def get_existing_container_info(self, container_name: str) -> dict | None:
|
||||
"""
|
||||
Find whether a container exists in Docker, and get its info.
|
||||
|
||||
@@ -1038,7 +1038,7 @@ class Gluetun(Proxy):
|
||||
)
|
||||
return False
|
||||
|
||||
def get_container_exit_info(self, container_name: str) -> Optional[dict]:
|
||||
def get_container_exit_info(self, container_name: str) -> dict | None:
|
||||
"""Get exit information for a stopped container."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
|
||||
@@ -2,7 +2,6 @@ import random
|
||||
import re
|
||||
import subprocess
|
||||
from functools import cached_property
|
||||
from typing import Optional
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.proxies.proxy import Proxy, cached_catalogue
|
||||
@@ -14,7 +13,7 @@ class Hola(Proxy):
|
||||
Proxy provider that uses Hola's direct connections through the hola-proxy binary.
|
||||
"""
|
||||
if not binaries.HolaProxy:
|
||||
raise EnvironmentError("hola-proxy executable not found but is required for the Hola proxy provider.")
|
||||
raise OSError("hola-proxy executable not found but is required for the Hola proxy provider.")
|
||||
self.binary = binaries.HolaProxy
|
||||
|
||||
@cached_property
|
||||
@@ -27,7 +26,7 @@ class Hola(Proxy):
|
||||
|
||||
return f"{countries} Countr{['ies', 'y'][countries == 1]}"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""
|
||||
Get an HTTP proxy URI for a Datacenter ('direct') or Residential ('lum') Hola server.
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import json
|
||||
import random
|
||||
import re
|
||||
from functools import cached_property
|
||||
from typing import Optional, Union
|
||||
|
||||
import requests
|
||||
|
||||
@@ -13,7 +12,7 @@ from unshackle.core.utilities import COUNTRY_CODE_ALIASES
|
||||
|
||||
|
||||
class NordVPN(Proxy):
|
||||
def __init__(self, username: str, password: str, server_map: Optional[dict[str, Union[int, str]]] = None) -> None:
|
||||
def __init__(self, username: str, password: str, server_map: dict[str, int | str] | None = None) -> None:
|
||||
"""
|
||||
Proxy provider that uses NordVPN Service Credentials.
|
||||
|
||||
@@ -36,7 +35,7 @@ class NordVPN(Proxy):
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.server_map = server_map or {}
|
||||
self.last_hostname: Optional[str] = None
|
||||
self.last_hostname: str | None = None
|
||||
|
||||
@cached_property
|
||||
def countries(self) -> list[dict]:
|
||||
@@ -49,7 +48,7 @@ class NordVPN(Proxy):
|
||||
|
||||
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""
|
||||
Get an HTTP(SSL) proxy URI for a NordVPN server.
|
||||
|
||||
@@ -133,11 +132,11 @@ class NordVPN(Proxy):
|
||||
self.last_hostname = hostname
|
||||
return f"https://{self.username}:{self.password}@{hostname}:89"
|
||||
|
||||
def last_connection_display(self) -> Optional[str]:
|
||||
def last_connection_display(self) -> str | None:
|
||||
"""Name the last server with its IP and network, so a blocked network can be excluded with '@-'."""
|
||||
return describe(self.last_hostname) if self.last_hostname else None
|
||||
|
||||
def get_country(self, by_id: Optional[int] = None, by_code: Optional[str] = None) -> Optional[dict]:
|
||||
def get_country(self, by_id: int | None = None, by_code: str | None = None) -> dict | None:
|
||||
"""Find a Country and its metadata."""
|
||||
if all(x is None for x in (by_id, by_code)):
|
||||
raise ValueError("At least one search query must be made.")
|
||||
@@ -168,12 +167,10 @@ class NordVPN(Proxy):
|
||||
try:
|
||||
return res.json()
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Could not decode list of NordVPN servers, not JSON data.")
|
||||
raise ValueError("Could not decode list of NordVPN servers, not JSON data.") from None
|
||||
|
||||
@staticmethod
|
||||
def get_recommended_servers(
|
||||
country_id: int, city_id: Optional[int] = None, limit: Optional[int] = None
|
||||
) -> list[dict]:
|
||||
def get_recommended_servers(country_id: int, city_id: int | None = None, limit: int | None = None) -> list[dict]:
|
||||
"""
|
||||
Get the list of recommended Servers for a Country, or for one of its cities.
|
||||
|
||||
@@ -191,7 +188,7 @@ class NordVPN(Proxy):
|
||||
try:
|
||||
return res.json()
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Could not decode list of NordVPN countries, not JSON data.")
|
||||
raise ValueError("Could not decode list of NordVPN countries, not JSON data.") from None
|
||||
|
||||
@staticmethod
|
||||
@cached_catalogue
|
||||
@@ -204,4 +201,4 @@ class NordVPN(Proxy):
|
||||
try:
|
||||
return res.json()
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Could not decode list of NordVPN countries, not JSON data.")
|
||||
raise ValueError("Could not decode list of NordVPN countries, not JSON data.") from None
|
||||
|
||||
@@ -8,7 +8,6 @@ import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
@@ -58,9 +57,9 @@ class ProtonVPN(Proxy):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_map: Optional[dict[str, str]] = None,
|
||||
cookie_path: Optional[str] = None,
|
||||
cache_path: Optional[str] = None,
|
||||
server_map: dict[str, str] | None = None,
|
||||
cookie_path: str | None = None,
|
||||
cache_path: str | None = None,
|
||||
timeout: float = 10.0,
|
||||
enable: bool = False,
|
||||
) -> None:
|
||||
@@ -69,14 +68,14 @@ class ProtonVPN(Proxy):
|
||||
self.enable = enable
|
||||
self.api_base = self.API_BASE
|
||||
|
||||
self.uid: Optional[str] = None
|
||||
self.access_token: Optional[str] = None
|
||||
self.refresh_token: Optional[str] = None
|
||||
self.logicals: Optional[list[dict]] = None
|
||||
self.max_tier: Optional[int] = None
|
||||
self.last_name: Optional[str] = None
|
||||
self.last_city: Optional[str] = None
|
||||
self.last_host: Optional[str] = None
|
||||
self.uid: str | None = None
|
||||
self.access_token: str | None = None
|
||||
self.refresh_token: str | None = None
|
||||
self.logicals: list[dict] | None = None
|
||||
self.max_tier: int | None = None
|
||||
self.last_name: str | None = None
|
||||
self.last_city: str | None = None
|
||||
self.last_host: str | None = None
|
||||
|
||||
self.cookie_path = Path(cookie_path).expanduser() if cookie_path else self.default_cookie_path()
|
||||
self.cache_path = Path(cache_path).expanduser() if cache_path else self.default_cache_path()
|
||||
@@ -97,7 +96,7 @@ class ProtonVPN(Proxy):
|
||||
f"{countries} Countr{'ies' if countries != 1 else 'y'} ({len(servers)} Server{'s' if servers != 1 else ''})"
|
||||
)
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
self.ensure_session()
|
||||
server = self.resolve_server(query.strip().lower())
|
||||
if not server:
|
||||
@@ -113,13 +112,13 @@ class ProtonVPN(Proxy):
|
||||
user, pwd = (quote(c, safe="") for c in creds)
|
||||
return f"https://{user}:{pwd}@{host}:{port}"
|
||||
|
||||
def last_connection_display(self) -> Optional[str]:
|
||||
def last_connection_display(self) -> str | None:
|
||||
if not self.last_name or not self.last_host:
|
||||
return None
|
||||
label = f"{self.last_name} - {self.last_city}" if self.last_city else self.last_name
|
||||
return f"({label}): {self.last_host.replace('.protonvpn.net', '')}"
|
||||
|
||||
def resolve_server(self, query: str) -> Optional[dict]:
|
||||
def resolve_server(self, query: str) -> dict | None:
|
||||
self.last_name = self.last_city = self.last_host = None
|
||||
query = self.server_map.get(query, query)
|
||||
country, city, server_num = self.parse_query(query)
|
||||
@@ -149,7 +148,7 @@ class ProtonVPN(Proxy):
|
||||
return None
|
||||
return self.select(pool, server_num)
|
||||
|
||||
def parse_query(self, query: str) -> tuple[Optional[str], Optional[str], Optional[int]]:
|
||||
def parse_query(self, query: str) -> tuple[str | None, str | None, int | None]:
|
||||
"""Parse "us", "us12"/"us-12"/"us#12" (server #12), and "us:ny" (city)."""
|
||||
city = None
|
||||
if ":" in query:
|
||||
@@ -180,7 +179,7 @@ class ProtonVPN(Proxy):
|
||||
substring.append(s)
|
||||
return exact or prefix or substring
|
||||
|
||||
def select(self, pool: list[dict], server_num: Optional[int]) -> dict:
|
||||
def select(self, pool: list[dict], server_num: int | None) -> dict:
|
||||
if server_num is not None:
|
||||
matches = [s for s in pool if server_no(s) == server_num]
|
||||
if matches:
|
||||
@@ -218,7 +217,7 @@ class ProtonVPN(Proxy):
|
||||
vpn = (response.json().get("VPN") or {}) if response is not None else {}
|
||||
return vpn if "MaxTier" in vpn else {}
|
||||
|
||||
def get_browser_token(self) -> Optional[tuple[str, str]]:
|
||||
def get_browser_token(self) -> tuple[str, str] | None:
|
||||
response = self.api("GET", f"/vpn/v1/browser/token?Duration={self.TOKEN_DURATION}")
|
||||
if response is None:
|
||||
return None
|
||||
@@ -228,7 +227,7 @@ class ProtonVPN(Proxy):
|
||||
log.error("Proton: browser/token response missing credentials")
|
||||
return None
|
||||
|
||||
def api(self, method: str, path: str) -> Optional[requests.Response]:
|
||||
def api(self, method: str, path: str) -> requests.Response | None:
|
||||
"""Call the Proton API, and refresh the login session one time on a 401."""
|
||||
if not self.access_token:
|
||||
self.load_session()
|
||||
@@ -450,7 +449,7 @@ def slugify(value: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
|
||||
|
||||
|
||||
def server_no(server: dict) -> Optional[int]:
|
||||
def server_no(server: dict) -> int | None:
|
||||
"""Proton's server number from the logical name, e.g. "US#231" -> 231, "US-CO#21" -> 21."""
|
||||
match = re.search(r"#(\d+)", str(server.get("Name") or ""))
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import functools
|
||||
import time
|
||||
from abc import abstractmethod
|
||||
from typing import Any, Callable, Optional, TypeVar
|
||||
from collections.abc import Callable
|
||||
from typing import Any, TypeVar
|
||||
|
||||
CATALOGUE_TTL = 600.0
|
||||
CATALOGUES: dict[str, tuple[float, Any]] = {}
|
||||
@@ -47,7 +48,7 @@ class Proxy:
|
||||
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
|
||||
|
||||
@abstractmethod
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""
|
||||
Get a proxy URI from the proxy provider.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import ipaddress
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, List, Optional
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import click
|
||||
@@ -33,11 +33,11 @@ class Unavailable(Proxy):
|
||||
def __repr__(self) -> str:
|
||||
return f"failed to load ({self.error})"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def find_provider(proxy_providers: List[Any], name: str, hint: str = "") -> Any:
|
||||
def find_provider(proxy_providers: list[Any], name: str, hint: str = "") -> Any:
|
||||
"""
|
||||
Find a proxy provider by its class name, case-insensitive.
|
||||
|
||||
@@ -58,7 +58,7 @@ def find_provider(proxy_providers: List[Any], name: str, hint: str = "") -> Any:
|
||||
raise coded(ValueError(f"{message}. {hint}" if hint else message), APIErrorCode.INVALID_PROXY)
|
||||
|
||||
|
||||
def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = False, quiet: bool = False) -> List[Any]:
|
||||
def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = False, quiet: bool = False) -> list[Any]:
|
||||
"""
|
||||
Build the proxy providers set in config: Basic first, then config key order, Control D last.
|
||||
|
||||
@@ -124,7 +124,7 @@ def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = Fal
|
||||
return proxy_providers
|
||||
|
||||
|
||||
def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False) -> List[Any]:
|
||||
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.
|
||||
|
||||
@@ -140,7 +140,7 @@ def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False)
|
||||
CITY_HINT = "A city query needs a proxy provider prefix, for example nordvpn:us:seattle."
|
||||
|
||||
|
||||
def split_proxy_query(proxy: str, proxy_providers: List[Any]) -> tuple[Optional[str], str]:
|
||||
def split_proxy_query(proxy: str, proxy_providers: list[Any]) -> tuple[str | None, str]:
|
||||
"""
|
||||
Split a proxy value into the proxy provider that its prefix names and the query for it.
|
||||
|
||||
@@ -156,7 +156,7 @@ def split_proxy_query(proxy: str, proxy_providers: List[Any]) -> tuple[Optional[
|
||||
return name, query
|
||||
|
||||
|
||||
def pick_proxy(proxy_providers: List[Any], query: str, provider_name: Optional[str] = None) -> tuple[Any, str]:
|
||||
def pick_proxy(proxy_providers: list[Any], query: str, provider_name: str | None = None) -> tuple[Any, str]:
|
||||
"""
|
||||
Get a proxy provider and its proxy URI: from the named one, or else from the first one that answers.
|
||||
|
||||
@@ -247,7 +247,7 @@ def describe_explicit_proxy(uri: str) -> str:
|
||||
return f"Using explicit Proxy: {mask_proxy(uri)}"
|
||||
|
||||
|
||||
def resolve_proxy(proxy: str, proxy_providers: List[Any]) -> Optional[str]:
|
||||
def resolve_proxy(proxy: str, proxy_providers: list[Any]) -> str | None:
|
||||
"""Change a proxy parameter to a real proxy URI.
|
||||
|
||||
Accepts:
|
||||
|
||||
@@ -7,7 +7,6 @@ import socket
|
||||
import ssl
|
||||
import threading
|
||||
from functools import cache, cached_property, partial
|
||||
from typing import Optional
|
||||
|
||||
import certifi
|
||||
import requests
|
||||
@@ -26,7 +25,7 @@ CONNECT_TIMEOUT = 30
|
||||
CHUNK = 65536
|
||||
TLS = ssl.create_default_context(cafile=certifi.where()) # the same CA bundle as requests
|
||||
PINS: dict[tuple[str, str], int] = {}
|
||||
LOOP: Optional[asyncio.AbstractEventLoop] = None
|
||||
LOOP: asyncio.AbstractEventLoop | None = None
|
||||
STATE = threading.Lock()
|
||||
|
||||
|
||||
@@ -84,7 +83,7 @@ def pinned(ip: str, hostname: str) -> int:
|
||||
|
||||
|
||||
class SurfsharkVPN(Proxy):
|
||||
def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None) -> None:
|
||||
def __init__(self, username: str, password: str, server_map: dict[str, str] | None = None) -> None:
|
||||
"""
|
||||
Proxy provider that uses SurfsharkVPN Service Credentials.
|
||||
|
||||
@@ -122,7 +121,7 @@ class SurfsharkVPN(Proxy):
|
||||
country, sep, city = str(region).lower().partition(":")
|
||||
self.server_map[COUNTRY_CODE_ALIASES.get(country, country) + sep + city] = server
|
||||
|
||||
self.last_server: Optional[tuple[str, str]] = None
|
||||
self.last_server: tuple[str, str] | None = None
|
||||
|
||||
@cached_property
|
||||
def countries(self) -> list[dict]:
|
||||
@@ -135,7 +134,7 @@ class SurfsharkVPN(Proxy):
|
||||
|
||||
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""
|
||||
Get an HTTP(SSL) proxy URI for a SurfsharkVPN server.
|
||||
|
||||
@@ -186,7 +185,7 @@ class SurfsharkVPN(Proxy):
|
||||
self.last_server = (hostname, ip)
|
||||
return f"http://{self.username}:{self.password}@127.0.0.1:{pinned(ip, hostname)}"
|
||||
|
||||
def last_connection_display(self) -> Optional[str]:
|
||||
def last_connection_display(self) -> str | None:
|
||||
"""Name the pinned server with its IP and network, so it can be pinned again or excluded with '@-'."""
|
||||
return describe(*self.last_server) if self.last_server else None
|
||||
|
||||
@@ -230,7 +229,7 @@ class SurfsharkVPN(Proxy):
|
||||
server = server.lower()
|
||||
return server if server.endswith(".surfshark.com") else f"{server}.prod.surfshark.com"
|
||||
|
||||
def get_city_servers(self, servers: list[dict], city: Optional[str] = None) -> list[dict]:
|
||||
def get_city_servers(self, servers: list[dict], city: str | None = None) -> list[dict]:
|
||||
"""
|
||||
Get a country's servers, optionally filtered by city.
|
||||
|
||||
@@ -266,4 +265,4 @@ class SurfsharkVPN(Proxy):
|
||||
try:
|
||||
return res.json()
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Could not decode list of SurfsharkVPN countries, not JSON data.")
|
||||
raise ValueError("Could not decode list of SurfsharkVPN countries, not JSON data.") from None
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from functools import cached_property
|
||||
from typing import Iterator, Optional
|
||||
|
||||
import requests
|
||||
|
||||
@@ -11,7 +11,7 @@ from unshackle.core.proxies.proxy import Proxy, cached_catalogue
|
||||
|
||||
|
||||
class WindscribeVPN(Proxy):
|
||||
def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None) -> None:
|
||||
def __init__(self, username: str, password: str, server_map: dict[str, str] | None = None) -> None:
|
||||
"""
|
||||
Proxy provider that uses WindscribeVPN Service Credentials.
|
||||
|
||||
@@ -32,7 +32,7 @@ class WindscribeVPN(Proxy):
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.server_map = server_map or {}
|
||||
self.last_hostname: Optional[str] = None
|
||||
self.last_hostname: str | None = None
|
||||
|
||||
@cached_property
|
||||
def countries(self) -> list[dict]:
|
||||
@@ -45,7 +45,7 @@ class WindscribeVPN(Proxy):
|
||||
|
||||
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
|
||||
|
||||
def get_proxy(self, query: str) -> Optional[str]:
|
||||
def get_proxy(self, query: str) -> str | None:
|
||||
"""
|
||||
Get an HTTPS proxy URI for a WindscribeVPN server.
|
||||
|
||||
@@ -70,7 +70,7 @@ class WindscribeVPN(Proxy):
|
||||
if selector:
|
||||
if not re.fullmatch(r"[a-z]+", query):
|
||||
raise ValueError(f"'{query}' is already one WindscribeVPN server, so it takes no '@' network selector.")
|
||||
hostname: Optional[str] = self.get_random_server(query, city, selector)
|
||||
hostname: str | None = self.get_random_server(query, city, selector)
|
||||
elif mapping := self.server_map.get(server_map_key) or self.server_map.get(query):
|
||||
if mapped := mapped_query(server_map_key, mapping):
|
||||
return self.get_proxy(mapped)
|
||||
@@ -92,7 +92,7 @@ class WindscribeVPN(Proxy):
|
||||
hostname = self.last_hostname = hostname.split(":")[0]
|
||||
return f"https://{self.username}:{self.password}@{hostname}:443"
|
||||
|
||||
def last_connection_display(self) -> Optional[str]:
|
||||
def last_connection_display(self) -> str | None:
|
||||
"""Name the last server with its IP and network, so a blocked network can be excluded with '@-'."""
|
||||
return describe(self.last_hostname) if self.last_hostname else None
|
||||
|
||||
@@ -104,7 +104,7 @@ class WindscribeVPN(Proxy):
|
||||
if host.get("hostname"):
|
||||
yield host["hostname"]
|
||||
|
||||
def get_specific_server(self, country_code: str, server_num: str) -> Optional[str]:
|
||||
def get_specific_server(self, country_code: str, server_num: str) -> str | None:
|
||||
"""
|
||||
Find a server by country code and number, e.g. "sg007" -> "sg-007.totallyacdn.com".
|
||||
|
||||
@@ -123,9 +123,7 @@ class WindscribeVPN(Proxy):
|
||||
return hostname
|
||||
return None
|
||||
|
||||
def get_random_server(
|
||||
self, country_code: str, city: Optional[str] = None, selector: Optional[str] = None
|
||||
) -> Optional[str]:
|
||||
def get_random_server(self, country_code: str, city: str | None = None, selector: str | None = None) -> str | None:
|
||||
"""
|
||||
Get a random server hostname for a country, optionally filtered by city.
|
||||
|
||||
@@ -185,4 +183,4 @@ class WindscribeVPN(Proxy):
|
||||
data = res.json()
|
||||
return data.get("data", [])
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Could not decode list of WindscribeVPN locations, not JSON data.")
|
||||
raise ValueError("Could not decode list of WindscribeVPN locations, not JSON data.") from None
|
||||
|
||||
Reference in New Issue
Block a user