362 lines
14 KiB
Python
362 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Isolated TikTok pipeline — never touches Shorts or Douyin monitor."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import random
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any, Optional
|
|
|
|
from . import db
|
|
from . import tiktok_db
|
|
from . import tiktok_session
|
|
from .shorts_clip import record_clip, resolve_stream_url
|
|
from .tiktok_schedule import pick_upload_at, schedule_board
|
|
from .tiktok_upload import upload_tiktok_mp4
|
|
from .timeutil import push_date_from_ts
|
|
|
|
|
|
def _room_tags(room: dict[str, Any]) -> list[str]:
|
|
tags = room.get("tags") or []
|
|
if isinstance(tags, str):
|
|
return [t.strip() for t in tags.split(",") if t.strip()]
|
|
return [str(t).strip() for t in tags if str(t).strip()]
|
|
|
|
|
|
def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool:
|
|
trigger = str(cfg.get("tiktok_trigger") or "tagged").strip().lower()
|
|
tags = _room_tags(room)
|
|
if trigger == "all":
|
|
return True
|
|
if trigger == "favorite":
|
|
return any(t in {"收藏", "重点", "priority", "vip", "高优", "shorts", "tiktok"} for t in tags)
|
|
tag = str(cfg.get("tiktok_tag") or "shorts").strip() or "shorts"
|
|
return tag in tags or "tiktok" in tags or "shorts" in tags
|
|
|
|
|
|
def _enqueue_job(
|
|
*,
|
|
session: dict[str, Any] | None,
|
|
room: dict[str, Any],
|
|
stream_url: str = "",
|
|
cfg: dict[str, Any] | None = None,
|
|
channel_pk: str = "",
|
|
) -> Optional[dict[str, Any]]:
|
|
try:
|
|
settings = cfg or db.get_settings_map()
|
|
if 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:"):
|
|
return None
|
|
day = push_date_from_ts(float((session or {}).get("started_at") or time.time()))
|
|
if settings.get("tiktok_dedupe_room_day", True) and room_id:
|
|
if tiktok_db.has_tiktok_job_for_room_day(room_id, day):
|
|
return None
|
|
channel: dict[str, Any] | None = None
|
|
if channel_pk:
|
|
ch = tiktok_db.get_tiktok_channel(channel_pk)
|
|
if ch and ch.get("enabled") and tiktok_session.channel_has_session(ch):
|
|
used = tiktok_db.tiktok_channel_upload_count(channel_pk, day)
|
|
if used < db.TIKTOK_DAILY_FORCE:
|
|
channel = ch
|
|
if not channel:
|
|
channel = tiktok_db.pick_tiktok_channel(day)
|
|
if not channel:
|
|
return None
|
|
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
|
|
return tiktok_db.create_tiktok_job(
|
|
session_id=sid,
|
|
room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""),
|
|
room_id=room_id,
|
|
source_url=str((session or {}).get("source_url") or room.get("url") or ""),
|
|
anchor_name=str(
|
|
(session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or ""
|
|
),
|
|
stream_url=str(stream_url or ""),
|
|
channel_pk=str(channel["id"]),
|
|
push_date=day,
|
|
)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
|
|
settings = cfg or db.get_settings_map()
|
|
if not settings.get("tiktok_enabled") or not settings.get("tiktok_live_sample", True):
|
|
return 0
|
|
batch = max(1, int(settings.get("tiktok_live_sample_batch") or 1))
|
|
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
|
|
if settings.get("tiktok_sample_any_live", True):
|
|
candidates = list(rooms)
|
|
else:
|
|
candidates = [r for r in rooms if _room_eligible(r, settings)]
|
|
if not candidates:
|
|
return 0
|
|
random.shuffle(candidates)
|
|
n = 0
|
|
for room in candidates[: batch * 3]:
|
|
if n >= batch:
|
|
break
|
|
sid = str(room.get("active_session_id") or "")
|
|
session = db.get_session(sid) if sid else None
|
|
if _enqueue_job(session=session, room=room, cfg=settings):
|
|
n += 1
|
|
return n
|
|
|
|
|
|
class TikTokPipeline:
|
|
def __init__(self) -> None:
|
|
self._task: asyncio.Task | None = None
|
|
self._stop = asyncio.Event()
|
|
self._active_records = 0
|
|
self._active_uploads = 0
|
|
self.processed = 0
|
|
self.sampled = 0
|
|
self.last_error = ""
|
|
self._last_sample_at = 0.0
|
|
self._last_oauth_check_at = 0.0
|
|
self._last_auto_retry_at = 0.0
|
|
|
|
def status(self) -> dict[str, Any]:
|
|
cfg = db.get_settings_map()
|
|
try:
|
|
board = schedule_board(limit=30)
|
|
except Exception:
|
|
board = {}
|
|
oauth_issues = []
|
|
for ch in tiktok_db.list_tiktok_channels(enabled=True):
|
|
ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1)
|
|
if ok_flag == 0 or not tiktok_session.channel_has_session(ch):
|
|
oauth_issues.append(
|
|
{
|
|
"id": ch.get("id"),
|
|
"name": ch.get("name"),
|
|
"oauth_error": ch.get("oauth_error") or "未授权",
|
|
}
|
|
)
|
|
return {
|
|
"running": bool(self._task and not self._task.done()),
|
|
"busy": self._active_records > 0 or self._active_uploads > 0,
|
|
"enabled": bool(cfg.get("tiktok_enabled")),
|
|
"processed": self.processed,
|
|
"sampled": self.sampled,
|
|
"quota_gap": tiktok_db.tiktok_total_quota_gap(),
|
|
"last_error": self.last_error,
|
|
"clip_sec": int(cfg.get("tiktok_clip_sec") or 15),
|
|
"douyin_live_count": len(db.list_live_douyin_rooms_for_shorts(limit=400)),
|
|
"board": board,
|
|
"oauth_issues": oauth_issues,
|
|
"stats": tiktok_db.tiktok_stats(),
|
|
}
|
|
|
|
async def start(self) -> None:
|
|
if self._task and not self._task.done():
|
|
return
|
|
self._stop.clear()
|
|
self._task = asyncio.create_task(self._loop(), name="tiktok-pipeline")
|
|
|
|
async def stop(self) -> None:
|
|
self._stop.set()
|
|
if self._task:
|
|
try:
|
|
await asyncio.wait_for(self._task, timeout=5)
|
|
except Exception:
|
|
self._task.cancel()
|
|
self._task = None
|
|
|
|
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:
|
|
raise ValueError("任务不可立即上传(需要成片且未发布;上传中卡住的可强制重试)")
|
|
await self._do_upload(job)
|
|
fresh = tiktok_db.get_tiktok_job(job_id)
|
|
if not fresh:
|
|
raise ValueError("任务不存在")
|
|
if str(fresh.get("status") or "") not in {"uploaded", "done"}:
|
|
raise ValueError(str(fresh.get("error") or "上传未完成"))
|
|
return fresh
|
|
|
|
async def _loop(self) -> None:
|
|
while not self._stop.is_set():
|
|
try:
|
|
cfg = db.get_settings_map()
|
|
if not cfg.get("tiktok_enabled"):
|
|
await asyncio.sleep(5)
|
|
continue
|
|
interval = max(60.0, float(cfg.get("tiktok_live_sample_interval_sec") or 180))
|
|
if cfg.get("tiktok_live_sample", True) and (time.time() - self._last_sample_at) >= interval:
|
|
self._last_sample_at = time.time()
|
|
n = try_sample_live_rooms(cfg)
|
|
if n:
|
|
self.sampled += n
|
|
session_interval = max(600.0, float(cfg.get("tiktok_oauth_check_interval_sec") or 3600))
|
|
if (time.time() - self._last_oauth_check_at) >= session_interval:
|
|
self._last_oauth_check_at = time.time()
|
|
for ch in tiktok_db.list_tiktok_channels(enabled=True):
|
|
asyncio.create_task(asyncio.to_thread(tiktok_session.probe_channel_session, ch))
|
|
retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300))
|
|
if cfg.get("tiktok_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval:
|
|
self._last_auto_retry_at = time.time()
|
|
for j in tiktok_db.list_auto_retry_tiktok_failed(limit=10):
|
|
tiktok_db.update_tiktok_job(
|
|
str(j["id"]),
|
|
status="scheduled",
|
|
upload_at=pick_upload_at(channel_pk=str(j.get("channel_pk") or ""), cfg=cfg),
|
|
error="",
|
|
)
|
|
try:
|
|
tiktok_db.reclaim_stale_tiktok_uploads(max_age_sec=180)
|
|
except Exception:
|
|
pass
|
|
max_up = max(1, int(cfg.get("tiktok_max_concurrent") or 1))
|
|
while self._active_uploads < max_up:
|
|
job = tiktok_db.claim_due_tiktok_upload()
|
|
if not job:
|
|
break
|
|
self._active_uploads += 1
|
|
asyncio.create_task(self._run_upload(job))
|
|
max_rec = max(1, int(cfg.get("tiktok_max_concurrent") or 1))
|
|
while self._active_records < max_rec:
|
|
job = tiktok_db.claim_pending_tiktok_record()
|
|
if not job:
|
|
break
|
|
self._active_records += 1
|
|
asyncio.create_task(self._run_record(job))
|
|
except Exception as exc:
|
|
self.last_error = str(exc)[:240]
|
|
await asyncio.sleep(3)
|
|
|
|
async def _run_upload(self, job: dict[str, Any]) -> None:
|
|
try:
|
|
await self._do_upload(job)
|
|
self.processed += 1
|
|
except Exception as exc:
|
|
self.last_error = str(exc)[:240]
|
|
tiktok_db.update_tiktok_job(
|
|
str(job.get("id") or ""),
|
|
status="failed",
|
|
error=str(exc)[:500],
|
|
finished_at=time.time(),
|
|
)
|
|
finally:
|
|
self._active_uploads = max(0, self._active_uploads - 1)
|
|
|
|
async def _run_record(self, job: dict[str, Any]) -> None:
|
|
try:
|
|
await self._do_record(job)
|
|
except Exception as exc:
|
|
self.last_error = str(exc)[:240]
|
|
tiktok_db.update_tiktok_job(
|
|
str(job.get("id") or ""),
|
|
status="failed",
|
|
error=str(exc)[:500],
|
|
finished_at=time.time(),
|
|
)
|
|
finally:
|
|
self._active_records = max(0, self._active_records - 1)
|
|
|
|
async def _do_record(self, job: dict[str, Any]) -> None:
|
|
cfg = db.get_settings_map()
|
|
jid = str(job.get("id") or "")
|
|
cookie = str(cfg.get("dy_cookie") or "")
|
|
stream = await resolve_stream_url(
|
|
source_url=str(job.get("source_url") or ""),
|
|
stream_url=str(job.get("stream_url") or ""),
|
|
cookie=cookie,
|
|
)
|
|
if not stream:
|
|
tiktok_db.update_tiktok_job(
|
|
jid,
|
|
status="failed",
|
|
error="无法获取直播流(可能已停播)",
|
|
finished_at=time.time(),
|
|
)
|
|
return
|
|
sec = max(5, int(cfg.get("tiktok_clip_sec") or 15))
|
|
outcome = await record_clip(job_id=f"tiktok_{jid[:8]}", stream_url=stream, seconds=sec)
|
|
if not outcome.get("ok"):
|
|
tiktok_db.update_tiktok_job(
|
|
jid,
|
|
status="failed",
|
|
error=str(outcome.get("error") or "录制失败")[:500],
|
|
finished_at=time.time(),
|
|
)
|
|
return
|
|
out_path = str(outcome.get("path") or "")
|
|
seconds = float(outcome.get("seconds") or sec)
|
|
day = str(job.get("push_date") or push_date_from_ts(time.time()))
|
|
ch_pk = str(job.get("channel_pk") or "")
|
|
if cfg.get("tiktok_auto_upload", True):
|
|
upload_at = pick_upload_at(channel_pk=ch_pk, push_date=day, cfg=cfg)
|
|
tiktok_db.update_tiktok_job(
|
|
jid,
|
|
status="scheduled",
|
|
clip_path=out_path,
|
|
clip_seconds=seconds,
|
|
stream_url=stream,
|
|
upload_at=upload_at,
|
|
error="",
|
|
)
|
|
else:
|
|
tiktok_db.update_tiktok_job(
|
|
jid, status="recorded", clip_path=out_path, clip_seconds=seconds, stream_url=stream, error=""
|
|
)
|
|
|
|
async def _do_upload(self, job: dict[str, Any]) -> None:
|
|
cfg = db.get_settings_map()
|
|
jid = str(job.get("id") or "")
|
|
fresh = tiktok_db.get_tiktok_job(jid) or job
|
|
clip = str(fresh.get("clip_path") or "")
|
|
if not clip or not Path(clip).is_file():
|
|
raise ValueError("成片文件不存在")
|
|
channel = tiktok_db.get_tiktok_channel(str(fresh.get("channel_pk") or ""))
|
|
if not channel:
|
|
raise ValueError("账号不存在")
|
|
if not tiktok_session.channel_has_session(channel):
|
|
tiktok_db.update_tiktok_job(jid, status="scheduled", error="账号未配置 Cookie")
|
|
return
|
|
title_tpl = str(channel.get("title_template") or "{anchor} #fyp")
|
|
desc_tpl = str(channel.get("description_template") or "")
|
|
anchor = str(fresh.get("anchor_name") or fresh.get("room_id") or "live")
|
|
url = str(fresh.get("source_url") or "")
|
|
title = title_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
|
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
|
if not tiktok_db.touch_tiktok_upload_lease(jid):
|
|
return
|
|
result = await upload_tiktok_mp4(
|
|
file_path=clip,
|
|
title=title,
|
|
description=desc,
|
|
privacy_level=str(channel.get("privacy_level") or "PUBLIC_TO_EVERYONE"),
|
|
channel_pk=str(channel["id"]),
|
|
)
|
|
if not tiktok_db.finalize_tiktok_upload(
|
|
jid,
|
|
tiktok_publish_id=str(result.get("publish_id") or ""),
|
|
tiktok_video_id=str(result.get("video_id") or ""),
|
|
):
|
|
return
|
|
tiktok_db.update_tiktok_channel(
|
|
str(channel["id"]),
|
|
oauth_ok=1,
|
|
oauth_checked_at=time.time(),
|
|
oauth_error="",
|
|
)
|
|
if cfg.get("tiktok_delete_clip_after_upload", True):
|
|
try:
|
|
Path(clip).unlink(missing_ok=True)
|
|
except Exception:
|
|
pass
|
|
|
|
@staticmethod
|
|
def _delete_clip(path: str) -> None:
|
|
try:
|
|
Path(path).unlink(missing_ok=True)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
tiktok_pipeline = TikTokPipeline()
|