diff --git a/api/monitor/creator_scan.py b/api/monitor/creator_scan.py new file mode 100644 index 0000000..7dbb7cf --- /dev/null +++ b/api/monitor/creator_scan.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +"""扫博主主页,找出**最早一条视频**的发布时间。 + +抖音的作品列表按时间倒序、按游标翻页:要知道「这个号第一条视频是什么时候发的」, +只能一页页翻到最后一页。一个号几十上百条作品就是十几次请求,接口还时不时超时 —— +所以这件事不能放在采集主流程里,更不能放在矩阵页的请求里。做法是: + +* 扫一次存进 ``monitor_creator_first_video``,30 天内不再扫(老作品不会变); +* 由调度器在**后台任务**里慢慢扫,不占调度循环; +* 矩阵只读缓存,读不到就退回库里最早的一条作品。 + +翻到 ``MAX_PAGES`` 页还没到底(作品上千条)就带着已有结果收工,标记为不完整 —— +为了一个日期打几十次请求不划算,翻到的部分里最早那条已经足够接近。 +""" + +import asyncio +import time +from typing import Dict, List, Optional, Tuple + +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from tools.time_util import get_current_timestamp + +from . import adapters, douyin_api +from .db import get_session +from .models import ( + MonitorCreatorFirstVideo, + MonitorCreatorStat, + MonitorNote, + MonitorTask, +) + +PAGE_SIZE = 20 +# 最多翻 50 页 = 1000 条作品。 +MAX_PAGES = 50 +# 单个博主最多扫这么久;到点带着已有结果收工,标记不完整。 +MAX_SECONDS_PER_CREATOR = 180 +# 两次请求之间歇一下:主页接口不是我们的,连着打更容易被限流。 +REQUEST_GAP_SECONDS = 0.5 +# 扫到的值 30 天内复用。 +TTL_MS = 30 * 24 * 60 * 60_000 +# 失败之后多久重试(用把 checked_at 往前拨的方式表达)。 +RETRY_MS = 6 * 60 * 60_000 +# 一批最多处理多少个博主。调度器每个 tick 都来问一次,扫完了自然不再有 due。 +BATCH_SIZE = 20 + + +async def due_creators( + session: AsyncSession, + platform: str, + now: int, + limit: int = BATCH_SIZE, +) -> List[Tuple[str, str]]: + """需要(重新)扫的 ``(creator_hash, creator_id)``,最近活跃的优先。""" + task_ids = select(MonitorTask.id).where(MonitorTask.platform == platform) + + candidates: Dict[Tuple[str, str], int] = {} + note_rows = await session.execute( + select( + MonitorNote.creator_hash, + MonitorNote.creator_id, + func.max(MonitorNote.last_seen_at), + ) + .where(MonitorNote.task_id.in_(task_ids), MonitorNote.creator_id != "") + .group_by(MonitorNote.creator_hash, MonitorNote.creator_id) + ) + for creator_hash, creator_id, seen_at in note_rows.all(): + candidates[(creator_hash, creator_id)] = seen_at or 0 + + # 作品模式早期入库的笔记没有 creator_id,但快照里可能有 —— 两边都收进来。 + stat_rows = await session.execute( + select(MonitorCreatorStat.creator_hash, MonitorCreatorStat.creator_id) + .where( + MonitorCreatorStat.task_id.in_(task_ids), + MonitorCreatorStat.creator_id != "", + ) + .group_by(MonitorCreatorStat.creator_hash, MonitorCreatorStat.creator_id) + ) + for creator_hash, creator_id in stat_rows.all(): + candidates.setdefault((creator_hash, creator_id), 0) + + cached = { + row.creator_id: row + for row in await session.scalars( + select(MonitorCreatorFirstVideo).where( + MonitorCreatorFirstVideo.platform == platform + ) + ) + } + due = [ + key + for key in candidates + if key[1] not in cached + or now - (cached[key[1]].checked_at or 0) >= TTL_MS + ] + due.sort(key=lambda key: candidates[key], reverse=True) + return due[:limit] + + +async def _scan(creator_id: str) -> Tuple[Optional[int], int, bool]: + """从最新一页翻到最后一页,返回 ``(最早时间毫秒, 页数, 是否翻到底)``。""" + identity = await douyin_api.browser_identity() + cursor = 0 + oldest: Optional[int] = None + pages = 0 + complete = False + started = time.monotonic() + + while pages < MAX_PAGES: + videos, next_cursor, has_more = await douyin_api.author_videos_page( + creator_id, cursor, PAGE_SIZE, identity=identity + ) + pages += 1 + + stamps = [ + adapters.DY.to_ms(video.get("create_time")) for video in videos + ] + stamps = [stamp for stamp in stamps if stamp] + if stamps: + page_oldest = min(stamps) + oldest = page_oldest if oldest is None else min(oldest, page_oldest) + + if not has_more or not videos: + complete = True + break + # 游标不动就是到了尽头(接口偶尔 has_more 和游标对不上),别死循环。 + if not next_cursor or next_cursor == cursor: + break + cursor = next_cursor + + if time.monotonic() - started >= MAX_SECONDS_PER_CREATOR: + break + await asyncio.sleep(REQUEST_GAP_SECONDS) + + return oldest, pages, complete + + +async def scan_one( + session: AsyncSession, + platform: str, + creator_hash: str, + creator_id: str, + now: Optional[int] = None, +) -> bool: + """扫一个博主并写缓存。返回是否成功(失败也落一行,记录原因和下次重试时间)。""" + now = now or get_current_timestamp() + row = await session.scalar( + select(MonitorCreatorFirstVideo).where( + MonitorCreatorFirstVideo.platform == platform, + MonitorCreatorFirstVideo.creator_id == creator_id, + ) + ) + if row is None: + row = MonitorCreatorFirstVideo( + platform=platform, + creator_id=creator_id, + creator_hash=creator_hash, + checked_at=0, + ) + session.add(row) + + try: + oldest, pages, complete = await _scan(creator_id) + except Exception as exc: # noqa: BLE001 - 接口抖动不该炸掉整批 + row.creator_hash = creator_hash + row.error = str(exc)[:500] + # checked_at 往前拨,让这一行在 RETRY_MS 之后重新进入待扫队列; + # 不拨到 now 是因为那会把它锁 30 天。 + row.checked_at = now - TTL_MS + RETRY_MS + return False + + row.creator_hash = creator_hash + row.first_published_at = oldest + row.scanned_pages = pages + row.complete = complete + row.checked_at = now + row.error = "" + return True + + +async def refresh_batch( + platform: str = adapters.PLATFORM_DY, limit: int = BATCH_SIZE +) -> Dict[str, int]: + """扫一批到期的博主。由调度器的后台任务调用。""" + now = get_current_timestamp() + async with get_session() as session: + due = await due_creators(session, platform, now, limit) + + scanned = failed = 0 + for creator_hash, creator_id in due: + async with get_session() as session: + ok = await scan_one( + session, platform, creator_hash, creator_id, + now=get_current_timestamp(), + ) + if ok: + scanned += 1 + else: + failed += 1 + return {"due": len(due), "scanned": scanned, "failed": failed} diff --git a/api/monitor/douyin_api.py b/api/monitor/douyin_api.py index 55d68ae..05ceaeb 100644 --- a/api/monitor/douyin_api.py +++ b/api/monitor/douyin_api.py @@ -479,6 +479,46 @@ def normalize_aweme(aweme: Dict[str, Any]) -> Dict[str, Any]: } +async def author_videos_page( + sec_user_id: str, + max_cursor: int = 0, + count: int = MAX_PAGE_SIZE, + *, + cookie: str = "", + identity: Optional[BrowserIdentity] = None, +) -> Tuple[List[Dict[str, Any]], int, bool]: + """一页博主作品,返回 ``(作品, 下一页游标, 还有没有更多)``。 + + 翻页是**按时间游标**的(``max_cursor``),不是 offset —— 所以想拿「最早一条」 + 只能一页页翻到底,没有直接跳最后一页的办法(见 ``creator_scan``)。 + """ + # 身份池传进来的身份直接用 —— 不要再去读浏览器,那会把别的账号的 cookie 顶进来。 + identity = identity or await browser_identity(cookie) + if not _has_session(identity.cookie): + raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有") + + payload = await _get( + POSTS_PATH, + { + "sec_user_id": sec_user_id, + "count": max(1, min(count, MAX_PAGE_SIZE)), + "max_cursor": max_cursor, + "device_platform": "webapp", + "aid": 6383, + }, + identity, + ) + + awemes = payload.get("aweme_list") or [] + if not awemes and payload.get("status_code") not in (0, None): + raise DouyinApiError( + f"接口拒绝了请求(status_code={payload.get('status_code')})" + ) + next_cursor = _as_int(payload.get("max_cursor")) + has_more = bool(payload.get("has_more")) + return [normalize_aweme(aweme) for aweme in awemes], next_cursor, has_more + + async def author_videos( sec_user_id: str, count: int = MAX_PAGE_SIZE, @@ -491,29 +531,10 @@ async def author_videos( 用 ``sec_user_id`` 而不是数字 uid:监控任务里存的就是主页链接里的那段 sec_uid, 而且这个接口两种都收(爬虫那边用的也是 sec_user_id)。 """ - # 身份池传进来的身份直接用 —— 不要再去读浏览器,那会把别的账号的 cookie 顶进来。 - identity = identity or await browser_identity(cookie) - if not _has_session(identity.cookie): - raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有") - - payload = await _get( - POSTS_PATH, - { - "sec_user_id": sec_user_id, - "count": max(1, min(count, MAX_PAGE_SIZE)), - "max_cursor": 0, - "device_platform": "webapp", - "aid": 6383, - }, - identity, + videos, _cursor, _has_more = await author_videos_page( + sec_user_id, 0, count, cookie=cookie, identity=identity ) - - awemes = payload.get("aweme_list") or [] - if not awemes and payload.get("status_code") not in (0, None): - raise DouyinApiError( - f"接口拒绝了请求(status_code={payload.get('status_code')})" - ) - return [normalize_aweme(aweme) for aweme in awemes] + return videos async def video_detail( diff --git a/api/monitor/douyin_fetch.py b/api/monitor/douyin_fetch.py index d601a15..c6433c7 100644 --- a/api/monitor/douyin_fetch.py +++ b/api/monitor/douyin_fetch.py @@ -32,8 +32,6 @@ import asyncio import json from datetime import datetime - -import httpx from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Sequence @@ -209,37 +207,10 @@ async def _collect_batch( videos = [] # 作品详情里带着作者的粉丝/总获赞。作品模式**不会**单独问博主资料 —— # 不从这里收一份,这类任务(超级编导导入的都在这里)的博主粉丝数永远是空的。 - # - # 顺带问一次这个博主**主页上最新的视频**:它可能根本不在监控目标里(自然发的、 - # 别的活动发的),但「他最近还发不发」只能从主页看。同一轮里一个博主只问一次。 - latest_by_creator: Dict[str, Optional[int]] = {} for video in videos: profile = _profile_from_author(video) - creator_id = str(video.get("creator_id") or "") - latest: Optional[int] = None - if creator_id: - if creator_id not in latest_by_creator: - latest_by_creator[creator_id] = await _latest_video_at( - creator_id, cookie, identity - ) - latest = latest_by_creator[creator_id] - - if profile is None: - if latest is None: - continue - # 账号指标一个都没拿到,但知道了最新视频时间 —— 也值得落一条快照, - # 否则矩阵上这个号的「最新视频」永远是空的。 - profile = { - "creator_hash": str(video.get("creator_hash") or ""), - "creator_id": creator_id, - "nickname": str(video.get("nickname") or ""), - "fans": None, - "total_favorited": None, - "works": None, - "following": None, - } - profile["latest_published_at"] = latest - profiles.append(profile) + if profile is not None: + profiles.append(profile) else: videos = await _creator_works( external_id, @@ -315,37 +286,6 @@ def _profile_from_author(video: Dict[str, Any]) -> Optional[Dict[str, Any]]: } -async def _latest_video_at( - sec_user_id: str, cookie: str, identity: Any = None -) -> Optional[int]: - """博主主页第一条(最新)视频的发布时间(毫秒);拿不到返回 None。 - - 作品列表按发布时间倒序,只要最新那条,所以一次请求就够,不翻页。连接超时重试一次 - (容器到抖音的 TCP 连接偶尔会卡);其它错误直接放弃 —— 这是附加信息,不值得为一轮 - 采集增加更多失败面。 - """ - if not sec_user_id: - return None - try: - videos = await douyin_api.author_videos( - sec_user_id, count=1, cookie=cookie, identity=identity - ) - except httpx.TransportError: - await asyncio.sleep(1.0) - try: - videos = await douyin_api.author_videos( - sec_user_id, count=1, cookie=cookie, identity=identity - ) - except Exception: # noqa: BLE001 - 附加信息,失败就留空 - return None - except Exception: # noqa: BLE001 - return None - - stamps = [adapters.DY.to_ms(video.get("create_time")) for video in videos] - stamps = [stamp for stamp in stamps if stamp] - return max(stamps) if stamps else None - - async def _creator_profile( sec_user_id: str, videos: Sequence[Dict[str, Any]], @@ -371,11 +311,6 @@ async def _creator_profile( if videos: profile["creator_hash"] = videos[0].get("creator_hash") or profile["creator_hash"] - # 作品列表是倒序的,最早取到的这 N 条里最新的那条就是主页第一条。 - stamps = [adapters.DY.to_ms(video.get("create_time")) for video in videos] - stamps = [stamp for stamp in stamps if stamp] - if stamps: - profile["latest_published_at"] = max(stamps) if not profile.get("creator_hash"): # 哈希都算不出来的快照没人能查到,落下去只是垃圾。 errors.append(f"博主 {sec_user_id} 的资料里没有可用的身份标识,跳过账号指标") diff --git a/api/monitor/ingest.py b/api/monitor/ingest.py index 25c8538..2d1041a 100644 --- a/api/monitor/ingest.py +++ b/api/monitor/ingest.py @@ -718,7 +718,6 @@ async def _ingest_creator_stats( total_favorited=parse_count(record.get("total_favorited")), works_count=parse_count(record.get("works")), following=parse_count(record.get("following")), - latest_published_at=record.get("latest_published_at"), captured_at=now, ) ) diff --git a/api/monitor/models.py b/api/monitor/models.py index c9265ee..c435c5f 100644 --- a/api/monitor/models.py +++ b/api/monitor/models.py @@ -411,14 +411,39 @@ class MonitorCreatorStat(MonitorBase): total_favorited: Mapped[Optional[int]] = mapped_column(BigInteger) works_count: Mapped[Optional[int]] = mapped_column(BigInteger) following: Mapped[Optional[int]] = mapped_column(BigInteger) - # 这个博主**主页上最新一条视频**的发布时间(毫秒)。作品列表是按时间倒序的, - # 「第一条」就是最新那条 —— 它可能根本不在监控的目标里(自然发的、别的活动发的), - # 但能回答「他最近还发不发」。拿不到(接口挡了/超时)就留 None。 - latest_published_at: Mapped[Optional[int]] = mapped_column(BigInteger) captured_at: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True) +class MonitorCreatorFirstVideo(MonitorBase): + """博主主页**最早一条视频**的发布时间缓存。 + + 抖音的作品列表是按时间倒序、按游标翻页的 —— 想知道「这个号第一条视频是什么时候 + 发的」,只能一页页翻到最后一页(几十上百条作品 = 十几次请求),而且接口时不时超时。 + 所以扫一次、存下来,30 天内不再扫:老作品不会变,这个值几乎是个常量。 + + 矩阵页只读这张表,不在这里发任何请求。 + """ + + __tablename__ = "monitor_creator_first_video" + __table_args__ = ( + UniqueConstraint("platform", "creator_id", name="uq_creator_first_video"), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + platform: Mapped[str] = mapped_column(String(16), nullable=False, index=True) + # 主页 id(抖音是 sec_uid)。哈希是单向的,查不了主页。 + creator_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True) + creator_hash: Mapped[str] = mapped_column(String(64), nullable=False, default="") + # 毫秒。**没扫到时留 NULL**,界面上退回「库里最早的一条作品」。 + first_published_at: Mapped[Optional[int]] = mapped_column(BigInteger) + scanned_pages: Mapped[int] = mapped_column(Integer, nullable=False, default=0) + # 是否翻到了最后一页。到了上限(作品特别多)时为 False,值只是「翻到的部分里最早的」。 + complete: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) + checked_at: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0, index=True) + error: Mapped[str] = mapped_column(String(500), nullable=False, default="") + + class MonitorNoteAlias(MonitorBase): """给**作品**起的备注。 diff --git a/api/monitor/scheduler.py b/api/monitor/scheduler.py index d073854..ea34ca7 100644 --- a/api/monitor/scheduler.py +++ b/api/monitor/scheduler.py @@ -49,7 +49,7 @@ from sqlalchemy import or_, select from tools.time_util import get_current_timestamp from ..services import crawler_manager -from . import adapters, app_settings, schedule, superdir, upstream +from . import adapters, app_settings, creator_scan, schedule, superdir, upstream from .db import get_session from .models import ( MODE_NOTE, @@ -147,6 +147,8 @@ class MonitorScheduler: # 正在跑的采集(task_id -> asyncio.Task)。**必须留强引用**,否则任务可能被 # GC 回收;顺带让测试和停机可以等它们结束。 self._running_tasks: dict[int, asyncio.Task] = {} + # 扫「最早一条视频」的后台任务。慢、且不急,单飞即可。 + self._first_video_task: Optional[asyncio.Task] = None async def start(self) -> None: if self._loop_task is not None and not self._loop_task.done(): @@ -197,8 +199,30 @@ class MonitorScheduler: await self._maybe_sync_superdir() except Exception as exc: # pragma: no cover - keep the loop alive print(f"[monitor.scheduler] 超级编导自动追加失败: {exc}") + # 扫博主主页「最早一条视频」。慢且不紧急,后台慢慢来。 + try: + await self._maybe_scan_first_videos() + 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_scan_first_videos(self) -> None: + if self._first_video_task is not None and not self._first_video_task.done(): + return + self._first_video_task = asyncio.create_task(self._scan_first_videos()) + + async def _scan_first_videos(self) -> None: + try: + result = await creator_scan.refresh_batch(adapters.PLATFORM_DY) + except Exception as exc: # pragma: no cover - keep the loop alive + print(f"[monitor.scheduler] 扫描最早视频失败: {exc}") + return + if result.get("scanned") or result.get("failed"): + print( + f"[monitor.scheduler] 最早视频扫描:" + f"到期 {result['due']},成功 {result['scanned']},失败 {result['failed']}" + ) + async def _maybe_sync_superdir(self) -> None: """到点的任务补一批超级编导新发布的作品。 diff --git a/api/monitor/service.py b/api/monitor/service.py index d4496b8..aac920e 100644 --- a/api/monitor/service.py +++ b/api/monitor/service.py @@ -40,6 +40,7 @@ from .models import ( MODE_NOTE, MonitorComment, MonitorCreatorAlias, + MonitorCreatorFirstVideo, MonitorCreatorStat, MonitorEvent, MonitorNote, @@ -1580,7 +1581,7 @@ async def daily_tag_matrix( {"dates": ["2026-10-21", ...], # 新到旧 "creators": [{"hash": ..., "name": ..., "fans": 1200, "total_favorited": 83000, - "latest_published_at": 1780000000000}], # 按昵称排序 + "first_published_at": 1780000000000}], # 按昵称排序 "cells": {"2026-10-21": {"": { "count": 2, "tags": ["大字报", "养号"], "likes": 120, "comments": 8, "collected": 30, "shares": 4, @@ -1636,6 +1637,7 @@ async def daily_tag_matrix( MonitorNote.title, MonitorNote.note_url, MonitorNote.creator_hash, + MonitorNote.creator_id, MonitorNote.creator_name, MonitorNote.published_at, ) @@ -1700,11 +1702,11 @@ async def daily_tag_matrix( await session.execute( select( MonitorCreatorStat.creator_hash, + MonitorCreatorStat.creator_id, MonitorCreatorStat.nickname, MonitorCreatorStat.captured_at, MonitorCreatorStat.fans, MonitorCreatorStat.total_favorited, - MonitorCreatorStat.latest_published_at, ).where( MonitorCreatorStat.task_id.in_(task_ids), MonitorCreatorStat.creator_hash != "", @@ -1717,9 +1719,11 @@ async def daily_tag_matrix( latest_fans: Dict[str, tuple] = {} # 主页上的「获赞总数」,和粉丝数一样取最近一次读到的值。 latest_likes: Dict[str, tuple] = {} - # 主页第一条(最新)视频的发布时间。采集时问过主页,这条可能不在监控目标里。 - latest_video: Dict[str, tuple] = {} + # 哈希 -> 主页 id。矩阵要查「最早一条视频」的缓存,缓存是按 sec_uid 存的。 + creator_ids: Dict[str, str] = {} for stat in stat_rows: + if stat.creator_id: + creator_ids.setdefault(stat.creator_hash, stat.creator_id) if stat.fans is not None: current_fans = latest_fans.get(stat.creator_hash) if current_fans is None or stat.captured_at > current_fans[1]: @@ -1731,13 +1735,6 @@ async def daily_tag_matrix( stat.total_favorited, stat.captured_at, ) - if stat.latest_published_at is not None: - current_video = latest_video.get(stat.creator_hash) - if current_video is None or stat.captured_at > current_video[1]: - latest_video[stat.creator_hash] = ( - stat.latest_published_at, - stat.captured_at, - ) # **空昵称不算名字。** 资料接口偶尔会回一个空对象(昵称、sec_uid、粉丝、 # 作品数全空),如果把这一轮当最新快照,就会用一个空字符串把之前的好名字 # 盖掉,界面上变成「未知(hash)」。实测线上有两个号就是这么丢的名字。 @@ -1750,6 +1747,8 @@ async def daily_tag_matrix( known: Dict[str, str] = {} for row in notes: key = row.creator_hash or f"note:{row.note_id}" + if row.creator_id and row.creator_hash: + creator_ids.setdefault(row.creator_hash, row.creator_id) if row.creator_name: known[key] = row.creator_name else: @@ -1824,11 +1823,12 @@ async def daily_tag_matrix( # 作品是按发布时间倒序取回来的,明细按时间正序更好读(1、2、3…)。 bucket["details"].reverse() - # 兜底:库里这个博主**已有作品里最新的**发布时间。首选是采集时从主页拿到的 - # 「第一条视频」(它可能根本不在监控目标里),主页那次没问到时才用它。 - tracked_rows = ( + # 「最早一条视频」:首选缓存表(后台把这个博主的作品列表翻到底扫出来的,可能根本 + # 不在监控目标里);没扫到就退回库里**最早**的一条作品 —— 后者只覆盖被监控的那些 + # 链接,但总比空着强。 + first_rows = ( await session.execute( - select(MonitorNote.creator_hash, func.max(MonitorNote.published_at)) + select(MonitorNote.creator_hash, func.min(MonitorNote.published_at)) .where( MonitorNote.task_id.in_(task_ids), MonitorNote.published_at.is_not(None), @@ -1837,12 +1837,29 @@ async def daily_tag_matrix( .group_by(MonitorNote.creator_hash) ) ).all() - latest_tracked: Dict[str, int] = { - creator_hash: latest_at - for creator_hash, latest_at in tracked_rows - if latest_at + tracked_first: Dict[str, int] = { + creator_hash: first_at for creator_hash, first_at in first_rows if first_at } + sec_uids = {value for value in creator_ids.values() if value} + scanned: Dict[str, int] = {} + if sec_uids: + scanned_rows = await session.execute( + select( + MonitorCreatorFirstVideo.creator_id, + MonitorCreatorFirstVideo.first_published_at, + ).where( + MonitorCreatorFirstVideo.platform == platform, + MonitorCreatorFirstVideo.creator_id.in_(sec_uids), + MonitorCreatorFirstVideo.first_published_at.is_not(None), + ) + ) + scanned = { + creator_id: first_at + for creator_id, first_at in scanned_rows.all() + if first_at + } + creators = [ { "hash": hash_, @@ -1851,17 +1868,8 @@ async def daily_tag_matrix( # 前端据此不画那个数字,而不是显示 0。 "fans": latest_fans.get(hash_, (None, 0))[0], "total_favorited": latest_likes.get(hash_, (None, 0))[0], - # 两个来源取较新的一个:主页数据可能比库里的作品旧(快照是上一轮的)。 - "latest_published_at": max( - [ - value - for value in ( - latest_video.get(hash_, (None, 0))[0], - latest_tracked.get(hash_), - ) - if value - ], - default=None, + "first_published_at": ( + scanned.get(creator_ids.get(hash_) or "") or tracked_first.get(hash_) ), } for hash_, name in known.items() diff --git a/api/reports/matrix.html b/api/reports/matrix.html index 9db7e29..afcec20 100644 --- a/api/reports/matrix.html +++ b/api/reports/matrix.html @@ -308,7 +308,7 @@
- 名字左边 = 粉丝数 / 主页总获赞 / 主页最新视频发布日期(可能不在监控目标里) + 名字左边 = 粉丝数 / 主页总获赞 / 主页最早一条视频的发布日期(可能不在监控目标里) 赞 / 评 = 当天这些作品的点赞 / 评论 左下角数字 = 当天作品条数 悬停后点标题 = 在抖音打开这条作品 @@ -612,7 +612,7 @@ const fansKnown = creator.fans !== null && creator.fans !== undefined; const likesKnown = creator.total_favorited !== null && creator.total_favorited !== undefined; - const firstAt = creator.latest_published_at; + const firstAt = creator.first_published_at; const titleParts = []; if (fansKnown) { const fans = document.createElement('span'); @@ -637,9 +637,9 @@ first.className = 'first'; first.textContent = parts.date; first.title = - '主页第一条(最新)视频发布于 ' + parts.date + ' ' + parts.time; + '主页最早一条视频发布于 ' + parts.date + ' ' + parts.time; th.appendChild(first); - titleParts.push('最新视频 ' + parts.date); + titleParts.push('最早视频 ' + parts.date); } const nameSpan = document.createElement('span'); nameSpan.textContent = label; diff --git a/tests/test_douyin_fetch.py b/tests/test_douyin_fetch.py index 1946d01..10ff667 100644 --- a/tests/test_douyin_fetch.py +++ b/tests/test_douyin_fetch.py @@ -178,18 +178,13 @@ class TestNoteMode: 「粘贴作品链接的监控」今天本来是能用的,别让它因为这一处走错而废掉。 """ - async def only_by_creator_id(sec_user_id, count=20, *, cookie="", identity=None): - # 可以为了「主页最新视频」问一次作品列表,但**只能用详情里的 sec_uid 问**, - # 不能拿作品目标 id 去当 sec_uid —— 那必然失败,而且报错很难看懂。 - assert sec_user_id == "MS4wLjABAAAAtestsecuid" - return [] + async def must_not_be_called(*args, **kwargs): + raise AssertionError("作品模式不该去拉博主的作品列表") async def fake_detail(aweme_id, *, cookie="", identity=None): - record = _video(aweme_id) - record["creator_id"] = "MS4wLjABAAAAtestsecuid" - return record + return _video(aweme_id) - monkeypatch.setattr(douyin_api, "author_videos", only_by_creator_id) + monkeypatch.setattr(douyin_api, "author_videos", must_not_be_called) monkeypatch.setattr(douyin_api, "video_detail", fake_detail) result = await _collect( @@ -263,33 +258,6 @@ class TestNoteMode: # 详情里没有作品总数,留 None 而不是 0。 assert profiles[0]["works"] is None - @pytest.mark.asyncio - async def test_the_latest_video_time_comes_from_the_profile(self, monkeypatch, tmp_path): - """主页第一条视频可能不在监控目标里 —— 单独问一次,用它的发布时间。""" - - async def fake_detail(aweme_id, *, cookie="", identity=None): - record = _video(aweme_id) - record.update( - {"creator_id": "MS4wLjABAAAAtestsecuid", "creator_fans": 10} - ) - return record - - async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): - assert sec_user_id == "MS4wLjABAAAAtestsecuid" - return [{"create_time": 1793000000}] - - monkeypatch.setattr(douyin_api, "video_detail", fake_detail) - monkeypatch.setattr(douyin_api, "author_videos", fake_videos) - - await _collect( - tmp_path, mode="note", want_comments=False, targets=[_Target("111")] - ) - - profiles = _read( - list((tmp_path / "douyin" / "jsonl").glob("*_profile_*.jsonl"))[0] - ) - assert profiles[0]["latest_published_at"] == 1793000000 * 1000 - @pytest.mark.asyncio async def test_no_stats_means_no_profile_row(self, monkeypatch, tmp_path): """精简版 author(字段全缺)不该写一条全 NULL 的快照。""" @@ -420,10 +388,7 @@ class TestCreatorProfile: await _collect(tmp_path, want_comments=False) - profile = self._profiles(tmp_path)[0] - # 作品列表里的最新一条也带出来了(秒 -> 毫秒)。 - assert profile.pop("latest_published_at") == 1790574515 * 1000 - assert profile == _profile() + assert self._profiles(tmp_path) == [_profile()] @pytest.mark.asyncio async def test_the_profile_is_keyed_by_the_same_hash_as_the_works( diff --git a/tests/test_monitor_creator_scan.py b/tests/test_monitor_creator_scan.py new file mode 100644 index 0000000..77c0363 --- /dev/null +++ b/tests/test_monitor_creator_scan.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +"""主页「最早一条视频」的扫描:翻页、取最小值、缓存与失败重试。""" + +import pytest +import pytest_asyncio +from sqlalchemy import select + +from api.monitor import creator_scan, db as monitor_db, douyin_api +from api.monitor.models import MonitorCreatorFirstVideo +from tools.time_util import get_current_timestamp + + +@pytest_asyncio.fixture +async def session(tmp_path): + monitor_db.set_sqlite_path(tmp_path / "scan.db") + await monitor_db.init_db() + async with monitor_db.get_session() as db_session: + yield db_session + await monitor_db.dispose_engine() + + +@pytest.fixture(autouse=True) +def _fast(monkeypatch): + monkeypatch.setattr(creator_scan, "REQUEST_GAP_SECONDS", 0) + + async def fake_identity(cookie="", force=False): + return None + + monkeypatch.setattr(douyin_api, "browser_identity", fake_identity) + + +class TestScan: + @pytest.mark.asyncio + async def test_pages_to_the_end_and_takes_the_oldest(self, monkeypatch): + pages = { + 0: ([{"create_time": 1793000000}, {"create_time": 1792000000}], 100, True), + 100: ([{"create_time": 1700000000}], 50, True), + 50: ([{"create_time": 1600000000}], 0, False), + } + + async def fake_page(sec_user_id, max_cursor=0, count=20, *, cookie="", identity=None): + return pages[max_cursor] + + monkeypatch.setattr(douyin_api, "author_videos_page", fake_page) + + oldest, page_count, complete = await creator_scan._scan("MS4w-sec") + + assert oldest == 1600000000 * 1000 + assert page_count == 3 + assert complete is True + + @pytest.mark.asyncio + async def test_an_unchanging_cursor_does_not_loop_forever(self, monkeypatch): + async def fake_page(sec_user_id, max_cursor=0, count=20, *, cookie="", identity=None): + return [{"create_time": 1600000000}], 7, True + + monkeypatch.setattr(douyin_api, "author_videos_page", fake_page) + + _oldest, page_count, complete = await creator_scan._scan("MS4w-sec") + + assert page_count == 2 + assert complete is False + + +class TestCache: + @pytest.mark.asyncio + async def test_a_successful_scan_is_written_to_the_cache(self, session, monkeypatch): + async def fake_scan(creator_id): + return 1700000000000, 4, True + + monkeypatch.setattr(creator_scan, "_scan", fake_scan) + + ok = await creator_scan.scan_one(session, "dy", "hash-a", "MS4w-sec") + + assert ok is True + row = await session.scalar( + select(MonitorCreatorFirstVideo).where( + MonitorCreatorFirstVideo.creator_id == "MS4w-sec" + ) + ) + assert row.first_published_at == 1700000000000 + assert row.scanned_pages == 4 + assert row.complete is True + assert row.error == "" + + @pytest.mark.asyncio + async def test_a_failure_is_recorded_and_retried_after_a_while( + self, session, monkeypatch + ): + async def boom(creator_id): + raise douyin_api.DouyinApiError("接口超时") + + monkeypatch.setattr(creator_scan, "_scan", boom) + now = get_current_timestamp() + + ok = await creator_scan.scan_one( + session, "dy", "hash-a", "MS4w-sec", now=now + ) + + assert ok is False + row = await session.scalar( + select(MonitorCreatorFirstVideo).where( + MonitorCreatorFirstVideo.creator_id == "MS4w-sec" + ) + ) + assert "接口超时" in row.error + assert row.first_published_at is None + # checked_at 往前拨:大约 6 小时后就重新到期,而不是锁 30 天。 + assert row.checked_at == now - creator_scan.TTL_MS + creator_scan.RETRY_MS diff --git a/tests/test_monitor_matrix.py b/tests/test_monitor_matrix.py index ca147a5..bdcc880 100644 --- a/tests/test_monitor_matrix.py +++ b/tests/test_monitor_matrix.py @@ -21,6 +21,7 @@ from api.monitor import db as monitor_db from api.monitor import service from api.monitor.models import ( MODE_CREATOR, + MonitorCreatorFirstVideo, MonitorCreatorStat, MonitorNote, MonitorNoteMetric, @@ -263,7 +264,7 @@ async def _stat( run_id: int = 1, fans: int | None = None, total_favorited: int | None = None, - latest_published_at: int | None = None, + creator_id: str = "", ) -> None: async with monitor_db.get_session() as session: session.add( @@ -272,16 +273,36 @@ async def _stat( run_id=run_id, creator_hash=creator_hash, nickname=nickname, - creator_id="", + creator_id=creator_id, works_count=0, fans=fans, total_favorited=total_favorited, - latest_published_at=latest_published_at, captured_at=captured_at or get_current_timestamp(), ) ) +async def _first_video( + platform: str, + creator_id: str, + first_at: int | None, + creator_hash: str = "hash-a", +) -> None: + async with monitor_db.get_session() as session: + session.add( + MonitorCreatorFirstVideo( + platform=platform, + creator_id=creator_id, + creator_hash=creator_hash, + first_published_at=first_at, + scanned_pages=3, + complete=True, + checked_at=get_current_timestamp(), + error="", + ) + ) + + @pytest.mark.asyncio async def test_creators_without_notes_still_get_a_row(db): """只在账号快照里出现的号不能消失。 @@ -342,46 +363,44 @@ async def test_the_creator_row_carries_the_total_likes_from_the_profile(db): @pytest.mark.asyncio -async def test_the_latest_video_date_comes_from_the_profile(db): - """主页第一条视频可能根本不在监控目标里 —— 采集时单独问过,就用它。""" +async def test_the_first_video_date_comes_from_the_scan_cache(db): + """后台扫过主页就把最早那条的日期存下来 —— 它可能根本不在监控目标里。""" task_id = await _task() - now = get_current_timestamp() - 1000 - tracked = now - 3 * DAY_MS - profile_latest = now - 60_000 - await _note(task_id, "n1", "博主A", tracked) - await _stat( - task_id, "hash-a", "博主A", latest_published_at=profile_latest - ) + sec = "MS4wLjABAAAAsecuid" + scanned_first = get_current_timestamp() - 300 * DAY_MS + await _stat(task_id, "hash-a", "博主A", creator_id=sec) + await _first_video("dy", sec, scanned_first) async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) - assert data["creators"][0]["latest_published_at"] == profile_latest + assert data["creators"][0]["first_published_at"] == scanned_first @pytest.mark.asyncio -async def test_it_falls_back_to_the_newest_tracked_note(db): - """主页那次没问到(接口挡了/超时)时,退到库里最新的一条作品。""" +async def test_it_falls_back_to_the_earliest_tracked_note(db): + """还没扫到主页时,退到库里**最早**的一条作品。""" task_id = await _task() now = get_current_timestamp() - 1000 - await _note(task_id, "old", "博主A", now - 400 * DAY_MS) + first = now - 400 * DAY_MS + await _note(task_id, "old", "博主A", first) await _note(task_id, "new", "博主A", now) async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) - assert data["creators"][0]["latest_published_at"] == now + assert data["creators"][0]["first_published_at"] == first @pytest.mark.asyncio -async def test_a_creator_without_works_has_no_latest_video_date(db): +async def test_a_creator_without_works_has_no_first_video_date(db): task_id = await _task() await _stat(task_id, "hash-a", "博主A", fans=10) async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) - assert data["creators"][0]["latest_published_at"] is None + assert data["creators"][0]["first_published_at"] is None @pytest.mark.asyncio