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_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||||
notify_failures: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
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.
|
# Scheduler state. Persisted so the schedule survives an API restart.
|
||||||
next_run_at: Mapped[Optional[int]] = mapped_column(BigInteger, index=True)
|
next_run_at: Mapped[Optional[int]] = mapped_column(BigInteger, index=True)
|
||||||
last_run_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
last_run_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||||
|
|||||||
@@ -44,14 +44,15 @@ import random
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import or_, select
|
||||||
|
|
||||||
from tools.time_util import get_current_timestamp
|
from tools.time_util import get_current_timestamp
|
||||||
|
|
||||||
from ..services import crawler_manager
|
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 .db import get_session
|
||||||
from .models import (
|
from .models import (
|
||||||
|
MODE_NOTE,
|
||||||
RUN_INTERRUPTED,
|
RUN_INTERRUPTED,
|
||||||
RUN_PENDING,
|
RUN_PENDING,
|
||||||
RUN_RUNNING,
|
RUN_RUNNING,
|
||||||
@@ -141,6 +142,8 @@ class MonitorScheduler:
|
|||||||
# Avoids logging "no cookie" on every single tick. Per platform, because
|
# Avoids logging "no cookie" on every single tick. Per platform, because
|
||||||
# warning once for Xiaohongshu must not silence the warning for Douyin.
|
# warning once for Xiaohongshu must not silence the warning for Douyin.
|
||||||
self._warned_no_cookie: set = set()
|
self._warned_no_cookie: set = set()
|
||||||
|
# 超级编导自动追加是网络操作,单独一个后台任务,不占调度循环。
|
||||||
|
self._superdir_task: Optional[asyncio.Task] = None
|
||||||
|
|
||||||
async def start(self) -> None:
|
async def start(self) -> None:
|
||||||
if self._loop_task is not None and not self._loop_task.done():
|
if self._loop_task is not None and not self._loop_task.done():
|
||||||
@@ -186,8 +189,72 @@ class MonitorScheduler:
|
|||||||
await self._maybe_send_digest()
|
await self._maybe_send_digest()
|
||||||
except Exception as exc: # pragma: no cover - keep the loop alive
|
except Exception as exc: # pragma: no cover - keep the loop alive
|
||||||
print(f"[monitor.scheduler] daily digest failed: {exc}")
|
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)
|
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:
|
async def _maybe_check_upstream(self) -> None:
|
||||||
"""到点就 fetch 一次上游仓库,看它有没有新提交。
|
"""到点就 fetch 一次上游仓库,看它有没有新提交。
|
||||||
|
|
||||||
|
|||||||
@@ -245,6 +245,12 @@ async def create_task(session: AsyncSession, payload: Dict[str, Any]) -> Monitor
|
|||||||
platform = payload.get("platform") or PLATFORM_XHS
|
platform = payload.get("platform") or PLATFORM_XHS
|
||||||
platforms.ensure_runnable(platform)
|
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()
|
now = get_current_timestamp()
|
||||||
|
|
||||||
# Fall back to the configured defaults for anything the caller left out, so
|
# 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),
|
run_timeout_seconds=payload.get("run_timeout_seconds", 3600),
|
||||||
notify_enabled=payload.get("notify_enabled", False),
|
notify_enabled=payload.get("notify_enabled", False),
|
||||||
notify_failures=payload.get("notify_failures", True),
|
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(
|
next_run_at=schedule.next_occurrence(
|
||||||
mode=schedule_mode,
|
mode=schedule_mode,
|
||||||
interval_minutes=interval_minutes,
|
interval_minutes=interval_minutes,
|
||||||
@@ -332,10 +343,26 @@ async def update_task(session: AsyncSession, task_id: int, payload: Dict[str, An
|
|||||||
"run_timeout_seconds",
|
"run_timeout_seconds",
|
||||||
"notify_enabled",
|
"notify_enabled",
|
||||||
"notify_failures",
|
"notify_failures",
|
||||||
|
"superdir_auto_interval_minutes",
|
||||||
):
|
):
|
||||||
if field in payload and payload[field] is not None:
|
if field in payload and payload[field] is not None:
|
||||||
setattr(task, field, payload[field])
|
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
|
# The clock lists are stored as comma-separated text, so they cannot go
|
||||||
# through the generic loop above.
|
# through the generic loop above.
|
||||||
if payload.get("schedule_hours") is not None:
|
if payload.get("schedule_hours") is not None:
|
||||||
@@ -1343,6 +1370,12 @@ async def list_tasks(
|
|||||||
"run_timeout_seconds": task.run_timeout_seconds,
|
"run_timeout_seconds": task.run_timeout_seconds,
|
||||||
"notify_enabled": task.notify_enabled,
|
"notify_enabled": task.notify_enabled,
|
||||||
"notify_failures": task.notify_failures,
|
"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,
|
"next_run_at": task.next_run_at,
|
||||||
"last_run_at": task.last_run_at,
|
"last_run_at": task.last_run_at,
|
||||||
"last_status": task.last_status,
|
"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
|
from typing import Any, AsyncIterator, Dict, List, Optional, Sequence, Tuple
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from sqlalchemy import select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from tools.time_util import get_current_timestamp
|
||||||
|
|
||||||
from . import adapters, app_settings, service, video_link
|
from . import adapters, app_settings, service, video_link
|
||||||
from .models import MODE_NOTE, MonitorTarget, MonitorTask
|
from .models import MODE_NOTE, MonitorTarget, MonitorTask
|
||||||
|
|
||||||
@@ -64,6 +66,16 @@ VIDEO_CONCURRENCY = 6
|
|||||||
MAX_TARGETS = 1000
|
MAX_TARGETS = 1000
|
||||||
MAX_RANGE_DAYS = 31
|
MAX_RANGE_DAYS = 31
|
||||||
|
|
||||||
|
# 自动追加每次查询的窗口往回**多覆盖**一小时。数据中心对刚发布的作品有索引延迟:
|
||||||
|
# 卡在两次查询边界上的那一条,如果窗口首尾相接就会被漏掉。重叠部分靠去重消化。
|
||||||
|
SYNC_OVERLAP_SECONDS = 3600
|
||||||
|
# 一次自动追加最多处理这么多条。超过说明窗口开得太久(进程停过几天),先加能加的,
|
||||||
|
# 剩下的留到下一次 —— 这比整批拒绝、然后每 30 分钟重试一次要有用。
|
||||||
|
MAX_SYNC_VIDEOS = 500
|
||||||
|
# 自动追加失败后的重试间隔。不能用正常的间隔:接口挂一小时的话,等两小时才重试
|
||||||
|
# 意味着恢复后还要再等两小时。
|
||||||
|
SYNC_FAILURE_RETRY_MS = 30 * 60_000
|
||||||
|
|
||||||
# 中国没有夏令时,固定 +8 比 zoneinfo 稳 —— 镜像里不一定装了 tzdata。
|
# 中国没有夏令时,固定 +8 比 zoneinfo 稳 —— 镜像里不一定装了 tzdata。
|
||||||
CN_TZ = timezone(timedelta(hours=8))
|
CN_TZ = timezone(timedelta(hours=8))
|
||||||
|
|
||||||
@@ -446,6 +458,95 @@ def _aweme_ids(links: Sequence[str]) -> List[str]:
|
|||||||
return ids
|
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(
|
async def create_task(
|
||||||
session: AsyncSession,
|
session: AsyncSession,
|
||||||
links: Sequence[str],
|
links: Sequence[str],
|
||||||
|
|||||||
@@ -64,6 +64,9 @@ class MonitorTaskCreate(BaseModel):
|
|||||||
# 异常频率低且意味着任务已经停止工作(默认开,否则你会一直不知道)。
|
# 异常频率低且意味着任务已经停止工作(默认开,否则你会一直不知道)。
|
||||||
notify_enabled: bool = False
|
notify_enabled: bool = False
|
||||||
notify_failures: bool = True
|
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.
|
# Raw pasted values: full URLs or bare ids, in either form.
|
||||||
targets: List[str] = Field(min_length=1)
|
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)
|
run_timeout_seconds: Optional[int] = Field(default=None, ge=60, le=86400)
|
||||||
notify_enabled: Optional[bool] = None
|
notify_enabled: Optional[bool] = None
|
||||||
notify_failures: 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.
|
# When present, replaces the whole target list.
|
||||||
targets: Optional[List[str]] = None
|
targets: Optional[List[str]] = None
|
||||||
|
|
||||||
|
|||||||
@@ -420,3 +420,147 @@ class TestCreateTask:
|
|||||||
async def test_append_to_a_missing_task_is_rejected(self, session):
|
async def test_append_to_a_missing_task_is_rejected(self, session):
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
await superdir.append_task(session, 99999, [AWEME_A])
|
await superdir.append_task(session, 99999, [AWEME_A])
|
||||||
|
|
||||||
|
|
||||||
|
class TestAutoAppend:
|
||||||
|
"""每隔 N 分钟自动把新发布的作品补进同一个任务。"""
|
||||||
|
|
||||||
|
async def _task(self, session):
|
||||||
|
task, _ = await superdir.create_task(session, [AWEME_A], "自动追加")
|
||||||
|
return task
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _token(self, monkeypatch):
|
||||||
|
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
|
||||||
|
return "token"
|
||||||
|
|
||||||
|
monkeypatch.setattr(superdir, "get_token", fake_token)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_sync_appends_only_new_public_videos(self, session, monkeypatch):
|
||||||
|
task = await self._task(session)
|
||||||
|
task.superdir_auto_interval_minutes = 120
|
||||||
|
|
||||||
|
async def fake_fetch(token, client, start_ts, end_ts):
|
||||||
|
return [
|
||||||
|
_video(AWEME_A), # 已经在任务里
|
||||||
|
_video(AWEME_B), # 新的
|
||||||
|
_video(AWEME_C, video_status=2), # 私密,不收
|
||||||
|
]
|
||||||
|
|
||||||
|
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||||
|
|
||||||
|
result = await superdir.sync_task(session, task)
|
||||||
|
|
||||||
|
assert result == {"fetched": 2, "added": 1, "total": 2}
|
||||||
|
assert task.superdir_auto_last_added == 1
|
||||||
|
assert task.superdir_auto_last_error == ""
|
||||||
|
assert task.superdir_auto_last_at is not None
|
||||||
|
assert task.superdir_auto_next_at is not None
|
||||||
|
|
||||||
|
targets = list(
|
||||||
|
await session.scalars(
|
||||||
|
select(MonitorTarget).where(MonitorTarget.task_id == task.id)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert sorted(t.external_id for t in targets) == sorted([AWEME_A, AWEME_B])
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_the_same_window_twice_adds_nothing_the_second_time(
|
||||||
|
self, session, monkeypatch
|
||||||
|
):
|
||||||
|
task = await self._task(session)
|
||||||
|
|
||||||
|
async def fake_fetch(token, client, start_ts, end_ts):
|
||||||
|
return [_video(AWEME_A), _video(AWEME_B)]
|
||||||
|
|
||||||
|
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||||
|
|
||||||
|
await superdir.sync_task(session, task)
|
||||||
|
# 窗口重叠一小时是故意的(接口有索引延迟),重复的靠去重消化。
|
||||||
|
result = await superdir.sync_task(session, task)
|
||||||
|
|
||||||
|
assert result["added"] == 0
|
||||||
|
assert result["total"] == 2
|
||||||
|
assert task.superdir_auto_last_added == 0
|
||||||
|
assert task.superdir_auto_last_error == ""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_nothing_new_still_advances_the_clock(self, session, monkeypatch):
|
||||||
|
task = await self._task(session)
|
||||||
|
|
||||||
|
async def fake_fetch(token, client, start_ts, end_ts):
|
||||||
|
return []
|
||||||
|
|
||||||
|
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
|
||||||
|
result = await superdir.sync_task(session, task)
|
||||||
|
|
||||||
|
assert result["added"] == 0
|
||||||
|
assert result["total"] == 1
|
||||||
|
assert task.superdir_auto_last_error == ""
|
||||||
|
assert task.superdir_auto_last_at is not None
|
||||||
|
# 下一次在「这次成功」之后一个间隔,而不是更早。
|
||||||
|
assert (
|
||||||
|
task.superdir_auto_next_at
|
||||||
|
== task.superdir_auto_last_at + 120 * 60_000
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_failure_does_not_advance_the_watermark(self, session, monkeypatch):
|
||||||
|
"""接口挂了的时候 last_at 必须停住,否则恢复后那段时间的作品就漏了。"""
|
||||||
|
task = await self._task(session)
|
||||||
|
|
||||||
|
async def boom(token, client, start_ts, end_ts):
|
||||||
|
raise superdir.SuperDirError(500, "接口挂了")
|
||||||
|
|
||||||
|
monkeypatch.setattr(superdir, "_fetch_published", boom)
|
||||||
|
|
||||||
|
with pytest.raises(superdir.SuperDirError):
|
||||||
|
await superdir.sync_task(session, task)
|
||||||
|
|
||||||
|
assert task.superdir_auto_last_at is None
|
||||||
|
assert task.superdir_auto_last_added is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestAutoAppendScheduling:
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_enabling_schedules_the_first_check_immediately(self, session):
|
||||||
|
task, _ = await superdir.create_task(session, [AWEME_A], "自动")
|
||||||
|
|
||||||
|
await superdir.service.update_task(
|
||||||
|
session, task.id, {"superdir_auto_enabled": True}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert task.superdir_auto_enabled is True
|
||||||
|
assert task.superdir_auto_next_at is not None
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_disabling_clears_the_clock(self, session):
|
||||||
|
task, _ = await superdir.create_task(session, [AWEME_A], "自动")
|
||||||
|
await superdir.service.update_task(
|
||||||
|
session, task.id, {"superdir_auto_enabled": True}
|
||||||
|
)
|
||||||
|
|
||||||
|
await superdir.service.update_task(
|
||||||
|
session, task.id, {"superdir_auto_enabled": False}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert task.superdir_auto_enabled is False
|
||||||
|
assert task.superdir_auto_next_at is None
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_creator_task_cannot_enable_it(self, session):
|
||||||
|
task = await superdir.service.create_task(
|
||||||
|
session,
|
||||||
|
{
|
||||||
|
"name": "博主任务",
|
||||||
|
"platform": "dy",
|
||||||
|
"mode": "creator",
|
||||||
|
"targets": ["MS4wLjABAAAAsomebody"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
await superdir.service.update_task(
|
||||||
|
session, task.id, {"superdir_auto_enabled": True}
|
||||||
|
)
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import {
|
|||||||
} from '@/components/ui/select'
|
} from '@/components/ui/select'
|
||||||
import { useCreateTask, useSettings, useUpdateTask } from '@/hooks/useMonitor'
|
import { useCreateTask, useSettings, useUpdateTask } from '@/hooks/useMonitor'
|
||||||
import { useCurrentPlatform } from '@/hooks/usePlatform'
|
import { useCurrentPlatform } from '@/hooks/usePlatform'
|
||||||
import { describeSchedule } from '@/lib/monitorFormat'
|
import { describeSchedule, formatDateTime } from '@/lib/monitorFormat'
|
||||||
import type {
|
import type {
|
||||||
MonitorMode,
|
MonitorMode,
|
||||||
MonitorTask,
|
MonitorTask,
|
||||||
@@ -59,6 +59,18 @@ const SCHEDULE_MODE_OPTIONS: Array<{ value: ScheduleMode; label: string }> = [
|
|||||||
|
|
||||||
const HOURS = Array.from({ length: 24 }, (_, hour) => hour)
|
const HOURS = Array.from({ length: 24 }, (_, hour) => hour)
|
||||||
|
|
||||||
|
// 超级编导自动追加的检查频率。默认 2 小时 —— 分发作品陆续发布,查太勤只是多打
|
||||||
|
// 第三方接口,查太慢则新作品要等很久才进监控。
|
||||||
|
const SUPERDIR_INTERVAL_OPTIONS = [
|
||||||
|
{ value: '30', label: '30 分钟' },
|
||||||
|
{ value: '60', label: '1 小时' },
|
||||||
|
{ value: '120', label: '2 小时' },
|
||||||
|
{ value: '180', label: '3 小时' },
|
||||||
|
{ value: '360', label: '6 小时' },
|
||||||
|
{ value: '720', label: '12 小时' },
|
||||||
|
{ value: '1440', label: '1 天' },
|
||||||
|
]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Above this many works per run, warn about the request volume.
|
* Above this many works per run, warn about the request volume.
|
||||||
*
|
*
|
||||||
@@ -123,6 +135,8 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
|||||||
const [enableComments, setEnableComments] = useState(true)
|
const [enableComments, setEnableComments] = useState(true)
|
||||||
const [maxComments, setMaxComments] = useState('50')
|
const [maxComments, setMaxComments] = useState('50')
|
||||||
const [notifyEnabled, setNotifyEnabled] = useState(false)
|
const [notifyEnabled, setNotifyEnabled] = useState(false)
|
||||||
|
const [superdirAuto, setSuperdirAuto] = useState(false)
|
||||||
|
const [superdirInterval, setSuperdirInterval] = useState('120')
|
||||||
// 异常推送默认开:失败意味着这个任务从此默默采不到东西,而你不会知道。
|
// 异常推送默认开:失败意味着这个任务从此默默采不到东西,而你不会知道。
|
||||||
const [notifyFailures, setNotifyFailures] = useState(true)
|
const [notifyFailures, setNotifyFailures] = useState(true)
|
||||||
const [targets, setTargets] = useState('')
|
const [targets, setTargets] = useState('')
|
||||||
@@ -153,6 +167,8 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
|||||||
)
|
)
|
||||||
setNotifyEnabled(task?.notify_enabled ?? false)
|
setNotifyEnabled(task?.notify_enabled ?? false)
|
||||||
setNotifyFailures(task?.notify_failures ?? true)
|
setNotifyFailures(task?.notify_failures ?? true)
|
||||||
|
setSuperdirAuto(task?.superdir_auto_enabled ?? false)
|
||||||
|
setSuperdirInterval(String(task?.superdir_auto_interval_minutes ?? 120))
|
||||||
setTargets(task ? task.targets.map((t) => t.raw_value || t.external_id).join('\n') : '')
|
setTargets(task ? task.targets.map((t) => t.raw_value || t.external_id).join('\n') : '')
|
||||||
setAppendTargets('')
|
setAppendTargets('')
|
||||||
}, [open, task, settings])
|
}, [open, task, settings])
|
||||||
@@ -185,6 +201,8 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
|||||||
const clockIncomplete =
|
const clockIncomplete =
|
||||||
scheduleMode !== 'interval' &&
|
scheduleMode !== 'interval' &&
|
||||||
(scheduleHours.length === 0 || (scheduleMode === 'weekly' && scheduleDays.length === 0))
|
(scheduleHours.length === 0 || (scheduleMode === 'weekly' && scheduleDays.length === 0))
|
||||||
|
// 超级编导只接抖音分发,追加进去的又只能是作品 id —— 只有这一种任务能用。
|
||||||
|
const superdirEligible = platform === 'dy' && mode === 'note'
|
||||||
const canSubmit =
|
const canSubmit =
|
||||||
name.trim().length > 0 && mergedTargets.length > 0 && !pending && !clockIncomplete
|
name.trim().length > 0 && mergedTargets.length > 0 && !pending && !clockIncomplete
|
||||||
|
|
||||||
@@ -209,6 +227,9 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
|||||||
enabled: true,
|
enabled: true,
|
||||||
notify_enabled: notifyEnabled,
|
notify_enabled: notifyEnabled,
|
||||||
notify_failures: notifyFailures,
|
notify_failures: notifyFailures,
|
||||||
|
// 非抖音/作品模式时后端会拒绝,所以这里按平台和模式清掉,别让旧状态带上去。
|
||||||
|
superdir_auto_enabled: superdirEligible ? superdirAuto : false,
|
||||||
|
superdir_auto_interval_minutes: Number(superdirInterval),
|
||||||
targets: mergedTargets,
|
targets: mergedTargets,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -511,6 +532,69 @@ export function TaskEditorDialog({ open, onOpenChange, task }: TaskEditorDialogP
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{superdirEligible && (
|
||||||
|
<div className="rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/40 p-3 space-y-2">
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<Checkbox
|
||||||
|
id="superdir-auto"
|
||||||
|
checked={superdirAuto}
|
||||||
|
onCheckedChange={(checked) => setSuperdirAuto(checked === true)}
|
||||||
|
/>
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<label
|
||||||
|
htmlFor="superdir-auto"
|
||||||
|
className="text-xs font-mono text-cyber-text-primary cursor-pointer"
|
||||||
|
>
|
||||||
|
自动从超级编导追加新作品
|
||||||
|
</label>
|
||||||
|
<p className="text-[10px] font-mono text-cyber-text-muted leading-relaxed">
|
||||||
|
每隔一段时间查一次超级编导,把这段时间
|
||||||
|
<span className="text-cyber-text-secondary">新发布</span>
|
||||||
|
的作品自动加到本任务;已有的不会重复。需要先在「设置」里配好超级编导 Token。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{superdirAuto && (
|
||||||
|
<div className="flex flex-wrap items-center gap-2 pl-6">
|
||||||
|
<span className="text-[10px] font-mono text-cyber-text-secondary">
|
||||||
|
检查间隔
|
||||||
|
</span>
|
||||||
|
<Select value={superdirInterval} onValueChange={setSuperdirInterval}>
|
||||||
|
<SelectTrigger className="h-7 w-28 text-xs">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{SUPERDIR_INTERVAL_OPTIONS.map((option) => (
|
||||||
|
<SelectItem key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<span className="text-[10px] font-mono text-cyber-text-muted">
|
||||||
|
保存后立即检查一次,之后按间隔跑
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isEdit && task?.superdir_auto_enabled && (
|
||||||
|
<p className="pl-6 text-[10px] font-mono text-cyber-text-muted">
|
||||||
|
上次检查 {formatDateTime(task.superdir_auto_last_at)},新增{' '}
|
||||||
|
<span className="text-cyber-neon-cyan">
|
||||||
|
{task.superdir_auto_last_added ?? 0}
|
||||||
|
</span>{' '}
|
||||||
|
条
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{isEdit && task?.superdir_auto_last_error && (
|
||||||
|
<p className="pl-6 text-[10px] font-mono text-cyber-neon-pink">
|
||||||
|
上次失败:{task.superdir_auto_last_error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/40 p-3 space-y-3">
|
<div className="rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/40 p-3 space-y-3">
|
||||||
{/* 两类通知的性质完全不同,所以分成两个开关:
|
{/* 两类通知的性质完全不同,所以分成两个开关:
|
||||||
异常低频且意味着任务已经停止工作 —— 默认开;
|
异常低频且意味着任务已经停止工作 —— 默认开;
|
||||||
|
|||||||
@@ -60,6 +60,15 @@ export interface MonitorTask {
|
|||||||
notify_enabled: boolean
|
notify_enabled: boolean
|
||||||
/** 推送**异常**(登录失效/运行失败/没抓到数据)。默认开。 */
|
/** 推送**异常**(登录失效/运行失败/没抓到数据)。默认开。 */
|
||||||
notify_failures: boolean
|
notify_failures: boolean
|
||||||
|
/** 超级编导自动追加(只有抖音的作品模式任务能开)。 */
|
||||||
|
superdir_auto_enabled: boolean
|
||||||
|
superdir_auto_interval_minutes: number
|
||||||
|
/** 下一次自动追加的时间(毫秒);关掉时是 null。 */
|
||||||
|
superdir_auto_next_at: number | null
|
||||||
|
/** 上一次**成功**追加的时间(毫秒),也是下次查询的窗口起点。 */
|
||||||
|
superdir_auto_last_at: number | null
|
||||||
|
superdir_auto_last_added: number | null
|
||||||
|
superdir_auto_last_error: string
|
||||||
/** Epoch milliseconds. */
|
/** Epoch milliseconds. */
|
||||||
next_run_at: number | null
|
next_run_at: number | null
|
||||||
last_run_at: number | null
|
last_run_at: number | null
|
||||||
@@ -367,6 +376,8 @@ export interface TaskCreatePayload {
|
|||||||
enabled: boolean
|
enabled: boolean
|
||||||
notify_enabled: boolean
|
notify_enabled: boolean
|
||||||
notify_failures: boolean
|
notify_failures: boolean
|
||||||
|
superdir_auto_enabled: boolean
|
||||||
|
superdir_auto_interval_minutes: number
|
||||||
targets: string[]
|
targets: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user