feat(monitor): 超级编导自动追加,任务设置里按间隔补新作品
任务编辑里新增「自动从超级编导追加新作品」(抖音 + 作品模式才有): - 每 N 分钟(默认 2 小时)按**发布时间**查一次数据中心,把这段时间新发布、 还没在任务里的作品追加进去;已有的不会重复。 - start_time/end_time 实测按发布时间过滤,所以老活动里今天才发的作品也能 收到 —— 按活动创建时间筛会整批漏掉。 - 查询窗口首尾重叠 1 小时,兜住数据中心的索引延迟;失败时 last_at 不动, 恢复后这段时间的作品仍在窗口里,只把调度钟按 30 分钟退避重试。 - 同步跑在后台任务里,不阻塞采集调度。 Co-Authored-By: Claude <[email protected]>
This commit is contained in:
@@ -117,6 +117,25 @@ class MonitorTask(MonitorBase):
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
notify_failures: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
|
||||
# 超级编导自动追加:每隔 N 分钟查一次这段时间**新发布**的作品,追加到本任务。
|
||||
# 只有抖音的作品模式任务能开(目标是作品 id;博主模式的目标是主页)。
|
||||
#
|
||||
# ``next_at`` 是调度钟,成功失败都往后推(失败按较短的退避重试);
|
||||
# ``last_at`` 是**成功**的窗口起点,失败时不动 —— 这样接口挂了两个小时,恢复后
|
||||
# 那两小时的作品还在窗口里,不会悄悄漏掉。
|
||||
superdir_auto_enabled: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, default=False
|
||||
)
|
||||
superdir_auto_interval_minutes: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=120
|
||||
)
|
||||
superdir_auto_next_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
superdir_auto_last_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
superdir_auto_last_added: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
superdir_auto_last_error: Mapped[str] = mapped_column(
|
||||
String(500), nullable=False, default=""
|
||||
)
|
||||
|
||||
# Scheduler state. Persisted so the schedule survives an API restart.
|
||||
next_run_at: Mapped[Optional[int]] = mapped_column(BigInteger, index=True)
|
||||
last_run_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
|
||||
@@ -44,14 +44,15 @@ import random
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import or_, select
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from ..services import crawler_manager
|
||||
from . import app_settings, schedule, upstream
|
||||
from . import adapters, app_settings, schedule, superdir, upstream
|
||||
from .db import get_session
|
||||
from .models import (
|
||||
MODE_NOTE,
|
||||
RUN_INTERRUPTED,
|
||||
RUN_PENDING,
|
||||
RUN_RUNNING,
|
||||
@@ -141,6 +142,8 @@ class MonitorScheduler:
|
||||
# Avoids logging "no cookie" on every single tick. Per platform, because
|
||||
# warning once for Xiaohongshu must not silence the warning for Douyin.
|
||||
self._warned_no_cookie: set = set()
|
||||
# 超级编导自动追加是网络操作,单独一个后台任务,不占调度循环。
|
||||
self._superdir_task: Optional[asyncio.Task] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._loop_task is not None and not self._loop_task.done():
|
||||
@@ -186,8 +189,72 @@ class MonitorScheduler:
|
||||
await self._maybe_send_digest()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] daily digest failed: {exc}")
|
||||
# 超级编导自动追加。和采集、推送都无关,单独一段 try。
|
||||
try:
|
||||
await self._maybe_sync_superdir()
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] 超级编导自动追加失败: {exc}")
|
||||
await asyncio.sleep(POLL_INTERVAL_SECONDS)
|
||||
|
||||
async def _maybe_sync_superdir(self) -> None:
|
||||
"""到点的任务补一批超级编导新发布的作品。
|
||||
|
||||
**放到后台任务里跑**:它要发第三方接口的请求(慢的时候一次好几秒),
|
||||
堵在调度循环里会推迟其他任务的采集。上一次还没跑完就跳过这一 tick ——
|
||||
不需要排队,下一次自然还会来。
|
||||
"""
|
||||
if self._superdir_task is not None and not self._superdir_task.done():
|
||||
return
|
||||
self._superdir_task = asyncio.create_task(self._sync_superdir())
|
||||
|
||||
async def _sync_superdir(self) -> None:
|
||||
try:
|
||||
now = get_current_timestamp()
|
||||
async with get_session() as session:
|
||||
due = list(
|
||||
await session.scalars(
|
||||
select(MonitorTask.id).where(
|
||||
MonitorTask.platform == adapters.PLATFORM_DY,
|
||||
MonitorTask.mode == MODE_NOTE,
|
||||
MonitorTask.superdir_auto_enabled.is_(True),
|
||||
or_(
|
||||
MonitorTask.superdir_auto_next_at.is_(None),
|
||||
MonitorTask.superdir_auto_next_at <= now,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||
print(f"[monitor.scheduler] 读取超级编导自动追加任务失败: {exc}")
|
||||
return
|
||||
|
||||
for task_id in due:
|
||||
await self._sync_one_superdir(task_id)
|
||||
|
||||
async def _sync_one_superdir(self, task_id: int) -> None:
|
||||
async with get_session() as session:
|
||||
task = await session.get(MonitorTask, task_id)
|
||||
if task is None or not task.superdir_auto_enabled:
|
||||
return
|
||||
try:
|
||||
result = await superdir.sync_task(session, task)
|
||||
except Exception as exc:
|
||||
# 失败**不推** last_at:接口挂了一小时,恢复后这一小时的作品还在
|
||||
# 查询窗口里。只把调度钟往后挪一段较短的时间再试。
|
||||
task.superdir_auto_last_error = str(exc)[:500]
|
||||
task.superdir_auto_next_at = (
|
||||
get_current_timestamp() + superdir.SYNC_FAILURE_RETRY_MS
|
||||
)
|
||||
print(
|
||||
f"[monitor.scheduler] 超级编导自动追加失败 task={task_id}: {exc}"
|
||||
)
|
||||
return
|
||||
if result["added"]:
|
||||
print(
|
||||
f"[monitor.scheduler] 超级编导自动追加 task={task_id} "
|
||||
f"新增 {result['added']} 条(共 {result['total']})"
|
||||
)
|
||||
|
||||
async def _maybe_check_upstream(self) -> None:
|
||||
"""到点就 fetch 一次上游仓库,看它有没有新提交。
|
||||
|
||||
|
||||
@@ -245,6 +245,12 @@ async def create_task(session: AsyncSession, payload: Dict[str, Any]) -> Monitor
|
||||
platform = payload.get("platform") or PLATFORM_XHS
|
||||
platforms.ensure_runnable(platform)
|
||||
|
||||
# 超级编导只接抖音分发,追加进去的又只能是作品 id —— 别的组合开了也永远不会跑,
|
||||
# 与其让它静静地什么都不做,不如在保存时就说清楚。
|
||||
superdir_auto = bool(payload.get("superdir_auto_enabled", False))
|
||||
if superdir_auto and (platform != adapters.PLATFORM_DY or mode != MODE_NOTE):
|
||||
raise ValueError("超级编导自动追加只能用在抖音的作品模式任务上")
|
||||
|
||||
now = get_current_timestamp()
|
||||
|
||||
# Fall back to the configured defaults for anything the caller left out, so
|
||||
@@ -274,6 +280,11 @@ async def create_task(session: AsyncSession, payload: Dict[str, Any]) -> Monitor
|
||||
run_timeout_seconds=payload.get("run_timeout_seconds", 3600),
|
||||
notify_enabled=payload.get("notify_enabled", False),
|
||||
notify_failures=payload.get("notify_failures", True),
|
||||
# 超级编导自动追加。刚打开时下一轮 tick 就会跑一次(窗口从一个间隔前算),
|
||||
# 不需要等到「创建后两小时」。
|
||||
superdir_auto_enabled=bool(payload.get("superdir_auto_enabled", False)),
|
||||
superdir_auto_interval_minutes=payload.get("superdir_auto_interval_minutes") or 120,
|
||||
superdir_auto_next_at=now if payload.get("superdir_auto_enabled") else None,
|
||||
next_run_at=schedule.next_occurrence(
|
||||
mode=schedule_mode,
|
||||
interval_minutes=interval_minutes,
|
||||
@@ -332,10 +343,26 @@ async def update_task(session: AsyncSession, task_id: int, payload: Dict[str, An
|
||||
"run_timeout_seconds",
|
||||
"notify_enabled",
|
||||
"notify_failures",
|
||||
"superdir_auto_interval_minutes",
|
||||
):
|
||||
if field in payload and payload[field] is not None:
|
||||
setattr(task, field, payload[field])
|
||||
|
||||
# 自动追加的开关要顺带经营调度钟:刚打开就排一次(否则新开的人要等一整个间隔
|
||||
# 才看到第一次同步);关掉就清掉,免得停了几个月之后又被 tick 捡起来。
|
||||
if payload.get("superdir_auto_enabled") is not None:
|
||||
auto_enabled = bool(payload["superdir_auto_enabled"])
|
||||
if auto_enabled and (
|
||||
task.platform != adapters.PLATFORM_DY or task.mode != MODE_NOTE
|
||||
):
|
||||
raise ValueError("超级编导自动追加只能用在抖音的作品模式任务上")
|
||||
if auto_enabled and not task.superdir_auto_enabled:
|
||||
task.superdir_auto_next_at = get_current_timestamp()
|
||||
task.superdir_auto_last_error = ""
|
||||
task.superdir_auto_enabled = auto_enabled
|
||||
if not auto_enabled:
|
||||
task.superdir_auto_next_at = None
|
||||
|
||||
# The clock lists are stored as comma-separated text, so they cannot go
|
||||
# through the generic loop above.
|
||||
if payload.get("schedule_hours") is not None:
|
||||
@@ -1343,6 +1370,12 @@ async def list_tasks(
|
||||
"run_timeout_seconds": task.run_timeout_seconds,
|
||||
"notify_enabled": task.notify_enabled,
|
||||
"notify_failures": task.notify_failures,
|
||||
"superdir_auto_enabled": task.superdir_auto_enabled,
|
||||
"superdir_auto_interval_minutes": task.superdir_auto_interval_minutes,
|
||||
"superdir_auto_next_at": task.superdir_auto_next_at,
|
||||
"superdir_auto_last_at": task.superdir_auto_last_at,
|
||||
"superdir_auto_last_added": task.superdir_auto_last_added,
|
||||
"superdir_auto_last_error": task.superdir_auto_last_error,
|
||||
"next_run_at": task.next_run_at,
|
||||
"last_run_at": task.last_run_at,
|
||||
"last_status": task.last_status,
|
||||
|
||||
+102
-1
@@ -27,9 +27,11 @@ from datetime import date, datetime, time as day_time, timedelta, timezone
|
||||
from typing import Any, AsyncIterator, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from . import adapters, app_settings, service, video_link
|
||||
from .models import MODE_NOTE, MonitorTarget, MonitorTask
|
||||
|
||||
@@ -64,6 +66,16 @@ VIDEO_CONCURRENCY = 6
|
||||
MAX_TARGETS = 1000
|
||||
MAX_RANGE_DAYS = 31
|
||||
|
||||
# 自动追加每次查询的窗口往回**多覆盖**一小时。数据中心对刚发布的作品有索引延迟:
|
||||
# 卡在两次查询边界上的那一条,如果窗口首尾相接就会被漏掉。重叠部分靠去重消化。
|
||||
SYNC_OVERLAP_SECONDS = 3600
|
||||
# 一次自动追加最多处理这么多条。超过说明窗口开得太久(进程停过几天),先加能加的,
|
||||
# 剩下的留到下一次 —— 这比整批拒绝、然后每 30 分钟重试一次要有用。
|
||||
MAX_SYNC_VIDEOS = 500
|
||||
# 自动追加失败后的重试间隔。不能用正常的间隔:接口挂一小时的话,等两小时才重试
|
||||
# 意味着恢复后还要再等两小时。
|
||||
SYNC_FAILURE_RETRY_MS = 30 * 60_000
|
||||
|
||||
# 中国没有夏令时,固定 +8 比 zoneinfo 稳 —— 镜像里不一定装了 tzdata。
|
||||
CN_TZ = timezone(timedelta(hours=8))
|
||||
|
||||
@@ -446,6 +458,95 @@ def _aweme_ids(links: Sequence[str]) -> List[str]:
|
||||
return ids
|
||||
|
||||
|
||||
async def _fetch_published(
|
||||
token: str, client: httpx.AsyncClient, start_ts: int, end_ts: int
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""按**发布时间**取作品,不分活动。
|
||||
|
||||
``start_time/end_time`` 实测是按发布时间过滤的(Unix 秒),这正是自动追加要的:
|
||||
一条活动可能早就建好,作品却是今天才发 —— 按活动创建时间筛会整批漏掉。
|
||||
"""
|
||||
return await _paginate(
|
||||
"/member/douyin/data_center/page",
|
||||
{
|
||||
"video_status": -1,
|
||||
"start_time": int(start_ts),
|
||||
"end_time": int(end_ts),
|
||||
},
|
||||
token,
|
||||
client,
|
||||
page_size=VIDEO_PAGE_SIZE,
|
||||
max_pages=max(1, (MAX_SYNC_VIDEOS + VIDEO_PAGE_SIZE - 1) // VIDEO_PAGE_SIZE + 1),
|
||||
)
|
||||
|
||||
|
||||
async def sync_task(session: AsyncSession, task: MonitorTask) -> Dict[str, Any]:
|
||||
"""查一次「上次成功之后新发布的」作品,追加到 ``task``。
|
||||
|
||||
调用方负责提交会话。字段更新也在这里做:成功才把 ``last_at`` 推到现在,失败时
|
||||
保持原值 —— 接口挂了三个小时,恢复后那三个小时的作品仍在窗口里,不会静默漏掉。
|
||||
|
||||
返回 ``{"fetched": 可用的条数, "added": 真正新增的条数, "total": 任务现有目标数}``。
|
||||
"""
|
||||
if task.platform != adapters.PLATFORM_DY:
|
||||
raise ValueError("自动追加只支持抖音任务")
|
||||
if task.mode != MODE_NOTE:
|
||||
raise ValueError("自动追加只能用在作品模式的监控任务上")
|
||||
|
||||
token = await get_token(session, task.platform)
|
||||
if not token:
|
||||
raise SuperDirError(
|
||||
"", "还没有配置超级编导 Token —— 到「设置」页填「超级编导 Token」"
|
||||
)
|
||||
|
||||
now_ms = get_current_timestamp()
|
||||
interval_ms = max(1, int(task.superdir_auto_interval_minutes or 120)) * 60_000
|
||||
# 第一次跑(或从没成功过):从「一个间隔之前」开始看,别一上来就翻整段历史。
|
||||
since_ms = (
|
||||
task.superdir_auto_last_at or (now_ms - interval_ms)
|
||||
) - SYNC_OVERLAP_SECONDS * 1000
|
||||
|
||||
async with _client_session() as client:
|
||||
videos = await _fetch_published(
|
||||
token, client, since_ms // 1000, now_ms // 1000
|
||||
)
|
||||
|
||||
links: List[str] = []
|
||||
seen: set = set()
|
||||
for video in videos:
|
||||
if not _is_public(video):
|
||||
continue
|
||||
share_url = str(video.get("share_url") or "").strip()
|
||||
aweme_id = video_link.aweme_id_from_url(share_url)
|
||||
if not aweme_id or aweme_id in seen:
|
||||
continue
|
||||
seen.add(aweme_id)
|
||||
links.append(share_url)
|
||||
if len(links) >= MAX_SYNC_VIDEOS:
|
||||
break
|
||||
|
||||
if links:
|
||||
_, added, total = await append_task(
|
||||
session, task.id, links, platform=task.platform
|
||||
)
|
||||
else:
|
||||
added = 0
|
||||
total = int(
|
||||
await session.scalar(
|
||||
select(func.count())
|
||||
.select_from(MonitorTarget)
|
||||
.where(MonitorTarget.task_id == task.id)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
|
||||
task.superdir_auto_last_at = now_ms
|
||||
task.superdir_auto_last_added = added
|
||||
task.superdir_auto_last_error = ""
|
||||
task.superdir_auto_next_at = now_ms + interval_ms
|
||||
return {"fetched": len(links), "added": added, "total": total}
|
||||
|
||||
|
||||
async def create_task(
|
||||
session: AsyncSession,
|
||||
links: Sequence[str],
|
||||
|
||||
@@ -64,6 +64,9 @@ class MonitorTaskCreate(BaseModel):
|
||||
# 异常频率低且意味着任务已经停止工作(默认开,否则你会一直不知道)。
|
||||
notify_enabled: bool = False
|
||||
notify_failures: bool = True
|
||||
# 超级编导自动追加(只有抖音的作品模式任务能用,服务层会校验)。
|
||||
superdir_auto_enabled: bool = False
|
||||
superdir_auto_interval_minutes: int = Field(default=120, ge=30, le=1440)
|
||||
# Raw pasted values: full URLs or bare ids, in either form.
|
||||
targets: List[str] = Field(min_length=1)
|
||||
|
||||
@@ -100,6 +103,10 @@ class MonitorTaskUpdate(BaseModel):
|
||||
run_timeout_seconds: Optional[int] = Field(default=None, ge=60, le=86400)
|
||||
notify_enabled: Optional[bool] = None
|
||||
notify_failures: Optional[bool] = None
|
||||
superdir_auto_enabled: Optional[bool] = None
|
||||
superdir_auto_interval_minutes: Optional[int] = Field(
|
||||
default=None, ge=30, le=1440
|
||||
)
|
||||
# When present, replaces the whole target list.
|
||||
targets: Optional[List[str]] = None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user