feat: implement unified data sources, proxy routing and local API
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
"""Project-local, non-secret configuration."""
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
DEFAULTS = {
|
||||
"network_mode": "prefer_proxy", "pool_url": "http://127.0.0.1:5010",
|
||||
"pool_project": r"C:\Users\Jayson\Desktop\proxy_pool",
|
||||
"backup_proxies": [], "request_interval": 1.2, "timeout": 30, "retries": 3,
|
||||
}
|
||||
|
||||
|
||||
def proxy_url(value):
|
||||
value = str(value).strip()
|
||||
if not value:
|
||||
return ""
|
||||
value = value if "://" in value else "http://" + value
|
||||
parsed = urlparse(value)
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
port = None
|
||||
if parsed.scheme not in ("http", "https", "socks5") or not parsed.hostname or not port:
|
||||
raise ValueError("代理格式应为 IP:端口或 http://IP:端口")
|
||||
if parsed.username or parsed.password:
|
||||
raise ValueError("此版本请使用不带账号密码的代理地址")
|
||||
return value
|
||||
|
||||
|
||||
class SettingsStore:
|
||||
def __init__(self, directory):
|
||||
self.path = Path(directory) / "settings.json"
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def read(self):
|
||||
with self.lock:
|
||||
values = json.loads(self.path.read_text(encoding="utf-8")) if self.path.exists() else {}
|
||||
return {**DEFAULTS, **{k: v for k, v in values.items() if k in DEFAULTS}}
|
||||
|
||||
def update(self, values):
|
||||
with self.lock:
|
||||
values = {**self.read(), **{k: v for k, v in values.items() if k in DEFAULTS}}
|
||||
if values["network_mode"] not in ("direct", "prefer_proxy", "proxy_only"):
|
||||
raise ValueError("未知网络策略")
|
||||
parsed = urlparse(values["pool_url"])
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password:
|
||||
raise ValueError("代理池 API 地址无效")
|
||||
values["pool_url"] = values["pool_url"].rstrip("/")
|
||||
for key, low, high in [("request_interval", .3, 60), ("timeout", 5, 120), ("retries", 1, 6)]:
|
||||
values[key] = float(values[key]) if key == "request_interval" else int(values[key])
|
||||
if not low <= values[key] <= high:
|
||||
raise ValueError(f"{key} 应在 {low} 到 {high} 之间")
|
||||
proxies = values["backup_proxies"]
|
||||
if isinstance(proxies, str):
|
||||
proxies = proxies.splitlines()
|
||||
values["backup_proxies"] = list(dict.fromkeys(proxy_url(p) for p in proxies if str(p).strip()))
|
||||
temporary = self.path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(values, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
temporary.replace(self.path)
|
||||
return values
|
||||
Reference in New Issue
Block a user