Files
EnuivTools/backend/euniv/proxy.py
T

218 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。也可使用代理池。"""
from __future__ import annotations
from urllib.parse import quote, urlparse
import httpx
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
SOCKS_SCHEMES = ("socks4", "socks5", "socks5h")
OFF_SCHEMES = ("", "off", "none", "direct", "close")
POOL_SCHEMES = ("pool", "auto")
class ProxyError(ValueError):
"""代理配置不符合要求。"""
def parse_proxy(value: str | None) -> str | None:
"""把代理地址规范成内部使用的 URL。空值表示直连。"""
text = (value or "").strip()
if not text:
return None
if "://" not in text:
text = "http://" + text
parsed = urlparse(text)
scheme = (parsed.scheme or "").lower()
if scheme not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
if not parsed.hostname:
raise ProxyError("代理地址不完整")
return text
def build_proxy_url(
scheme: str,
host: str,
port: int,
username: str = "",
password: str = "",
) -> str:
scheme, host, port, username = validate_parts(scheme, host, port, username)
if username or password:
user = quote(username, safe="")
secret = quote(password, safe="")
auth = f"{user}:{secret}@"
else:
auth = ""
return f"{scheme}://{auth}{host}:{port}"
def validate_parts(scheme: str, host: str, port: object, username: str = "") -> tuple[str, str, int, str]:
kind = (scheme or "").strip().lower()
if kind not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
address = (host or "").strip()
if not address or "://" in address or any(ch.isspace() for ch in address):
raise ProxyError("请填写代理地址")
if len(address) > 255:
raise ProxyError("代理地址过长")
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
raise ProxyError("代理端口须为 1 到 65535 的整数")
user = (username or "").strip()
if len(user) > 128:
raise ProxyError("代理账号过长")
return kind, address, port, user
def is_off(scheme: str | None) -> bool:
return (scheme or "").strip().lower() in OFF_SCHEMES
def is_pool(scheme: str | None) -> bool:
return (scheme or "").strip().lower() in POOL_SCHEMES
def uses_pool(account) -> bool:
return bool(getattr(account, "use_proxy_pool", False))
def enabled(account) -> bool:
if uses_pool(account):
return True
return bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
def view_of(account) -> dict:
if uses_pool(account):
return {
"enabled": True,
"scheme": "pool",
"host": "",
"port": None,
"username": "",
"has_password": False,
}
on = bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
return {
"enabled": on,
"scheme": account.proxy_scheme if on else "off",
"host": account.proxy_host or "",
"port": int(account.proxy_port) if account.proxy_port else None,
"username": account.proxy_username or "",
"has_password": bool(account.proxy_password_cipher),
}
def summary_of(account) -> str:
if uses_pool(account):
return "自动"
if not (account.proxy_scheme and account.proxy_host and account.proxy_port):
return ""
return f"{account.proxy_scheme.upper()} {account.proxy_host}:{account.proxy_port}"
def url_of(account) -> str | None:
if uses_pool(account) or not (account.proxy_scheme and account.proxy_host and account.proxy_port):
return None
password = ""
if account.proxy_password_cipher:
from euniv.crypto import decrypt_secret
password = decrypt_secret(account.proxy_password_cipher)
return build_proxy_url(
account.proxy_scheme,
account.proxy_host,
int(account.proxy_port),
account.proxy_username or "",
password,
)
def apply(account, scheme: str, host: str = "", port: object = None, username: str = "", password: str | None = None) -> None:
if is_off(scheme):
clear(account)
return
if is_pool(scheme):
clear(account)
account.use_proxy_pool = True
return
employee_id = getattr(account, "employee_id", "")
if uses_pool(account) and employee_id:
from euniv.proxy_pool import release
release(str(employee_id))
account.use_proxy_pool = False
kind, address, number, user = validate_parts(scheme, host, port, username)
if password is not None and len(str(password)) > 256:
raise ProxyError("代理密码过长")
account.proxy_scheme = kind
account.proxy_host = address
account.proxy_port = number
account.proxy_username = user
if password is None:
return
if password == "":
account.proxy_password_cipher = ""
return
from euniv.crypto import encrypt_secret
account.proxy_password_cipher = encrypt_secret(str(password))
def clear(account) -> None:
account.proxy_scheme = ""
account.proxy_host = ""
account.proxy_port = None
account.proxy_username = ""
account.proxy_password_cipher = ""
account.use_proxy_pool = False
employee_id = getattr(account, "employee_id", "")
if employee_id:
from euniv.proxy_pool import release
release(str(employee_id))
def bind_url(account) -> str | None:
if uses_pool(account):
from euniv.proxy_pool import acquire
return acquire(str(account.employee_id))
return url_of(account)
def client_proxy_args(proxy: str | None, *, asynchronous: bool = False) -> dict:
"""httpx 不认 socks4;SOCKS 走 httpx-socks 传输,HTTP/HTTPS 仍用 proxy=。"""
url = parse_proxy(proxy)
if not url:
return {}
scheme = urlparse(url).scheme.lower()
if scheme in SOCKS_SCHEMES:
if asynchronous:
from httpx_socks import AsyncProxyTransport
return {"transport": AsyncProxyTransport.from_url(url)}
from httpx_socks import SyncProxyTransport
return {"transport": SyncProxyTransport.from_url(url)}
return {"proxy": url}
def sync_httpx_client(proxy: str | None = None, **kwargs) -> httpx.Client:
kwargs.update(client_proxy_args(proxy))
return httpx.Client(**kwargs)
def async_httpx_client(proxy: str | None = None, **kwargs) -> httpx.AsyncClient:
kwargs.update(client_proxy_args(proxy, asynchronous=True))
return httpx.AsyncClient(**kwargs)
def is_proxy_failure(exc: BaseException) -> bool:
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, httpx.ConnectTimeout)):
return True
text = f"{type(exc).__name__} {exc}".lower()
return "proxy" in text or "socks" in text