diff --git a/backend/app/db.py b/backend/app/db.py index fc856c4..c80a3a4 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -272,6 +272,14 @@ def init_db() -> None: conn.execute( "ALTER TABLE tiktok_channels ADD COLUMN cookie_saved_at REAL NOT NULL DEFAULT 0" ) + if "socks_enabled" not in tt_cols: + conn.execute( + "ALTER TABLE tiktok_channels ADD COLUMN socks_enabled INTEGER NOT NULL DEFAULT 0" + ) + if "socks_profile_id" not in tt_cols: + conn.execute( + "ALTER TABLE tiktok_channels ADD COLUMN socks_profile_id TEXT NOT NULL DEFAULT ''" + ) sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()} for col, ddl in [ ("oauth_ok", "INTEGER NOT NULL DEFAULT -1"), @@ -426,6 +434,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "tiktok_upload_min_gap_sec": 720, "tiktok_channel_min_gap_sec": 2400, "tiktok_delete_clip_after_upload": True, + # TikTok upload SOCKS profiles (pool); each account opts in via socks_enabled=0 by default + "tiktok_upload_socks_profiles": [], "tiktok_auto_retry_failed": False, "tiktok_auto_retry_max_attempts": 3, "tiktok_auto_retry_interval_sec": 300, diff --git a/backend/app/main.py b/backend/app/main.py index f8a49b0..b98416e 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -48,6 +48,7 @@ from .models import ( TikTokJobsBulkBody, TikTokOAuthConfig, TikTokSessionBody, + TikTokSocksProfilesBody, TikTokUploadNowBody, YouTubeVideoUpdate, ) @@ -821,6 +822,8 @@ async def shorts_schedule() -> dict[str, Any]: def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: if not ch: return None + from . import tiktok_socks + out = dict(ch) for k in ("client_secret", "refresh_token", "access_token"): v = str(out.get(k) or "") @@ -830,6 +833,10 @@ def _public_tiktok_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: out["authorized"] = tiktok_session.channel_has_session(ch) out["auth_mode"] = "cookie" if out["authorized"] else "" out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1) + out["socks_enabled"] = bool(int(out.get("socks_enabled") or 0)) + out["socks_profile_id"] = str(out.get("socks_profile_id") or "").strip() + prof = tiktok_socks.get_socks_profile(out["socks_profile_id"]) + out["socks_profile_label"] = str((prof or {}).get("label") or "") if out["socks_enabled"] else "" out.update(tiktok_session.cookie_age_info(ch, persist_backfill=True)) return out @@ -861,6 +868,9 @@ async def tiktok_status() -> dict[str, Any]: st["session_ready"] = bool(setup.get("steps") and setup["steps"][-1].get("done")) st["setup"] = setup st["channels"] = [_public_tiktok_channel(c) for c in (await _db(tiktok_db.list_tiktok_channels))] + from . import tiktok_socks + + st["socks_profiles"] = tiktok_socks.list_socks_profiles(cfg, public=True) return st @@ -988,6 +998,8 @@ async def tiktok_channels_create(body: TikTokChannelCreate) -> dict[str, Any]: description_template=body.description_template, privacy_level=body.privacy_level, note=body.note, + socks_enabled=bool(body.socks_enabled), + socks_profile_id=str(body.socks_profile_id or ""), ) return {"ok": True, "channel": _public_tiktok_channel(ch)} @@ -1005,6 +1017,15 @@ async def tiktok_channels_update(channel_pk: str, body: TikTokChannelUpdate) -> return {"ok": True, "channel": _public_tiktok_channel(ch)} +@app.put("/api/tiktok/socks-profiles") +async def tiktok_socks_profiles_put(body: TikTokSocksProfilesBody) -> dict[str, Any]: + """Save TikTok SOCKS profile pool (used by per-account selection).""" + from . import tiktok_socks + + profiles = await _db(tiktok_socks.save_socks_profiles, body.profiles or []) + return {"ok": True, "socks_profiles": profiles} + + @app.delete("/api/tiktok/channels/{channel_pk}") async def tiktok_channels_delete(channel_pk: str) -> dict[str, Any]: from . import tiktok_db diff --git a/backend/app/models.py b/backend/app/models.py index 87749eb..6fbdd5a 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -290,6 +290,8 @@ class TikTokChannelCreate(BaseModel): description_template: str = "" privacy_level: str = "PUBLIC_TO_EVERYONE" note: str = "" + socks_enabled: bool = False + socks_profile_id: str = "" class TikTokChannelUpdate(BaseModel): @@ -299,6 +301,12 @@ class TikTokChannelUpdate(BaseModel): description_template: Optional[str] = None privacy_level: Optional[str] = None note: Optional[str] = None + socks_enabled: Optional[bool] = None + socks_profile_id: Optional[str] = None + + +class TikTokSocksProfilesBody(BaseModel): + profiles: list[dict[str, Any]] = Field(default_factory=list) class TikTokJobsBulkBody(BaseModel): diff --git a/backend/app/tiktok_db.py b/backend/app/tiktok_db.py index e1204b9..a279bfd 100644 --- a/backend/app/tiktok_db.py +++ b/backend/app/tiktok_db.py @@ -60,6 +60,8 @@ def create_tiktok_channel( description_template: str = "", privacy_level: str = "SELF_ONLY", note: str = "", + socks_enabled: bool = False, + socks_profile_id: str = "", ) -> dict[str, Any]: now = time.time() cid = str(uuid.uuid4()) @@ -74,8 +76,9 @@ def create_tiktok_channel( id, name, tiktok_open_id, tiktok_username, client_key, client_secret, refresh_token, access_token, token_expires_at, enabled, daily_min, daily_max, title_template, description_template, privacy_level, last_assigned_at, - oauth_ok, oauth_checked_at, oauth_error, note, created_at, updated_at - ) VALUES (?, ?, '', '', '', '', '', '', 0, ?, ?, ?, ?, ?, ?, 0, -1, 0, '', ?, ?, ?) + oauth_ok, oauth_checked_at, oauth_error, note, cookie_saved_at, + socks_enabled, socks_profile_id, created_at, updated_at + ) VALUES (?, ?, '', '', '', '', '', '', 0, ?, ?, ?, ?, ?, ?, 0, -1, 0, '', ?, 0, ?, ?, ?, ?) """, ( cid, @@ -87,6 +90,8 @@ def create_tiktok_channel( description_template, (privacy_level or "SELF_ONLY").strip(), (note or "").strip(), + 1 if socks_enabled else 0, + str(socks_profile_id or "").strip(), now, now, ), @@ -103,6 +108,7 @@ def update_tiktok_channel(channel_pk: str, **fields: Any) -> dict[str, Any] | No "refresh_token", "access_token", "token_expires_at", "enabled", "daily_min", "daily_max", "title_template", "description_template", "privacy_level", "last_assigned_at", "oauth_ok", "oauth_checked_at", "oauth_error", "note", "cookie_saved_at", + "socks_enabled", "socks_profile_id", } with _lock: conn = _connect() @@ -117,10 +123,12 @@ def update_tiktok_channel(channel_pk: str, **fields: Any) -> dict[str, Any] | No continue if k in {"daily_min", "daily_max"}: v = _force_daily(int(v)) - if k == "enabled": + if k in {"enabled", "socks_enabled"}: v = 1 if v else 0 if k == "oauth_ok" and v is not None: v = int(v) + if k == "socks_profile_id": + v = str(v or "").strip() sets.append(f"{k} = ?") params.append(v) if not sets: diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index b8fe090..a7bb75b 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -13,6 +13,7 @@ from . import tiktok_db from . import tiktok_session from .shorts_clip import record_clip, resolve_stream_candidates from .tiktok_schedule import pick_upload_at, schedule_board +from .tiktok_socks import resolve_channel_socks_proxy from .tiktok_upload import upload_tiktok_mp4 from .timeutil import push_date_from_ts @@ -536,12 +537,14 @@ class TikTokPipeline: title = str(channel.get("title_template") or "").strip() if not tiktok_db.touch_tiktok_upload_lease(jid): return + proxy = resolve_channel_socks_proxy(channel, cfg) or None result = await upload_tiktok_mp4( file_path=clip, title=title, description="", privacy_level=str(channel.get("privacy_level") or "PUBLIC_TO_EVERYONE"), channel_pk=str(channel["id"]), + proxy=proxy, ) pub = str(result.get("publish_id") or "").strip() or f"cookie-{jid[:12]}" vid = str(result.get("video_id") or "").strip() or pub diff --git a/backend/app/tiktok_socks.py b/backend/app/tiktok_socks.py new file mode 100644 index 0000000..1c39d0b --- /dev/null +++ b/backend/app/tiktok_socks.py @@ -0,0 +1,132 @@ +# -*- 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: + """Return proxy URL only when this TikTok account opted into SOCKS; else empty (direct).""" + if not channel: + return "" + enabled = channel.get("socks_enabled") + if isinstance(enabled, str): + enabled = enabled.strip().lower() in {"1", "true", "yes", "on"} + if not enabled: + return "" + 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 + return socks_proxy_url(prof) + + +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) diff --git a/backend/requirements.txt b/backend/requirements.txt index f14948f..65f729d 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -10,5 +10,6 @@ boto3==1.35.99 fake-useragent>=1.4 requests-auth-aws-sigv4>=0.7 requests>=2.31 +PySocks>=1.7.1 python-dotenv>=1.0 diff --git a/backend/tests/test_tiktok_socks.py b/backend/tests/test_tiktok_socks.py new file mode 100644 index 0000000..580b39a --- /dev/null +++ b/backend/tests/test_tiktok_socks.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +from app.tiktok_socks import ( + merge_socks_profiles_patch, + resolve_channel_socks_proxy, + socks_proxy_url, +) + + +def test_socks_proxy_url_builds_socks5h(): + url = socks_proxy_url( + { + "server": "1.2.3.4", + "port": 1080, + "username": "u", + "password": "p", + "type": "socks5", + } + ) + assert url.startswith("socks5h://") + assert "@1.2.3.4:1080" in url + + +def test_resolve_channel_socks_default_off(temp_db): + cfg = temp_db.get_settings_map() + temp_db.update_settings_map( + { + "tiktok_upload_socks_profiles": [ + { + "id": "p1", + "label": "住宅1", + "type": "socks5", + "server": "10.0.0.1", + "port": 1000, + "username": "a", + "password": "b", + } + ] + } + ) + ch = {"socks_enabled": 0, "socks_profile_id": "p1"} + assert resolve_channel_socks_proxy(ch, temp_db.get_settings_map()) == "" + ch["socks_enabled"] = 1 + url = resolve_channel_socks_proxy(ch, temp_db.get_settings_map()) + assert url.startswith("socks5h://") + assert "10.0.0.1:1000" in url + _ = cfg + + +def test_merge_keeps_masked_password(temp_db): + temp_db.update_settings_map( + { + "tiktok_upload_socks_profiles": [ + { + "id": "p1", + "label": "住宅1", + "type": "socks5", + "server": "10.0.0.1", + "port": 1000, + "username": "a", + "password": "secretpass", + } + ] + } + ) + merged = merge_socks_profiles_patch( + [ + { + "id": "p1", + "label": "住宅1", + "type": "socks5", + "server": "10.0.0.1", + "port": 1000, + "username": "a", + "password": "***pass", + } + ], + temp_db.get_settings_map(), + ) + assert merged[0]["password"] == "secretpass" diff --git a/frontend/src/app/tiktok/page.tsx b/frontend/src/app/tiktok/page.tsx index dd08be2..78087c8 100644 --- a/frontend/src/app/tiktok/page.tsx +++ b/frontend/src/app/tiktok/page.tsx @@ -42,6 +42,20 @@ type Channel = { cookie_ttl_days?: number; cookie_expires_in_days?: number | null; cookie_status?: "ok" | "warn" | "expired" | "missing" | string; + socks_enabled?: boolean; + socks_profile_id?: string; + socks_profile_label?: string; +}; + +type SocksProfile = { + id: string; + label?: string; + type?: string; + server?: string; + port?: number; + username?: string; + password?: string; + has_password?: boolean; }; type BoardChannel = { @@ -98,6 +112,10 @@ export default function TikTokPage() { const [loading, setLoading] = useState(true); const [status, setStatus] = useState(null); const [channels, setChannels] = useState([]); + const [socksProfiles, setSocksProfiles] = useState([]); + const [socksDraft, setSocksDraft] = useState([]); + const [socksSelectedId, setSocksSelectedId] = useState(""); + const [savingSocks, setSavingSocks] = useState(false); const [jobs, setJobs] = useState([]); const [jobTotal, setJobTotal] = useState(0); @@ -106,6 +124,8 @@ export default function TikTokPage() { const [formName, setFormName] = useState("TikTok 账号"); const [formPrivacy, setFormPrivacy] = useState("PUBLIC_TO_EVERYONE"); const [formTitle, setFormTitle] = useState(""); + const [formSocksEnabled, setFormSocksEnabled] = useState(false); + const [formSocksProfileId, setFormSocksProfileId] = useState(""); const [sessionChannelId, setSessionChannelId] = useState(""); const [sessionChannelName, setSessionChannelName] = useState(""); @@ -123,6 +143,13 @@ export default function TikTokPage() { ]); setStatus(st); setChannels(st?.channels || []); + const profiles = Array.isArray(st?.socks_profiles) ? (st.socks_profiles as SocksProfile[]) : []; + setSocksProfiles(profiles); + setSocksDraft(profiles.map((p) => ({ ...p }))); + setSocksSelectedId((prev) => { + if (prev && profiles.some((p) => p.id === prev)) return prev; + return String(profiles[0]?.id || ""); + }); setJobs(j?.jobs || []); setJobTotal(j?.total || 0); setLoading(false); @@ -164,6 +191,8 @@ export default function TikTokPage() { setFormName("TikTok 账号"); setFormPrivacy("PUBLIC_TO_EVERYONE"); setFormTitle(""); + setFormSocksEnabled(false); + setFormSocksProfileId(String(socksProfiles[0]?.id || "")); setShowForm(true); setShowSessionForm(false); }; @@ -252,6 +281,8 @@ export default function TikTokPage() { privacy_level: formPrivacy, title_template: formTitle, description_template: "", + socks_enabled: formSocksEnabled, + socks_profile_id: formSocksEnabled ? formSocksProfileId : "", }), }); toast.push("账号已添加,请粘贴 Cookie", "ok"); @@ -272,6 +303,8 @@ export default function TikTokPage() { privacy_level: formPrivacy, title_template: formTitle, description_template: "", + socks_enabled: formSocksEnabled, + socks_profile_id: formSocksEnabled ? formSocksProfileId : "", }), }); toast.push("已保存", "ok"); @@ -361,9 +394,30 @@ export default function TikTokPage() { setFormName(ch.name || "TikTok 账号"); setFormPrivacy(ch.privacy_level || "PUBLIC_TO_EVERYONE"); setFormTitle(ch.title_template || ""); + setFormSocksEnabled(Boolean(ch.socks_enabled)); + setFormSocksProfileId(String(ch.socks_profile_id || socksProfiles[0]?.id || "")); setShowForm(true); }; + const saveSocksProfiles = async () => { + setSavingSocks(true); + try { + const r = await fetchJson("/api/tiktok/socks-profiles", { + method: "PUT", + body: JSON.stringify({ profiles: socksDraft }), + }); + const next = Array.isArray(r?.socks_profiles) ? (r.socks_profiles as SocksProfile[]) : []; + setSocksProfiles(next); + setSocksDraft(next.map((p) => ({ ...p }))); + toast.push("SOCKS 配置已保存", "ok"); + void load(); + } catch (e: any) { + toast.push(e?.message || "保存 SOCKS 失败", "err"); + } finally { + setSavingSocks(false); + } + }; + const statusLabel = useMemo( () => ({ pending: "待录制", @@ -617,6 +671,37 @@ export default function TikTokPage() {

发到 TikTok 的文案就是这里写的原文,不会自动加直播间名字或链接。

+
+ +

+ 默认不勾选(直连)。勾选后使用下方 SOCKS 配置池中的某一套,按账号独立选择。 +

+ {formSocksEnabled && ( + + )} +
+
+ {(() => { + const selected = + socksDraft.find((p) => String(p.id) === String(socksSelectedId)) || socksDraft[0] || null; + const setList = (next: SocksProfile[]) => { + setSocksDraft(next); + if (!next.some((p) => String(p.id) === String(socksSelectedId))) { + setSocksSelectedId(String(next[0]?.id || "")); + } + }; + const patchSelected = (patch: Partial) => { + if (!selected) return; + setList( + socksDraft.map((p) => (String(p.id) === String(selected.id) ? { ...p, ...patch } : p)), + ); + }; + return ( +
+
+ + + {selected && ( + + )} +
+ {selected ? ( +
+ + + + + + +
+ ) : ( +

暂无 SOCKS 配置,请点「新增配置」。

+ )} +
+ ); + })()} + + {/* Two-column board */} {channels.length > 0 && (
@@ -784,6 +1025,11 @@ export default function TikTokPage() { {full?.authorized && full.cookie_saved_at ? (
保存于 {fmtTs(full.cookie_saved_at)}
) : null} +
+ {full?.socks_enabled + ? `SOCKS · ${full.socks_profile_label || full.socks_profile_id || "已启用"}` + : "SOCKS · 直连"} +