fix: Shorts/TikTok 立即取样从当前抖音在播立刻开录

手动取样不再只入队 1 条、也不再被 YouTube 上传配额拦住;点击后按在播直播间创建任务并马上开始录制。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-14 11:40:12 -05:00
parent c7a7275229
commit 7f4a1de2c4
8 changed files with 259 additions and 17 deletions

View File

@ -3311,7 +3311,12 @@ def room_ids_with_shorts_job_today(push_date: str) -> set[str]:
conn.close()
def pick_shorts_channel(push_date: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
def pick_shorts_channel(
push_date: str,
cfg: dict[str, Any] | None = None,
*,
require_upload_quota: bool = True,
) -> dict[str, Any] | None:
"""Pick enabled channel with most room left today (Beijing day); under daily_min first."""
from .shorts_yt_quota import profile_id_for_channel, project_uploads_available
@ -3321,7 +3326,7 @@ def pick_shorts_channel(push_date: str, cfg: dict[str, Any] | None = None) -> di
scored: list[tuple[int, int, float, dict[str, Any]]] = []
for ch in channels:
pid = profile_id_for_channel(ch)
if not project_uploads_available(cfg, profile_id=pid):
if require_upload_quota and not project_uploads_available(cfg, profile_id=pid):
continue
used = shorts_channel_upload_count(str(ch["id"]), push_date)
daily_max = SHORTS_DAILY_FORCE
@ -3595,6 +3600,29 @@ def claim_pending_shorts_record() -> dict[str, Any] | None:
conn.close()
def claim_shorts_job_record(job_id: str) -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
cur = conn.execute(
"""
UPDATE shorts_jobs
SET status = 'recording', attempts = attempts + 1,
started_at = CASE WHEN started_at = 0 THEN ? ELSE started_at END,
updated_at = ?, error = ''
WHERE id = ? AND status = 'pending'
""",
(now, now, job_id),
)
conn.commit()
if cur.rowcount == 0:
return None
return _row_to_dict(conn.execute("SELECT * FROM shorts_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def claim_next_shorts_job() -> dict[str, Any] | None:
"""Prefer due upload, then pending record."""
job = claim_due_shorts_upload()

View File

@ -565,18 +565,22 @@ async def shorts_stop() -> dict[str, Any]:
@app.post("/api/shorts/sample-now")
async def shorts_sample_now() -> dict[str, Any]:
"""Manually trigger one live-room sample tick (does not affect monitor)."""
from .shorts_pipeline import try_fill_daily_quota, try_sample_live_rooms
"""Manually sample current Douyin lives and start recording immediately."""
from .shorts_pipeline import sample_live_now
cfg = db.get_settings_map()
if not cfg.get("shorts_enabled"):
raise HTTPException(400, "请先启用 Shorts")
n = try_sample_live_rooms(cfg)
qn = try_fill_daily_quota(cfg)
result = await asyncio.to_thread(sample_live_now, cfg)
recording = await shorts_pipeline.kick_pending_records(list(result.get("job_ids") or []))
st = shorts_pipeline.status()
st["just_enqueued"] = n + qn
st["just_sampled"] = n
st["just_quota_filled"] = qn
st["just_enqueued"] = int(result.get("enqueued") or 0)
st["just_sampled"] = int(result.get("enqueued") or 0)
st["just_quota_filled"] = 0
st["live_count"] = int(result.get("live_count") or 0)
st["skipped_dedupe"] = int(result.get("skipped_dedupe") or 0)
st["recording"] = recording
st["reason"] = str(result.get("reason") or "")
return st
@ -943,10 +947,19 @@ async def tiktok_stop() -> dict[str, Any]:
@app.post("/api/tiktok/sample-now")
async def tiktok_sample_now() -> dict[str, Any]:
from .tiktok_pipeline import try_sample_live_rooms
from .tiktok_pipeline import sample_live_now
n = await asyncio.to_thread(try_sample_live_rooms)
return {"ok": True, "enqueued": n, "status": tiktok_pipeline.status()}
result = await asyncio.to_thread(sample_live_now)
recording = await tiktok_pipeline.kick_pending_records(list(result.get("job_ids") or []))
return {
"ok": True,
"enqueued": int(result.get("enqueued") or 0),
"live_count": int(result.get("live_count") or 0),
"skipped_dedupe": int(result.get("skipped_dedupe") or 0),
"recording": recording,
"reason": str(result.get("reason") or ""),
"status": tiktok_pipeline.status(),
}
@app.get("/api/tiktok/channels")

View File

@ -57,6 +57,7 @@ def _enqueue_job(
stream_url: str = "",
cfg: dict[str, Any] | None = None,
channel_pk: str = "",
require_upload_quota: bool = True,
) -> Optional[dict[str, Any]]:
"""Internal enqueue; never raises."""
try:
@ -80,7 +81,7 @@ def _enqueue_job(
if used < daily_max:
channel = ch
if not channel:
channel = db.pick_shorts_channel(day, settings)
channel = db.pick_shorts_channel(day, settings, require_upload_quota=require_upload_quota)
if not channel:
return None
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
@ -177,6 +178,65 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
return 0
def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Manual sample from current Douyin lives; records even if YouTube upload quota is exhausted."""
settings = cfg or db.get_settings_map()
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
live_count = len(rooms)
empty: dict[str, Any] = {
"enqueued": 0,
"job_ids": [],
"live_count": live_count,
"skipped_dedupe": 0,
"reason": "",
}
if not settings.get("shorts_enabled"):
empty["reason"] = "请先启用 Shorts"
return empty
if live_count <= 0:
empty["reason"] = "当前没有抖音在播直播间"
return empty
day = push_date_from_ts(time.time())
any_live = settings.get("shorts_sample_any_live", True)
unused: list[dict[str, Any]] = []
skipped = 0
for room in rooms:
rid = str(room.get("room_id") or "")
if not rid:
continue
if not any_live and not _room_eligible(room, settings):
continue
if settings.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(rid, day):
skipped += 1
continue
unused.append(room)
if not unused:
empty["skipped_dedupe"] = skipped
empty["reason"] = f"在播 {live_count} 间均已今日取样"
return empty
if not db.pick_shorts_channel(day, settings, require_upload_quota=False):
empty["skipped_dedupe"] = skipped
empty["reason"] = "没有可用 Shorts 频道(或今日配额已满)"
return empty
gap = max(1, db.shorts_total_quota_gap(day))
batch = min(len(unused), gap, 8)
random.shuffle(unused)
job_ids: list[str] = []
for room in unused[:batch]:
sid = str(room.get("active_session_id") or "")
session = db.get_session(sid) if sid else None
job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings, require_upload_quota=False)
if job and job.get("id"):
job_ids.append(str(job["id"]))
return {
"enqueued": len(job_ids),
"job_ids": job_ids,
"live_count": live_count,
"skipped_dedupe": skipped,
"reason": "" if job_ids else "入队失败,请检查 Shorts 频道",
}
def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
"""Enqueue live-room clips toward each channel's daily_max before Beijing midnight."""
try:
@ -530,6 +590,28 @@ class ShortsPipeline:
self._task.cancel()
self._task = None
async def kick_pending_records(self, job_ids: list[str]) -> int:
ids = [str(j) for j in job_ids if str(j).strip()]
if not ids:
return 0
cfg = db.get_settings_map()
max_rec = self._record_max(cfg)
async def _drain() -> None:
leftover = list(ids)
while leftover:
while self._active_records >= max_rec:
await asyncio.sleep(0.25)
jid = leftover.pop(0)
job = db.claim_shorts_job_record(jid)
if not job:
continue
self._active_records += 1
asyncio.create_task(self._run_job(job, cfg))
asyncio.create_task(_drain())
return min(len(ids), max_rec)
async def _loop(self) -> None:
while not self._stop.is_set():
try:

View File

@ -381,6 +381,26 @@ def claim_pending_tiktok_record() -> dict[str, Any] | None:
conn.close()
def claim_tiktok_job_record(job_id: str) -> dict[str, Any] | None:
now = time.time()
with _lock:
conn = _connect()
try:
cur = conn.execute(
"""
UPDATE tiktok_jobs SET status = 'recording', started_at = ?, updated_at = ?, attempts = attempts + 1
WHERE id = ? AND status = 'pending'
""",
(now, now, job_id),
)
conn.commit()
if cur.rowcount == 0:
return None
return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (job_id,)).fetchone())
finally:
conn.close()
def claim_due_tiktok_upload() -> dict[str, Any] | None:
now = time.time()
with _lock:

View File

@ -42,10 +42,11 @@ def _enqueue_job(
stream_url: str = "",
cfg: dict[str, Any] | None = None,
channel_pk: str = "",
force: bool = False,
) -> Optional[dict[str, Any]]:
try:
settings = cfg or db.get_settings_map()
if not settings.get("tiktok_enabled"):
if not force and not settings.get("tiktok_enabled"):
return None
room_id = str((session or {}).get("room_id") or room.get("room_id") or "")
if room_id.startswith("yt:"):
@ -106,6 +107,64 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
return n
def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Manual sample: enqueue current Douyin lives and return job ids for immediate record."""
settings = cfg or db.get_settings_map()
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
live_count = len(rooms)
empty = {
"enqueued": 0,
"job_ids": [],
"live_count": live_count,
"skipped_dedupe": 0,
"reason": "",
}
if live_count <= 0:
empty["reason"] = "当前没有抖音在播直播间"
return empty
day = push_date_from_ts(time.time())
if settings.get("tiktok_sample_any_live", True):
candidates = list(rooms)
else:
candidates = [r for r in rooms if _room_eligible(r, settings)]
unused: list[dict[str, Any]] = []
skipped = 0
for room in candidates:
rid = str(room.get("room_id") or "")
if not rid:
continue
if settings.get("tiktok_dedupe_room_day", True) and tiktok_db.has_tiktok_job_for_room_day(rid, day):
skipped += 1
continue
unused.append(room)
if not unused:
empty["skipped_dedupe"] = skipped
empty["reason"] = f"在播 {live_count} 间均已今日取样"
return empty
if not tiktok_db.pick_tiktok_channel(day):
empty["skipped_dedupe"] = skipped
empty["reason"] = "没有可用 TikTok 账号(需 Cookie 且未满每日配额)"
return empty
gap = max(1, tiktok_db.tiktok_total_quota_gap(day))
batch = min(len(unused), gap, 8)
random.shuffle(unused)
job_ids: list[str] = []
for room in unused[:batch]:
sid = str(room.get("active_session_id") or "")
session = db.get_session(sid) if sid else None
job = _enqueue_job(session=session, room=room, cfg=settings, force=True)
if job and job.get("id"):
job_ids.append(str(job["id"]))
reason = "" if job_ids else "入队失败,请检查 TikTok 账号 Cookie"
return {
"enqueued": len(job_ids),
"job_ids": job_ids,
"live_count": live_count,
"skipped_dedupe": skipped,
"reason": reason,
}
class TikTokPipeline:
def __init__(self) -> None:
self._task: asyncio.Task | None = None
@ -166,6 +225,28 @@ class TikTokPipeline:
self._task.cancel()
self._task = None
async def kick_pending_records(self, job_ids: list[str]) -> int:
ids = [str(j) for j in job_ids if str(j).strip()]
if not ids:
return 0
cfg = db.get_settings_map()
max_rec = max(1, int(cfg.get("tiktok_max_concurrent") or 1))
async def _drain() -> None:
leftover = list(ids)
while leftover:
while self._active_records >= max_rec:
await asyncio.sleep(0.25)
jid = leftover.pop(0)
job = tiktok_db.claim_tiktok_job_record(jid)
if not job:
continue
self._active_records += 1
asyncio.create_task(self._run_record(job))
asyncio.create_task(_drain())
return min(len(ids), max_rec)
async def upload_job_now(self, job_id: str) -> dict[str, Any]:
job = tiktok_db.claim_tiktok_job_manual_upload(job_id)
if not job:

View File

@ -760,7 +760,13 @@ export default function ShortsPage() {
setBusy(true);
try {
const r = await fetchJson("/api/shorts/sample-now", { method: "POST" });
setMsg(`取样入队 ${r.just_enqueued ?? 0}(录完后自动错峰排程)`);
const n = Number(r.just_enqueued ?? 0);
const live = Number(r.live_count ?? 0);
if (n > 0) {
setMsg(`正在从 ${live} 路在播中录制 ${n} 条(录完后自动错峰排程)`);
} else {
setError(String(r.reason || "没有可取样的在播直播间"));
}
await load();
} catch (e) {
setError((e as Error).message);

View File

@ -910,7 +910,13 @@ export default function ShortsPage() {
setBusy(true);
try {
const r = await fetchJson("/api/shorts/sample-now", { method: "POST" });
setMsg(`取样入队 ${r.just_enqueued ?? 0}(录完后自动错峰排程)`);
const n = Number(r.just_enqueued ?? 0);
const live = Number(r.live_count ?? 0);
if (n > 0) {
setMsg(`正在从 ${live} 路在播中录制 ${n} 条(录完后自动错峰排程)`);
} else {
setError(String(r.reason || "没有可取样的在播直播间"));
}
await load();
} catch (e) {
setError((e as Error).message);

View File

@ -288,7 +288,13 @@ export default function TikTokPage() {
const sampleNow = async () => {
const r = await fetchJson("/api/tiktok/sample-now", { method: "POST" });
toast.push(`已取样 ${r.enqueued || 0} 条`, "ok");
const n = Number(r.enqueued || 0);
const live = Number(r.live_count || 0);
if (n > 0) {
toast.push(`正在从 ${live} 路在播中录制 ${n} 条`, "ok");
} else {
toast.push(String(r.reason || "没有可取样的在播直播间"), "err");
}
void load();
};