feat(matrix): 「第一条视频」改成主页最早一条,后台翻页扫描 + 缓存
要的是这个博主**最早发的**那条(可能根本不在监控目标里),不是主页第一屏。 按游标翻到底才知道,所以: - 新增 monitor_creator_first_video 缓存表,按 sec_uid 存最早发布时间, 30 天内不再扫; - 调度器后台任务慢慢扫(每页 20 条、页间 0.5 秒、单次最多 50 页 / 3 分钟), 不占调度循环; - 矩阵只读缓存,读不到退回库里最早的一条作品; - 失败只锁 6 小时再试,不会把没扫到的号锁 30 天。 同时撤掉上一版「每轮采集多问一次主页最新视频」的实现(方向反了)。
This commit is contained in:
@@ -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}
|
||||
+43
-22
@@ -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(
|
||||
|
||||
@@ -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} 的资料里没有可用的身份标识,跳过账号指标")
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
)
|
||||
|
||||
+29
-4
@@ -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):
|
||||
"""给**作品**起的备注。
|
||||
|
||||
|
||||
@@ -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:
|
||||
"""到点的任务补一批超级编导新发布的作品。
|
||||
|
||||
|
||||
+38
-30
@@ -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": {"<hash>": {
|
||||
"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()
|
||||
|
||||
@@ -308,7 +308,7 @@
|
||||
<div class="wrap" id="wrap"></div>
|
||||
<div id="tip"></div>
|
||||
<div class="legend">
|
||||
<span><b>名字左边</b> = 粉丝数 / 主页总获赞 / 主页最新视频发布日期(可能不在监控目标里)</span>
|
||||
<span><b>名字左边</b> = 粉丝数 / 主页总获赞 / 主页最早一条视频的发布日期(可能不在监控目标里)</span>
|
||||
<span><b>赞 / 评</b> = 当天这些作品的点赞 / 评论</span>
|
||||
<span><b>左下角数字</b> = 当天作品条数</span>
|
||||
<span><b>悬停后点标题</b> = 在抖音打开这条作品</span>
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user