feat: TikTok 上传支持按账号可选 SOCKS 静态住宅 IP
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
e2f03e4082
commit
45c2437a0e
@ -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,
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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):
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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
|
||||
|
||||
132
backend/app/tiktok_socks.py
Normal file
132
backend/app/tiktok_socks.py
Normal file
@ -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)
|
||||
@ -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
|
||||
|
||||
|
||||
79
backend/tests/test_tiktok_socks.py
Normal file
79
backend/tests/test_tiktok_socks.py
Normal file
@ -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"
|
||||
@ -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<any>(null);
|
||||
const [channels, setChannels] = useState<Channel[]>([]);
|
||||
const [socksProfiles, setSocksProfiles] = useState<SocksProfile[]>([]);
|
||||
const [socksDraft, setSocksDraft] = useState<SocksProfile[]>([]);
|
||||
const [socksSelectedId, setSocksSelectedId] = useState("");
|
||||
const [savingSocks, setSavingSocks] = useState(false);
|
||||
const [jobs, setJobs] = useState<Job[]>([]);
|
||||
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() {
|
||||
<p className="text-[11px] text-slate-500 sm:col-span-2">
|
||||
发到 TikTok 的文案就是这里写的原文,不会自动加直播间名字或链接。
|
||||
</p>
|
||||
<div className="sm:col-span-2 rounded-xl border border-white/10 bg-white/[0.03] p-3">
|
||||
<label className="inline-flex items-center gap-2 text-sm text-slate-200">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formSocksEnabled}
|
||||
onChange={(e) => setFormSocksEnabled(e.target.checked)}
|
||||
/>
|
||||
上传走 SOCKS(静态住宅 IP)
|
||||
</label>
|
||||
<p className="mt-1 text-[11px] text-slate-500">
|
||||
默认不勾选(直连)。勾选后使用下方 SOCKS 配置池中的某一套,按账号独立选择。
|
||||
</p>
|
||||
{formSocksEnabled && (
|
||||
<label className="mt-2 block text-xs text-slate-400">
|
||||
SOCKS 配置
|
||||
<select
|
||||
value={formSocksProfileId}
|
||||
onChange={(e) => setFormSocksProfileId(e.target.value)}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
>
|
||||
{socksProfiles.length === 0 && <option value="">请先在下方添加 SOCKS 配置</option>}
|
||||
{socksProfiles.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.label || p.server || p.id}
|
||||
{p.server ? ` · ${p.server}:${p.port || ""}` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<button
|
||||
@ -748,6 +833,162 @@ export default function TikTokPage() {
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* TikTok SOCKS profile pool */}
|
||||
<section className="mb-6 rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4">
|
||||
<div className="mb-3 flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-slate-100">TikTok 上传 SOCKS(静态住宅 IP)</h3>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-slate-500">
|
||||
先在这里维护多套 SOCKS,再在每个账号的「编辑」里勾选并选择要用哪一套。默认不勾选 = 直连上传。
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void saveSocksProfiles()}
|
||||
disabled={savingSocks}
|
||||
className="rounded-lg bg-cyan-500/20 px-3 py-2 text-xs text-cyan-100 hover:bg-cyan-500/30 disabled:opacity-50"
|
||||
>
|
||||
{savingSocks ? "保存中…" : "保存 SOCKS 配置"}
|
||||
</button>
|
||||
</div>
|
||||
{(() => {
|
||||
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<SocksProfile>) => {
|
||||
if (!selected) return;
|
||||
setList(
|
||||
socksDraft.map((p) => (String(p.id) === String(selected.id) ? { ...p, ...patch } : p)),
|
||||
);
|
||||
};
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
<label className="block min-w-[12rem] flex-1 text-xs text-slate-400">
|
||||
当前配置
|
||||
<select
|
||||
value={String(selected?.id || "")}
|
||||
onChange={(e) => setSocksSelectedId(e.target.value)}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
>
|
||||
{socksDraft.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.label || p.server || p.id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const id =
|
||||
typeof crypto !== "undefined" && crypto.randomUUID
|
||||
? crypto.randomUUID()
|
||||
: `socks-${Date.now()}`;
|
||||
const next = [
|
||||
...socksDraft,
|
||||
{
|
||||
id,
|
||||
label: `住宅 ${socksDraft.length + 1}`,
|
||||
type: "socks5",
|
||||
server: "",
|
||||
port: 1080,
|
||||
username: "",
|
||||
password: "",
|
||||
},
|
||||
];
|
||||
setList(next);
|
||||
setSocksSelectedId(id);
|
||||
}}
|
||||
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-200 hover:bg-white/10"
|
||||
>
|
||||
新增配置
|
||||
</button>
|
||||
{selected && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (socksDraft.length <= 0) return;
|
||||
const next = socksDraft.filter((p) => String(p.id) !== String(selected.id));
|
||||
setList(next);
|
||||
}}
|
||||
className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-xs text-rose-200"
|
||||
>
|
||||
删除当前
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{selected ? (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="text-xs text-slate-400">
|
||||
名称
|
||||
<input
|
||||
value={selected.label || ""}
|
||||
onChange={(e) => patchSelected({ label: e.target.value })}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
类型
|
||||
<select
|
||||
value={selected.type || "socks5"}
|
||||
onChange={(e) => patchSelected({ type: e.target.value })}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="socks5">socks5</option>
|
||||
<option value="socks5h">socks5h</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
主机
|
||||
<input
|
||||
value={selected.server || ""}
|
||||
onChange={(e) => patchSelected({ server: e.target.value })}
|
||||
placeholder="x.x.x.x"
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
端口
|
||||
<input
|
||||
type="number"
|
||||
value={Number(selected.port || 0) || ""}
|
||||
onChange={(e) => patchSelected({ port: Number(e.target.value) || 0 })}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
用户名
|
||||
<input
|
||||
value={selected.username || ""}
|
||||
onChange={(e) => patchSelected({ username: e.target.value })}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-400">
|
||||
密码
|
||||
<input
|
||||
type="password"
|
||||
value={selected.password || ""}
|
||||
onChange={(e) => patchSelected({ password: e.target.value })}
|
||||
placeholder={selected.has_password ? "已保存(留空或 *** 表示不改)" : ""}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-amber-200">暂无 SOCKS 配置,请点「新增配置」。</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</section>
|
||||
|
||||
{/* Two-column board */}
|
||||
{channels.length > 0 && (
|
||||
<div className="mb-6 grid gap-4 xl:grid-cols-[1.4fr_1fr] xl:items-start">
|
||||
@ -784,6 +1025,11 @@ export default function TikTokPage() {
|
||||
{full?.authorized && full.cookie_saved_at ? (
|
||||
<div className="text-[10px] text-slate-500">保存于 {fmtTs(full.cookie_saved_at)}</div>
|
||||
) : null}
|
||||
<div className="mt-1 text-[10px] text-slate-500">
|
||||
{full?.socks_enabled
|
||||
? `SOCKS · ${full.socks_profile_label || full.socks_profile_id || "已启用"}`
|
||||
: "SOCKS · 直连"}
|
||||
</div>
|
||||
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-white/10">
|
||||
<div className="h-full rounded-full bg-pink-500/70" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user