douyinWEB/backend/app/tiktok_socks.py
hackrobot 1e8eb0130a Sync dylive production working tree to test3.
Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
2026-10-14 07:04:18 +00:00

139 lines
4.8 KiB
Python

# -*- coding: utf-8 -*-
"""TikTok upload SOCKS5 profiles (optional per account, default off)."""
from __future__ import annotations
import uuid
from typing import Any
from urllib.parse import quote
SETTINGS_KEY = "tiktok_upload_socks_profiles"
def _norm_profile(raw: Any) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
pid = str(raw.get("id") or "").strip() or str(uuid.uuid4())
server = str(raw.get("server") or "").strip()
try:
port = int(raw.get("port") or 0)
except Exception:
port = 0
ptype = str(raw.get("type") or "socks5").strip().lower() or "socks5"
if ptype not in {"socks5", "socks5h"}:
ptype = "socks5"
return {
"id": pid,
"label": str(raw.get("label") or server or pid).strip() or pid,
"type": ptype,
"server": server,
"port": port,
"username": str(raw.get("username") or ""),
"password": str(raw.get("password") or ""),
}
def list_socks_profiles(cfg: dict[str, Any] | None = None, *, public: bool = False) -> list[dict[str, Any]]:
from . import db
settings = dict(cfg if cfg is not None else db.get_settings_map())
raw = settings.get(SETTINGS_KEY)
rows: list[dict[str, Any]] = []
if isinstance(raw, list):
for item in raw:
p = _norm_profile(item)
if p and p["server"] and p["port"] > 0:
rows.append(p)
if not public:
return rows
out = []
for p in rows:
pwd = str(p.get("password") or "")
q = dict(p)
q["has_password"] = bool(pwd.strip())
q["password"] = ("***" + pwd[-4:]) if len(pwd) > 4 else ("***" if pwd else "")
out.append(q)
return out
def get_socks_profile(profile_id: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
pid = str(profile_id or "").strip()
if not pid:
return None
for p in list_socks_profiles(cfg, public=False):
if str(p.get("id") or "") == pid:
return p
return None
def socks_proxy_url(profile: dict[str, Any] | None) -> str:
"""Build SOCKS URL for requests/TiktokAutoUploader. Prefer socks5h (remote DNS)."""
if not profile:
return ""
server = str(profile.get("server") or "").strip()
try:
port = int(profile.get("port") or 0)
except Exception:
port = 0
if not server or port <= 0:
return ""
user = str(profile.get("username") or "")
pwd = str(profile.get("password") or "")
scheme = "socks5h"
if user or pwd:
return f"{scheme}://{quote(user, safe='')}:{quote(pwd, safe='')}@{server}:{port}"
return f"{scheme}://{server}:{port}"
def resolve_channel_socks_proxy(channel: dict[str, Any] | None, cfg: dict[str, Any] | None = None) -> str:
"""Per-account SOCKS if opted in; else fall back to global residential / egress uploads proxy."""
if channel:
enabled = channel.get("socks_enabled")
if isinstance(enabled, str):
enabled = enabled.strip().lower() in {"1", "true", "yes", "on"}
if enabled:
pid = str(channel.get("socks_profile_id") or "").strip()
prof = get_socks_profile(pid, cfg)
if not prof:
rows = list_socks_profiles(cfg, public=False)
prof = rows[0] if rows else None
url = socks_proxy_url(prof)
if url:
return url
try:
from . import egress_hub
return egress_hub.resolve_upload_proxy(cfg) or ""
except Exception:
return ""
def merge_socks_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
"""Merge UI patch; keep existing password when incoming is blank or ***masked."""
existing = {str(p["id"]): p for p in list_socks_profiles(existing_cfg, public=False)}
out: list[dict[str, Any]] = []
src = incoming if isinstance(incoming, list) else []
for item in src:
p = _norm_profile(item)
if not p:
continue
pid = str(p["id"])
old = existing.get(pid) or {}
pwd = str(p.get("password") or "")
if (not pwd.strip()) or pwd.startswith("***"):
p["password"] = str(old.get("password") or "")
if not p["server"] or int(p.get("port") or 0) <= 0:
continue
out.append(p)
if not src:
return list(existing.values())
return out
def save_socks_profiles(profiles: list[dict[str, Any]]) -> list[dict[str, Any]]:
from . import db
cfg = db.get_settings_map()
merged = merge_socks_profiles_patch(profiles, cfg)
db.update_settings_map({SETTINGS_KEY: merged})
return list_socks_profiles(db.get_settings_map(), public=True)