mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 15:35:06 +00:00
55 lines
1.8 KiB
Python
55 lines
1.8 KiB
Python
import random
|
|
import re
|
|
|
|
from requests.utils import prepend_scheme_if_needed
|
|
from urllib3.util import parse_url
|
|
|
|
from unshackle.core.proxies.proxy import Proxy
|
|
from unshackle.core.utils.redact import mask_proxy
|
|
|
|
|
|
class Basic(Proxy):
|
|
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()}
|
|
|
|
def __repr__(self) -> str:
|
|
countries = len(self.countries)
|
|
servers = len(self.countries.values())
|
|
|
|
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
|
|
|
|
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()
|
|
|
|
match = re.fullmatch(r"([a-z]{2})(\d+)?", query)
|
|
if not match:
|
|
return None
|
|
|
|
country_code = match.group(1)
|
|
entry = match.group(2)
|
|
|
|
servers: str | list[str] | None = self.countries.get(country_code)
|
|
if not servers:
|
|
return None
|
|
|
|
if isinstance(servers, str):
|
|
proxy = servers
|
|
elif entry:
|
|
if not 1 <= int(entry) <= len(servers):
|
|
return None
|
|
proxy = servers[int(entry) - 1]
|
|
else:
|
|
proxy = random.choice(servers)
|
|
|
|
proxy = prepend_scheme_if_needed(proxy, "http")
|
|
parsed_proxy = parse_url(proxy)
|
|
if not parsed_proxy.host:
|
|
raise ValueError(
|
|
f"The proxy '{mask_proxy(proxy, mask_host=True, allow_debug=False)}' "
|
|
"is not a valid proxy URI supported by Python-Requests."
|
|
)
|
|
|
|
return proxy
|