feat: per-channel/account enable switches with job purge on disable
Shorts/yt-long use per-channel toggles; TikTok/X use account toggles. Turning off clears queued jobs and blocks sampling, recording, and uploads for that target. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
86e330d004
commit
f2b3242e7d
@ -3848,6 +3848,7 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict
|
|||||||
FROM shorts_jobs j
|
FROM shorts_jobs j
|
||||||
INNER JOIN shorts_channels c ON c.id = j.channel_pk
|
INNER JOIN shorts_channels c ON c.id = j.channel_pk
|
||||||
WHERE j.status = 'scheduled'
|
WHERE j.status = 'scheduled'
|
||||||
|
AND c.enabled = 1
|
||||||
AND j.clip_path != ''
|
AND j.clip_path != ''
|
||||||
AND j.youtube_video_id = ''
|
AND j.youtube_video_id = ''
|
||||||
AND j.upload_at > 0
|
AND j.upload_at > 0
|
||||||
@ -3864,6 +3865,7 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict
|
|||||||
FROM shorts_jobs j
|
FROM shorts_jobs j
|
||||||
INNER JOIN shorts_channels c ON c.id = j.channel_pk
|
INNER JOIN shorts_channels c ON c.id = j.channel_pk
|
||||||
WHERE j.status = 'recorded'
|
WHERE j.status = 'recorded'
|
||||||
|
AND c.enabled = 1
|
||||||
AND j.clip_path != ''
|
AND j.clip_path != ''
|
||||||
AND j.youtube_video_id = ''
|
AND j.youtube_video_id = ''
|
||||||
AND j.upload_at > 0
|
AND j.upload_at > 0
|
||||||
@ -3911,9 +3913,11 @@ def claim_pending_shorts_record() -> dict[str, Any] | None:
|
|||||||
try:
|
try:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM shorts_jobs
|
SELECT j.* FROM shorts_jobs j
|
||||||
WHERE status = 'pending'
|
INNER JOIN shorts_channels c ON c.id = j.channel_pk
|
||||||
ORDER BY created_at ASC
|
WHERE j.status = 'pending'
|
||||||
|
AND c.enabled = 1
|
||||||
|
ORDER BY j.created_at ASC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
"""
|
"""
|
||||||
).fetchone()
|
).fetchone()
|
||||||
|
|||||||
@ -767,11 +767,19 @@ async def shorts_channels_update(channel_pk: str, body: ShortsChannelUpdate) ->
|
|||||||
patch.pop(secret_key, None)
|
patch.pop(secret_key, None)
|
||||||
if secret_key in patch and str(patch[secret_key]).startswith("***"):
|
if secret_key in patch and str(patch[secret_key]).startswith("***"):
|
||||||
patch.pop(secret_key, None)
|
patch.pop(secret_key, None)
|
||||||
|
prev = db.get_shorts_channel(channel_pk)
|
||||||
|
was_enabled = bool(prev.get("enabled")) if prev else True
|
||||||
try:
|
try:
|
||||||
ch = db.update_shorts_channel(channel_pk, **patch)
|
ch = db.update_shorts_channel(channel_pk, **patch)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(404, str(exc)) from exc
|
raise HTTPException(404, str(exc)) from exc
|
||||||
return {"channel": _public_shorts_channel(ch)}
|
cleared: dict[str, int] = {}
|
||||||
|
if was_enabled and ch and not ch.get("enabled"):
|
||||||
|
cleared = db.delete_shorts_jobs_for_channel(channel_pk)
|
||||||
|
out: dict[str, Any] = {"channel": _public_shorts_channel(ch)}
|
||||||
|
if cleared:
|
||||||
|
out["cleared"] = cleared
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
@app.delete("/api/shorts/channels/{channel_pk}")
|
@app.delete("/api/shorts/channels/{channel_pk}")
|
||||||
@ -1031,6 +1039,42 @@ async def x2_accounts_list(limit: int = Query(50, ge=1, le=200)) -> dict[str, An
|
|||||||
return {"accounts": rows}
|
return {"accounts": rows}
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/x2/accounts/{account_id}")
|
||||||
|
async def x2_accounts_update(account_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""Toggle X account enabled. When disabled, clear clip jobs + cancel queued ops for that account."""
|
||||||
|
from . import x2_db
|
||||||
|
from . import x_clips_db
|
||||||
|
from .x2_ws import hub
|
||||||
|
|
||||||
|
patch = dict(body or {})
|
||||||
|
if "enabled" not in patch:
|
||||||
|
raise HTTPException(400, "缺少 enabled")
|
||||||
|
enabled = bool(patch.get("enabled"))
|
||||||
|
prev = await _db(x2_db.get_account, account_id)
|
||||||
|
if not prev:
|
||||||
|
raise HTTPException(404, "账号不存在")
|
||||||
|
was_enabled = bool(int(prev.get("enabled") if prev.get("enabled") is not None else 1))
|
||||||
|
acc = await _db(x2_db.set_account_enabled, account_id, enabled)
|
||||||
|
if not acc:
|
||||||
|
raise HTTPException(404, "账号不存在")
|
||||||
|
cleared: dict[str, Any] = {}
|
||||||
|
if was_enabled and not enabled:
|
||||||
|
username = str(acc.get("username") or "").strip().lstrip("@")
|
||||||
|
if username:
|
||||||
|
cleared = await _db(x_clips_db.delete_x_clip_jobs_for_account, username)
|
||||||
|
cancelled = await _db(x2_db.cancel_jobs_for_account, username)
|
||||||
|
cleared["x2_cancelled"] = cancelled
|
||||||
|
for jid in cancelled.get("ids") or []:
|
||||||
|
try:
|
||||||
|
await hub.notify_cancel(str(jid), agent_id=str(acc.get("agent_id") or ""))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
out: dict[str, Any] = {"ok": True, "account": acc}
|
||||||
|
if cleared:
|
||||||
|
out["cleared"] = cleared
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/x2/jobs")
|
@app.post("/api/x2/jobs")
|
||||||
async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]:
|
async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""Web console creates a job; Chrome extension claims & executes it."""
|
"""Web console creates a job; Chrome extension claims & executes it."""
|
||||||
@ -1039,6 +1083,9 @@ async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]:
|
|||||||
|
|
||||||
kind = str(body.get("kind") or "").strip()
|
kind = str(body.get("kind") or "").strip()
|
||||||
params = body.get("params") if isinstance(body.get("params"), dict) else {}
|
params = body.get("params") if isinstance(body.get("params"), dict) else {}
|
||||||
|
username = str((params or {}).get("username") or body.get("username") or "").strip().lstrip("@")
|
||||||
|
if username and not await _db(x2_db.is_account_enabled, username):
|
||||||
|
raise HTTPException(400, f"账号 @{username} 已停用,禁止下发任务")
|
||||||
try:
|
try:
|
||||||
job = await _db(x2_db.create_web_job, kind, params)
|
job = await _db(x2_db.create_web_job, kind, params)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
@ -1498,11 +1545,19 @@ async def yt_long_channels_update(channel_pk: str, body: dict[str, Any] | None =
|
|||||||
not str(patch.get(secret_key) or "").strip() or str(patch[secret_key]).startswith("***")
|
not str(patch.get(secret_key) or "").strip() or str(patch[secret_key]).startswith("***")
|
||||||
):
|
):
|
||||||
patch.pop(secret_key, None)
|
patch.pop(secret_key, None)
|
||||||
|
prev = await _db(yt_long_db.get_yt_long_channel, channel_pk)
|
||||||
|
was_enabled = bool(prev.get("enabled")) if prev else True
|
||||||
try:
|
try:
|
||||||
ch = await _db(yt_long_db.update_yt_long_channel, channel_pk, **patch)
|
ch = await _db(yt_long_db.update_yt_long_channel, channel_pk, **patch)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(404, str(exc)) from exc
|
raise HTTPException(404, str(exc)) from exc
|
||||||
return {"channel": yt_long_db.public_yt_long_channel(ch)}
|
cleared: dict[str, int] = {}
|
||||||
|
if was_enabled and ch and not ch.get("enabled"):
|
||||||
|
cleared = await _db(yt_long_db.delete_yt_long_jobs_for_channel, channel_pk)
|
||||||
|
out: dict[str, Any] = {"channel": yt_long_db.public_yt_long_channel(ch)}
|
||||||
|
if cleared:
|
||||||
|
out["cleared"] = cleared
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
@app.delete("/api/yt-long/channels/{channel_pk}")
|
@app.delete("/api/yt-long/channels/{channel_pk}")
|
||||||
@ -1957,10 +2012,18 @@ async def tiktok_channels_update(channel_pk: str, body: TikTokChannelUpdate) ->
|
|||||||
patch = body.model_dump(exclude_none=True)
|
patch = body.model_dump(exclude_none=True)
|
||||||
if not patch:
|
if not patch:
|
||||||
raise HTTPException(400, "无更新字段")
|
raise HTTPException(400, "无更新字段")
|
||||||
|
prev = await _db(tiktok_db.get_tiktok_channel, channel_pk)
|
||||||
|
was_enabled = bool(prev.get("enabled")) if prev else True
|
||||||
ch = await _db(tiktok_db.update_tiktok_channel, channel_pk, **patch)
|
ch = await _db(tiktok_db.update_tiktok_channel, channel_pk, **patch)
|
||||||
if not ch:
|
if not ch:
|
||||||
raise HTTPException(404, "账号不存在")
|
raise HTTPException(404, "账号不存在")
|
||||||
return {"ok": True, "channel": _public_tiktok_channel(ch)}
|
cleared: dict[str, int] = {}
|
||||||
|
if was_enabled and not ch.get("enabled"):
|
||||||
|
cleared = await _db(tiktok_db.delete_tiktok_jobs_for_channel, channel_pk)
|
||||||
|
out: dict[str, Any] = {"ok": True, "channel": _public_tiktok_channel(ch)}
|
||||||
|
if cleared:
|
||||||
|
out["cleared"] = cleared
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
@app.put("/api/tiktok/socks-profiles")
|
@app.put("/api/tiktok/socks-profiles")
|
||||||
|
|||||||
@ -433,9 +433,11 @@ def claim_pending_tiktok_record() -> dict[str, Any] | None:
|
|||||||
try:
|
try:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM tiktok_jobs
|
SELECT j.* FROM tiktok_jobs j
|
||||||
WHERE status = 'pending'
|
INNER JOIN tiktok_channels c ON c.id = j.channel_pk
|
||||||
ORDER BY created_at ASC
|
WHERE j.status = 'pending'
|
||||||
|
AND c.enabled = 1
|
||||||
|
ORDER BY j.created_at ASC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
"""
|
"""
|
||||||
).fetchone()
|
).fetchone()
|
||||||
@ -617,17 +619,51 @@ def reschedule_soft_quota_held_jobs(*, limit: int = 50) -> int:
|
|||||||
return n
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def delete_tiktok_jobs_for_channel(channel_pk: str) -> dict[str, int]:
|
||||||
|
"""Delete all TikTok jobs for an account (keep account row)."""
|
||||||
|
pk = str(channel_pk or "").strip()
|
||||||
|
if not pk:
|
||||||
|
return {"jobs": 0, "clips": 0}
|
||||||
|
clip_paths: list[str] = []
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT clip_path FROM tiktok_jobs WHERE channel_pk = ?",
|
||||||
|
(pk,),
|
||||||
|
).fetchall()
|
||||||
|
clip_paths = [str(r["clip_path"] or "") for r in rows if r["clip_path"]]
|
||||||
|
cur = conn.execute("DELETE FROM tiktok_jobs WHERE channel_pk = ?", (pk,))
|
||||||
|
jobs = int(cur.rowcount or 0)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
clips = 0
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
for raw in clip_paths:
|
||||||
|
try:
|
||||||
|
p = Path(str(raw).strip())
|
||||||
|
if p.is_file():
|
||||||
|
p.unlink()
|
||||||
|
clips += 1
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return {"jobs": jobs, "clips": clips}
|
||||||
|
|
||||||
|
|
||||||
def claim_due_tiktok_upload() -> dict[str, Any] | None:
|
def claim_due_tiktok_upload() -> dict[str, Any] | None:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
with _lock:
|
with _lock:
|
||||||
conn = _connect()
|
conn = _connect()
|
||||||
try:
|
try:
|
||||||
# Skip accounts currently under TikTok platform rate-limit (hourly probe handles those)
|
# Skip disabled accounts and accounts under TikTok platform rate-limit
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT j.* FROM tiktok_jobs j
|
SELECT j.* FROM tiktok_jobs j
|
||||||
LEFT JOIN tiktok_channels c ON c.id = j.channel_pk
|
INNER JOIN tiktok_channels c ON c.id = j.channel_pk
|
||||||
WHERE j.status = 'scheduled'
|
WHERE j.status = 'scheduled'
|
||||||
|
AND c.enabled = 1
|
||||||
AND j.clip_path != ''
|
AND j.clip_path != ''
|
||||||
AND IFNULL(j.tiktok_video_id,'') = ''
|
AND IFNULL(j.tiktok_video_id,'') = ''
|
||||||
AND IFNULL(j.tiktok_publish_id,'') = ''
|
AND IFNULL(j.tiktok_publish_id,'') = ''
|
||||||
|
|||||||
@ -32,6 +32,7 @@ def ensure_x2_tables(conn) -> None:
|
|||||||
bound_at TEXT NOT NULL DEFAULT '',
|
bound_at TEXT NOT NULL DEFAULT '',
|
||||||
last_seen_at TEXT NOT NULL DEFAULT '',
|
last_seen_at TEXT NOT NULL DEFAULT '',
|
||||||
raw_json TEXT NOT NULL DEFAULT '{}',
|
raw_json TEXT NOT NULL DEFAULT '{}',
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
updated_at REAL NOT NULL
|
updated_at REAL NOT NULL
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS idx_x2_accounts_agent ON x2_accounts(agent_id, username);
|
CREATE INDEX IF NOT EXISTS idx_x2_accounts_agent ON x2_accounts(agent_id, username);
|
||||||
@ -65,6 +66,9 @@ def ensure_x2_tables(conn) -> None:
|
|||||||
CREATE INDEX IF NOT EXISTS idx_x2_events_created ON x2_events(created_at DESC);
|
CREATE INDEX IF NOT EXISTS idx_x2_events_created ON x2_events(created_at DESC);
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
cols = {str(r[1]) for r in conn.execute("PRAGMA table_info(x2_accounts)").fetchall()}
|
||||||
|
if "enabled" not in cols:
|
||||||
|
conn.execute("ALTER TABLE x2_accounts ADD COLUMN enabled INTEGER NOT NULL DEFAULT 1")
|
||||||
|
|
||||||
|
|
||||||
def ensure_ingest_token() -> str:
|
def ensure_ingest_token() -> str:
|
||||||
@ -423,7 +427,118 @@ def list_accounts(*, limit: int = 50) -> list[dict[str, Any]]:
|
|||||||
"SELECT * FROM x2_accounts ORDER BY updated_at DESC LIMIT ?",
|
"SELECT * FROM x2_accounts ORDER BY updated_at DESC LIMIT ?",
|
||||||
(max(1, min(int(limit), 200)),),
|
(max(1, min(int(limit), 200)),),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [_row_to_dict(r) for r in rows] # type: ignore
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
d = _row_to_dict(r) or {}
|
||||||
|
d["enabled"] = bool(int(d.get("enabled") if d.get("enabled") is not None else 1))
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_account(account_id: str) -> dict[str, Any] | None:
|
||||||
|
pk = str(account_id or "").strip()
|
||||||
|
if not pk:
|
||||||
|
return None
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_x2_tables(conn)
|
||||||
|
row = conn.execute("SELECT * FROM x2_accounts WHERE id = ?", (pk,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = _row_to_dict(row) or {}
|
||||||
|
d["enabled"] = bool(int(d.get("enabled") if d.get("enabled") is not None else 1))
|
||||||
|
return d
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_account_by_username(username: str) -> dict[str, Any] | None:
|
||||||
|
uname = str(username or "").strip().lstrip("@")
|
||||||
|
if not uname:
|
||||||
|
return None
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_x2_tables(conn)
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM x2_accounts WHERE LOWER(username) = LOWER(?) ORDER BY updated_at DESC LIMIT 1",
|
||||||
|
(uname,),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = _row_to_dict(row) or {}
|
||||||
|
d["enabled"] = bool(int(d.get("enabled") if d.get("enabled") is not None else 1))
|
||||||
|
return d
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def is_account_enabled(username: str) -> bool:
|
||||||
|
acc = get_account_by_username(username)
|
||||||
|
if not acc:
|
||||||
|
return True
|
||||||
|
return bool(acc.get("enabled"))
|
||||||
|
|
||||||
|
|
||||||
|
def set_account_enabled(account_id: str, enabled: bool) -> dict[str, Any] | None:
|
||||||
|
pk = str(account_id or "").strip()
|
||||||
|
if not pk:
|
||||||
|
return None
|
||||||
|
now = time.time()
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_x2_tables(conn)
|
||||||
|
cur = conn.execute(
|
||||||
|
"UPDATE x2_accounts SET enabled = ?, updated_at = ? WHERE id = ?",
|
||||||
|
(1 if enabled else 0, now, pk),
|
||||||
|
)
|
||||||
|
if cur.rowcount == 0:
|
||||||
|
return None
|
||||||
|
conn.commit()
|
||||||
|
row = conn.execute("SELECT * FROM x2_accounts WHERE id = ?", (pk,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = _row_to_dict(row) or {}
|
||||||
|
d["enabled"] = bool(int(d.get("enabled") if d.get("enabled") is not None else 1))
|
||||||
|
return d
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_jobs_for_account(username: str) -> dict[str, Any]:
|
||||||
|
"""Cancel queued/running x2 jobs for an account."""
|
||||||
|
uname = str(username or "").strip().lstrip("@")
|
||||||
|
if not uname:
|
||||||
|
return {"count": 0, "ids": []}
|
||||||
|
now = time.time()
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_x2_tables(conn)
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id FROM x2_jobs
|
||||||
|
WHERE LOWER(account_username) = LOWER(?)
|
||||||
|
AND status IN ('queued', 'running', 'pending')
|
||||||
|
""",
|
||||||
|
(uname,),
|
||||||
|
).fetchall()
|
||||||
|
ids = [str(r["id"]) for r in rows]
|
||||||
|
if ids:
|
||||||
|
conn.executemany(
|
||||||
|
"""
|
||||||
|
UPDATE x2_jobs
|
||||||
|
SET status = 'cancelled', error = 'account_disabled', updated_at = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
[(now, jid) for jid in ids],
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return {"count": len(ids), "ids": ids}
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|||||||
@ -9,6 +9,7 @@ from typing import Any, Optional
|
|||||||
|
|
||||||
from .db import _connect, _lock, _row_to_dict
|
from .db import _connect, _lock, _row_to_dict
|
||||||
from .timeutil import push_date_from_ts
|
from .timeutil import push_date_from_ts
|
||||||
|
from .x2_db import ensure_x2_tables
|
||||||
|
|
||||||
# Quota-consuming statuses (posting pipeline has claimed a daily slot)
|
# Quota-consuming statuses (posting pipeline has claimed a daily slot)
|
||||||
_QUOTA_STATUSES = ("pending", "recording", "scheduled", "posting", "posted")
|
_QUOTA_STATUSES = ("pending", "recording", "scheduled", "posting", "posted")
|
||||||
@ -284,11 +285,18 @@ def list_pending_x_clip_jobs(*, limit: int = 10) -> list[dict[str, Any]]:
|
|||||||
conn = _connect()
|
conn = _connect()
|
||||||
try:
|
try:
|
||||||
ensure_x_clips_tables(conn)
|
ensure_x_clips_tables(conn)
|
||||||
|
ensure_x2_tables(conn)
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM x_clip_jobs
|
SELECT j.* FROM x_clip_jobs j
|
||||||
WHERE status = 'pending'
|
LEFT JOIN x2_accounts a ON LOWER(TRIM(a.username)) = LOWER(TRIM(j.account_username))
|
||||||
ORDER BY created_at ASC
|
WHERE j.status = 'pending'
|
||||||
|
AND (
|
||||||
|
TRIM(j.account_username) = ''
|
||||||
|
OR a.id IS NULL
|
||||||
|
OR a.enabled = 1
|
||||||
|
)
|
||||||
|
ORDER BY j.created_at ASC
|
||||||
LIMIT ?
|
LIMIT ?
|
||||||
""",
|
""",
|
||||||
(max(1, min(int(limit), 50)),),
|
(max(1, min(int(limit), 50)),),
|
||||||
@ -326,15 +334,22 @@ def claim_due_x_clip_post() -> dict[str, Any] | None:
|
|||||||
conn = _connect()
|
conn = _connect()
|
||||||
try:
|
try:
|
||||||
ensure_x_clips_tables(conn)
|
ensure_x_clips_tables(conn)
|
||||||
|
ensure_x2_tables(conn)
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM x_clip_jobs
|
SELECT j.* FROM x_clip_jobs j
|
||||||
WHERE status = 'scheduled'
|
LEFT JOIN x2_accounts a ON LOWER(TRIM(a.username)) = LOWER(TRIM(j.account_username))
|
||||||
AND clip_path != ''
|
WHERE j.status = 'scheduled'
|
||||||
AND IFNULL(x2_job_id, '') = ''
|
AND j.clip_path != ''
|
||||||
AND upload_at > 0
|
AND IFNULL(j.x2_job_id, '') = ''
|
||||||
AND upload_at <= ?
|
AND j.upload_at > 0
|
||||||
ORDER BY upload_at ASC, created_at ASC
|
AND j.upload_at <= ?
|
||||||
|
AND (
|
||||||
|
TRIM(j.account_username) = ''
|
||||||
|
OR a.id IS NULL
|
||||||
|
OR a.enabled = 1
|
||||||
|
)
|
||||||
|
ORDER BY j.upload_at ASC, j.created_at ASC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""",
|
""",
|
||||||
(now,),
|
(now,),
|
||||||
@ -536,3 +551,61 @@ def skip_remaining_scheduled_for_day(
|
|||||||
return int(cur.rowcount or 0)
|
return int(cur.rowcount or 0)
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_x_clip_jobs_for_account(account_username: str) -> dict[str, int]:
|
||||||
|
"""Delete all X clip jobs for an account (keep account row)."""
|
||||||
|
uname = str(account_username or "").strip().lstrip("@")
|
||||||
|
if not uname:
|
||||||
|
return {"jobs": 0, "clips": 0}
|
||||||
|
clip_paths: list[str] = []
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_x_clips_tables(conn)
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, clip_path FROM x_clip_jobs
|
||||||
|
WHERE LOWER(account_username) = LOWER(?)
|
||||||
|
""",
|
||||||
|
(uname,),
|
||||||
|
).fetchall()
|
||||||
|
for row in rows:
|
||||||
|
clip = str(row["clip_path"] or "").strip()
|
||||||
|
if clip:
|
||||||
|
clip_paths.append(clip)
|
||||||
|
cur = conn.execute(
|
||||||
|
"DELETE FROM x_clip_jobs WHERE LOWER(account_username) = LOWER(?)",
|
||||||
|
(uname,),
|
||||||
|
)
|
||||||
|
jobs = int(cur.rowcount or 0)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
clips = 0
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
for raw in clip_paths:
|
||||||
|
try:
|
||||||
|
p = Path(str(raw).strip())
|
||||||
|
if p.is_file():
|
||||||
|
p.unlink()
|
||||||
|
clips += 1
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return {"jobs": jobs, "clips": clips}
|
||||||
|
|
||||||
|
|
||||||
|
def list_enabled_x_account_usernames() -> list[str]:
|
||||||
|
"""Usernames of X accounts that are enabled (default enabled if not in x2_accounts)."""
|
||||||
|
from . import x2_db
|
||||||
|
|
||||||
|
try:
|
||||||
|
accounts = x2_db.list_accounts(limit=200)
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
str(a.get("username") or "").strip().lstrip("@")
|
||||||
|
for a in accounts
|
||||||
|
if a.get("enabled") is not False and str(a.get("username") or "").strip()
|
||||||
|
]
|
||||||
|
|||||||
@ -111,6 +111,11 @@ def _enqueue_job(
|
|||||||
return None
|
return None
|
||||||
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
|
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
|
||||||
acct = str(settings.get("x_clips_account_username") or "").strip().lstrip("@")
|
acct = str(settings.get("x_clips_account_username") or "").strip().lstrip("@")
|
||||||
|
if acct:
|
||||||
|
from . import x2_db
|
||||||
|
|
||||||
|
if not x2_db.is_account_enabled(acct):
|
||||||
|
return None
|
||||||
job = x_clips_db.create_x_clip_job(
|
job = x_clips_db.create_x_clip_job(
|
||||||
session_id=sid,
|
session_id=sid,
|
||||||
room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""),
|
room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""),
|
||||||
@ -551,6 +556,8 @@ class XClipsPipeline:
|
|||||||
str(job.get("account_username") or "").strip().lstrip("@")
|
str(job.get("account_username") or "").strip().lstrip("@")
|
||||||
or str(cfg.get("x_clips_account_username") or "").strip().lstrip("@")
|
or str(cfg.get("x_clips_account_username") or "").strip().lstrip("@")
|
||||||
)
|
)
|
||||||
|
if acct and not x2_db.is_account_enabled(acct):
|
||||||
|
raise ValueError(f"账号 @{acct} 已停用")
|
||||||
if acct and str(job.get("account_username") or "").strip().lstrip("@") != acct:
|
if acct and str(job.get("account_username") or "").strip().lstrip("@") != acct:
|
||||||
x_clips_db.update_x_clip_job(jid, account_username=acct)
|
x_clips_db.update_x_clip_job(jid, account_username=acct)
|
||||||
media_url = str(job.get("media_url") or "").strip()
|
media_url = str(job.get("media_url") or "").strip()
|
||||||
|
|||||||
@ -665,9 +665,11 @@ def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]:
|
|||||||
ensure_yt_long_tables(conn)
|
ensure_yt_long_tables(conn)
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM yt_long_jobs
|
SELECT j.* FROM yt_long_jobs j
|
||||||
WHERE status = 'pending'
|
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
||||||
ORDER BY created_at ASC
|
WHERE j.status = 'pending'
|
||||||
|
AND c.enabled = 1
|
||||||
|
ORDER BY j.created_at ASC
|
||||||
LIMIT ?
|
LIMIT ?
|
||||||
""",
|
""",
|
||||||
(max(1, min(int(limit), 20)),),
|
(max(1, min(int(limit), 20)),),
|
||||||
@ -702,6 +704,22 @@ def claim_yt_long_job_record(job_id: str) -> dict[str, Any] | None:
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_yt_long_jobs_for_channel(channel_pk: str) -> dict[str, int]:
|
||||||
|
"""Delete all yt-long jobs for a channel (keep channel row)."""
|
||||||
|
pk = str(channel_pk or "").strip()
|
||||||
|
if not pk:
|
||||||
|
return {"jobs": 0}
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_long_tables(conn)
|
||||||
|
cur = conn.execute("DELETE FROM yt_long_jobs WHERE channel_pk = ?", (pk,))
|
||||||
|
conn.commit()
|
||||||
|
return {"jobs": int(cur.rowcount or 0)}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
with _lock:
|
with _lock:
|
||||||
@ -710,12 +728,14 @@ def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
|||||||
ensure_yt_long_tables(conn)
|
ensure_yt_long_tables(conn)
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM yt_long_jobs
|
SELECT j.* FROM yt_long_jobs j
|
||||||
WHERE status = 'scheduled'
|
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
||||||
AND clip_path != ''
|
WHERE j.status = 'scheduled'
|
||||||
AND upload_at > 0
|
AND c.enabled = 1
|
||||||
AND upload_at <= ?
|
AND j.clip_path != ''
|
||||||
ORDER BY upload_at ASC, created_at ASC
|
AND j.upload_at > 0
|
||||||
|
AND j.upload_at <= ?
|
||||||
|
ORDER BY j.upload_at ASC, j.created_at ASC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""",
|
""",
|
||||||
(now,),
|
(now,),
|
||||||
|
|||||||
@ -547,6 +547,28 @@ export default function ShortsPage() {
|
|||||||
await load();
|
await load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function toggleChannelEnabled(ch: Channel) {
|
||||||
|
const turningOn = ch.enabled === false;
|
||||||
|
try {
|
||||||
|
const r = await fetchJson(`/api/shorts/channels/${ch.id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({ enabled: turningOn }),
|
||||||
|
});
|
||||||
|
const cleared = r.cleared as { jobs?: number; clips?: number } | undefined;
|
||||||
|
if (!turningOn && cleared) {
|
||||||
|
toast.push(
|
||||||
|
`已停用「${ch.name}」· 清除任务 ${cleared.jobs ?? 0} · 成片 ${cleared.clips ?? 0}`,
|
||||||
|
"ok",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok");
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function retryJob(id: string) {
|
async function retryJob(id: string) {
|
||||||
await fetchJson(`/api/shorts/jobs/${id}/retry`, { method: "POST" });
|
await fetchJson(`/api/shorts/jobs/${id}/retry`, { method: "POST" });
|
||||||
toast.push("已重新入队", "ok");
|
toast.push("已重新入队", "ok");
|
||||||
@ -1195,6 +1217,20 @@ export default function ShortsPage() {
|
|||||||
meta={channelMeta(ch)}
|
meta={channelMeta(ch)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
{full ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={full.enabled === false ? "启用此频道" : "停用并清除任务"}
|
||||||
|
onClick={() => void toggleChannelEnabled(full)}
|
||||||
|
className={`shrink-0 rounded-lg px-2 py-1 text-[10px] ${
|
||||||
|
full.enabled === false
|
||||||
|
? "bg-white/5 text-slate-400"
|
||||||
|
: "bg-teal-500/15 text-teal-200"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{full.enabled === false ? "已停" : "启用中"}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="relative mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
|
<div className="relative mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
|
||||||
<div
|
<div
|
||||||
|
|||||||
@ -420,12 +420,25 @@ export default function TikTokPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const toggleChannelEnabled = async (ch: Channel) => {
|
const toggleChannelEnabled = async (ch: Channel) => {
|
||||||
await fetchJson(`/api/tiktok/channels/${ch.id}`, {
|
const turningOn = ch.enabled === false;
|
||||||
|
try {
|
||||||
|
const r = await fetchJson(`/api/tiktok/channels/${ch.id}`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
body: JSON.stringify({ enabled: !ch.enabled }),
|
body: JSON.stringify({ enabled: turningOn }),
|
||||||
});
|
});
|
||||||
toast.push(ch.enabled ? "已停用此账号" : "已启用此账号", "ok");
|
const cleared = r.cleared as { jobs?: number; clips?: number } | undefined;
|
||||||
|
if (!turningOn && cleared) {
|
||||||
|
toast.push(
|
||||||
|
`已停用「${ch.name}」· 清除任务 ${cleared.jobs ?? 0} · 成片 ${cleared.clips ?? 0}`,
|
||||||
|
"ok",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok");
|
||||||
|
}
|
||||||
void load();
|
void load();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast.push(e?.message || "切换失败", "err");
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const sampleNow = async () => {
|
const sampleNow = async () => {
|
||||||
|
|||||||
@ -47,6 +47,7 @@ type X2Account = {
|
|||||||
display_name?: string;
|
display_name?: string;
|
||||||
avatar_url?: string;
|
avatar_url?: string;
|
||||||
last_seen_at?: string;
|
last_seen_at?: string;
|
||||||
|
enabled?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const NAV: { id: TabId; emoji: string; label: string }[] = [
|
const NAV: { id: TabId; emoji: string; label: string }[] = [
|
||||||
@ -129,6 +130,32 @@ export default function XPage() {
|
|||||||
}
|
}
|
||||||
}, [toast]);
|
}, [toast]);
|
||||||
|
|
||||||
|
const toggleAccountEnabled = useCallback(
|
||||||
|
async (acc: X2Account) => {
|
||||||
|
const turningOn = acc.enabled === false;
|
||||||
|
try {
|
||||||
|
const r = await fetchJson(`/api/x2/accounts/${encodeURIComponent(acc.id)}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({ enabled: turningOn }),
|
||||||
|
});
|
||||||
|
const cleared = r.cleared as { jobs?: number; clips?: number; x2_cancelled?: { count?: number } } | undefined;
|
||||||
|
if (!turningOn && cleared) {
|
||||||
|
const x2n = cleared.x2_cancelled?.count ?? 0;
|
||||||
|
toast.push(
|
||||||
|
`已停用 @${acc.username || "—"} · 切片 ${cleared.jobs ?? 0} · 插件任务 ${x2n}`,
|
||||||
|
"ok",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast.push(turningOn ? `已启用 @${acc.username || "—"}` : `已停用 @${acc.username || "—"}`, "ok");
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
} catch (e: unknown) {
|
||||||
|
toast.push((e as Error)?.message || "切换失败", "err");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[load, toast],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load();
|
void load();
|
||||||
const t = setInterval(() => void load(), 3500);
|
const t = setInterval(() => void load(), 3500);
|
||||||
@ -392,6 +419,41 @@ export default function XPage() {
|
|||||||
<h3 className="font-display text-xl text-white">{crumb?.emoji} {crumb?.label}</h3>
|
<h3 className="font-display text-xl text-white">{crumb?.emoji} {crumb?.label}</h3>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{accounts.length > 0 ? (
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="mb-2 text-[11px] uppercase tracking-[0.14em] text-slate-500">账号开关</div>
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
|
||||||
|
{accounts.map((a) => (
|
||||||
|
<div
|
||||||
|
key={a.id}
|
||||||
|
className={`flex items-center justify-between gap-2 rounded-xl border px-3 py-2.5 ${
|
||||||
|
a.enabled === false ? "border-white/10 bg-white/[0.02]" : "border-orange-400/25 bg-orange-500/5"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="truncate text-sm font-medium text-slate-100">@{a.username || "—"}</div>
|
||||||
|
{a.display_name ? (
|
||||||
|
<div className="truncate text-[11px] text-slate-500">{a.display_name}</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={a.enabled === false ? "启用此账号" : "停用并清除切片任务"}
|
||||||
|
onClick={() => void toggleAccountEnabled(a)}
|
||||||
|
className={`shrink-0 rounded-lg px-2.5 py-1 text-[11px] ${
|
||||||
|
a.enabled === false
|
||||||
|
? "bg-white/5 text-slate-400"
|
||||||
|
: "bg-orange-500/20 text-orange-100"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{a.enabled === false ? "已停" : "启用中"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{tab === "workbench" ? (
|
{tab === "workbench" ? (
|
||||||
<WorkbenchPanel
|
<WorkbenchPanel
|
||||||
{...common}
|
{...common}
|
||||||
|
|||||||
@ -453,6 +453,25 @@ export default function YtLongPage() {
|
|||||||
await load();
|
await load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function toggleChannelEnabled(ch: Channel) {
|
||||||
|
const turningOn = ch.enabled === false;
|
||||||
|
try {
|
||||||
|
const r = await fetchJson(`/api/yt-long/channels/${ch.id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({ enabled: turningOn }),
|
||||||
|
});
|
||||||
|
const cleared = r.cleared as { jobs?: number } | undefined;
|
||||||
|
if (!turningOn && cleared) {
|
||||||
|
toast.push(`已停用「${ch.name}」· 清除任务 ${cleared.jobs ?? 0}`, "ok");
|
||||||
|
} else {
|
||||||
|
toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok");
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function retryJob(id: string) {
|
async function retryJob(id: string) {
|
||||||
await fetchJson(`/api/yt-long/jobs/${id}/retry`, { method: "POST" });
|
await fetchJson(`/api/yt-long/jobs/${id}/retry`, { method: "POST" });
|
||||||
toast.push("已重新入队", "ok");
|
toast.push("已重新入队", "ok");
|
||||||
@ -672,6 +691,20 @@ export default function YtLongPage() {
|
|||||||
meta={buildChannelMeta(ch)}
|
meta={buildChannelMeta(ch)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
{full ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={full.enabled === false ? "启用此频道" : "停用并清除任务"}
|
||||||
|
onClick={() => void toggleChannelEnabled(full)}
|
||||||
|
className={`shrink-0 rounded-lg px-2 py-1 text-[10px] ${
|
||||||
|
full.enabled === false
|
||||||
|
? "bg-white/5 text-slate-400"
|
||||||
|
: "bg-teal-500/15 text-teal-200"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{full.enabled === false ? "已停" : "启用中"}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="relative mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
|
<div className="relative mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
|
||||||
<div
|
<div
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user