之前取的是本任务已有作品里**最早**的那条 —— 既不是主页上看到的第一条, 也只看得到被监控的那批链接。现在采集时对每个博主额外问一次作品列表 (倒序,只要第一条),把它的发布时间落进账号快照;矩阵优先用它,没问到 时退回库里最新的一条作品。 - 作品模式:每个博主每轮一次请求,同轮内去重;连接超时重试一次。 - 博主模式:本来就在拉作品列表,直接用其中的最新时间。 - 新列 monitor_creator_stat.latest_published_at(毫秒,可空)。
1885 lines
75 KiB
Python
1885 lines
75 KiB
Python
# -*- coding: utf-8 -*-
|
||
# Copyright (c) 2025 [email protected]
|
||
#
|
||
# This file is part of MediaCrawler project.
|
||
# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/api/monitor/service.py
|
||
# GitHub: https://github.com/NanmiCoder
|
||
# Non-commercial learning license 1.1
|
||
#
|
||
# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则:
|
||
# 1. 不得用于任何商业用途。
|
||
# 2. 使用时应遵守目标平台的使用条款和robots.txt规则。
|
||
# 3. 不得进行大规模爬取或对平台造成运营干扰。
|
||
# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。
|
||
# 5. 不得用于任何非法或不当的用途。
|
||
#
|
||
# 详细许可条款请参阅项目根目录下的LICENSE文件。
|
||
# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。
|
||
|
||
"""Task CRUD and dashboard queries for the monitoring layer."""
|
||
|
||
import asyncio
|
||
import os
|
||
import re
|
||
import time
|
||
from datetime import datetime, timedelta
|
||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||
from urllib.parse import parse_qs, urlparse
|
||
|
||
import httpx
|
||
from sqlalchemy import delete, func, select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from tools.time_util import get_current_timestamp
|
||
|
||
from . import adapters, app_settings, covers, platforms, schedule
|
||
from .db import get_session
|
||
from .platforms import PLATFORM_XHS
|
||
from .models import (
|
||
MODE_CREATOR,
|
||
MODE_NOTE,
|
||
MonitorComment,
|
||
MonitorCreatorAlias,
|
||
MonitorCreatorStat,
|
||
MonitorEvent,
|
||
MonitorNote,
|
||
MonitorNoteAlias,
|
||
MonitorNoteMetric,
|
||
MonitorNoteTag,
|
||
MonitorTag,
|
||
MonitorRun,
|
||
MonitorTarget,
|
||
MonitorTask,
|
||
RUN_SUCCESS,
|
||
RUN_PARTIAL,
|
||
)
|
||
from .runner import execute_task
|
||
from .tagrules import split_keywords
|
||
|
||
# Keep strong references to in-flight manual runs; asyncio only holds weak ones,
|
||
# so without this a run can be garbage collected mid-flight.
|
||
_background_runs: set[asyncio.Task] = set()
|
||
|
||
MIN_INTERVAL_MINUTES = 30
|
||
MAX_INTERVAL_MINUTES = 7 * 24 * 60
|
||
|
||
# Changing any of these invalidates the pending run slot.
|
||
SCHEDULE_FIELDS = {
|
||
"interval_minutes",
|
||
"schedule_mode",
|
||
"schedule_hours",
|
||
"schedule_days",
|
||
"schedule_minute",
|
||
}
|
||
|
||
|
||
def _require_clock_fields(mode: str, hours: list, days: list) -> None:
|
||
"""A clock schedule with no clock time can never fire.
|
||
|
||
The create schema already rejects that shape, but the update path merges
|
||
partial fields and therefore has no schema-level view of the result -- so the
|
||
check lives here, where both paths meet.
|
||
"""
|
||
if mode in schedule.CLOCK_MODES and not hours:
|
||
raise ValueError("按钟点调度至少要选一个时间")
|
||
if mode == schedule.MODE_WEEKLY and not days:
|
||
raise ValueError("按周调度至少要选一个星期")
|
||
|
||
# 各平台的链接形态、id 形状、短链域名都在 adapters.py —— 那里是「平台之间不一样」
|
||
# 的东西的唯一出处,所以这里不再留任何平台字面量。
|
||
|
||
|
||
class TargetParseError(ValueError):
|
||
"""Raised when a pasted monitoring target cannot be understood."""
|
||
|
||
|
||
# 短链跳转的两个参数。超时给得短:这是**保存任务**的路上,用户在等,
|
||
# 一个卡住的跳转不该把「新建任务」这个动作拖成十几秒。
|
||
SHORT_LINK_TIMEOUT_SECONDS = 8.0
|
||
_SHORT_LINK_UA = (
|
||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||
"(KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
|
||
)
|
||
|
||
|
||
async def expand_short_link(value: str, platform: str) -> str:
|
||
"""把分享短链换成它指向的完整地址;不是短链、或者解不出来就**原样返回**。
|
||
|
||
做法是发一个 **GET 且不跟随跳转**,直接读第一个 ``Location``:
|
||
|
||
* 小红书分享出来的 ``xhslink.cn/o/xxx`` —— 第一个 Location 就是
|
||
``xiaohongshu.com/user/profile/<id>?xsec_token=...&xsec_source=...``,
|
||
要的东西全在里面。**跟到底反而会丢**:它会一路跳到登录页。
|
||
* 抖音的 ``v.douyin.com/xxx`` 同样是 302 + Location。**码不存在时会跳到首页**,
|
||
那就解不出 id —— 于是落回原值。
|
||
|
||
解不出来时返回原值、**不报错**:链接校验已经按用户要求关掉了(粘什么都收得下),
|
||
这里再造一个新的拒绝点就自相矛盾。代价是那个目标抓不到东西,但 ingest 会把这种
|
||
「长得像 URL 的目标」认出来并直说,不静默。
|
||
"""
|
||
raw = (value or "").strip()
|
||
if not raw.startswith("http") or not adapters.has_adapter(platform):
|
||
return value
|
||
|
||
if not any(host in raw for host in adapters.adapter(platform).short_link_hosts):
|
||
return value
|
||
|
||
try:
|
||
async with httpx.AsyncClient(timeout=SHORT_LINK_TIMEOUT_SECONDS) as client:
|
||
response = await client.get(
|
||
raw,
|
||
headers={"User-Agent": _SHORT_LINK_UA},
|
||
follow_redirects=False,
|
||
)
|
||
except httpx.HTTPError as exc:
|
||
print(f"[monitor.target] 短链解析失败,保持原值:{exc}")
|
||
return value
|
||
|
||
return response.headers.get("location") or value
|
||
|
||
|
||
async def prepare_target(
|
||
value: str, mode: str, platform: str = PLATFORM_XHS
|
||
) -> Dict[str, str]:
|
||
"""保存目标前的完整处理:**先解短链,再解析**。
|
||
|
||
短链只能在这里解 —— ``parse_target_input`` 是纯函数、不联网,它拿到
|
||
``https://xhslink.cn/o/xxx`` 只能原样存下来,而那会变成一个永远抓不到东西的目标。
|
||
"""
|
||
parsed = parse_target_input(await expand_short_link(value, platform), mode, platform)
|
||
# ``raw_value`` 记的必须是**用户当初粘的那串**(也就是短链原文),不是解开之后的地址:
|
||
# 那是解错目标时唯一能回溯「他到底粘了什么」的东西。id / token 那几项才用解开的。
|
||
parsed["raw_value"] = (value or "").strip()
|
||
return parsed
|
||
|
||
|
||
def parse_target_input(
|
||
value: str, mode: str, platform: str = PLATFORM_XHS
|
||
) -> Dict[str, str]:
|
||
"""Parse a pasted creator/note value into a stable id plus a refreshable token.
|
||
|
||
Accepts either a full URL (with or without ``xsec_token``) or a bare id.
|
||
Storing the id separately from the token is what keeps a long-running task
|
||
alive: tokens expire, ids do not.
|
||
|
||
**认不出来的一律原样存下,不报错。**(2026-10-12 按用户要求关掉了链路校验。)
|
||
以前这里是白名单:链接不匹配平台的形状就拒收。问题是平台一改链接形状,用户粘一个
|
||
完全正确的链接也只能干瞪眼 —— 而拒收换来的那点保护,代价是「任务建不出来」。
|
||
|
||
现在只保留两件不能省的事:
|
||
|
||
* **空值仍然拒收** —— 空目标连库都写不进去;
|
||
* **不许跨平台误抠** —— 小红书的正则不会从抖音链接里抠出一个 id 来。那会造出一个
|
||
**看起来正常但完全错误**的目标,比原样存下来糟得多。
|
||
|
||
平台没有适配器仍然拒收:那不是校验链接,是「这个平台我们根本采不了」。
|
||
|
||
代价(已知并接受):认不出的值会变成一个永远抓不到东西的目标。好在那不会静默 ——
|
||
跑完一轮 ingest 就会发现「一条都没抓到」并报出来。
|
||
"""
|
||
if not adapters.has_adapter(platform):
|
||
raise TargetParseError(f"暂不支持解析该平台({platform})的目标链接")
|
||
spec = adapters.adapter(platform)
|
||
|
||
raw = (value or "").strip()
|
||
if not raw:
|
||
raise TargetParseError("Empty target")
|
||
|
||
creator_mode = mode == MODE_CREATOR
|
||
|
||
external_id = ""
|
||
if raw.startswith("http") or "/" in raw:
|
||
patterns = spec.creator_url_res if creator_mode else spec.note_url_res
|
||
for pattern in patterns:
|
||
match = pattern.search(raw)
|
||
if match:
|
||
external_id = match.group(1)
|
||
break
|
||
|
||
# **认不出来就原样存,不拦。**(2026-10-12 按用户要求关掉校验。)
|
||
#
|
||
# 代价必须写在明处:`external_id` 是采集时**唯一**拿去请求的东西,所以一个认不出的
|
||
# 值会变成一个「永远抓不到东西」的目标。好在不会静默 —— 那一轮跑完 ingest 会发现
|
||
# 「一条都没抓到」并报出来,而且会先排除登录问题(其他任务正常时提示检查这个目标)。
|
||
#
|
||
# 之所以能接受:解析规则是**平台相关的白名单**(比如抖音博主链接必须含
|
||
# `douyin.com/user/`,`v.douyin.com` 那种分享短链现在也放行),平台一改形状就会把
|
||
# 正常链接拦在外面 —— 而拦在门外时用户只能干瞪眼,放进来至少还有得查。
|
||
if not external_id:
|
||
# `external_id` 是 varchar(128),而带参数的完整链接常常就 130+ 字符
|
||
# (抖音 sec_uid 本身 66 位)。不截断的话这一条会直接写库失败。
|
||
external_id = raw[:128]
|
||
|
||
params = parse_qs(urlparse(raw).query) if raw.startswith("http") else {}
|
||
return {
|
||
"external_id": external_id,
|
||
"xsec_token": (params.get("xsec_token") or [""])[0],
|
||
"xsec_source": (params.get("xsec_source") or [""])[0],
|
||
"raw_value": raw,
|
||
}
|
||
|
||
|
||
async def platform_task_ids(session: AsyncSession, platform: str) -> List[int]:
|
||
"""Ids of the tasks belonging to a platform.
|
||
|
||
Note/comment/event tables carry no platform column -- they hang off a task --
|
||
so scoping a query to a platform means scoping it to that task set.
|
||
"""
|
||
return list(
|
||
await session.scalars(select(MonitorTask.id).where(MonitorTask.platform == platform))
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Task CRUD
|
||
# ---------------------------------------------------------------------------
|
||
|
||
async def create_task(session: AsyncSession, payload: Dict[str, Any]) -> MonitorTask:
|
||
mode = payload["mode"]
|
||
if mode not in (MODE_CREATOR, MODE_NOTE):
|
||
raise ValueError(f"Unsupported mode: {mode}")
|
||
|
||
# Rejects unknown platforms and, more importantly, platforms whose crawler
|
||
# exists upstream but whose monitoring is not wired up -- accepting those
|
||
# would create a task that can never produce data.
|
||
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
|
||
# the Settings page actually governs new tasks.
|
||
defaults = await app_settings.defaults(session, platform)
|
||
interval_minutes = payload.get("interval_minutes") or defaults["interval_minutes"]
|
||
|
||
schedule_mode = payload.get("schedule_mode") or schedule.MODE_INTERVAL
|
||
schedule_hours = list(payload.get("schedule_hours") or [])
|
||
schedule_days = list(payload.get("schedule_days") or [])
|
||
schedule_minute = int(payload.get("schedule_minute") or 0)
|
||
_require_clock_fields(schedule_mode, schedule_hours, schedule_days)
|
||
|
||
task = MonitorTask(
|
||
name=payload["name"],
|
||
platform=platform,
|
||
mode=mode,
|
||
enabled=payload.get("enabled", True),
|
||
interval_minutes=interval_minutes,
|
||
schedule_mode=schedule_mode,
|
||
schedule_hours=schedule.format_hours(schedule_hours),
|
||
schedule_days=schedule.format_days(schedule_days),
|
||
schedule_minute=schedule_minute,
|
||
max_notes_count=payload.get("max_notes_count") or defaults["max_notes_count"],
|
||
enable_comments=payload.get("enable_comments", True),
|
||
max_comments_count=payload.get("max_comments_count") or defaults["max_comments_count"],
|
||
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,
|
||
hours=schedule_hours,
|
||
days=schedule_days,
|
||
minute=schedule_minute,
|
||
after_ms=now,
|
||
),
|
||
last_status="idle",
|
||
created_at=now,
|
||
updated_at=now,
|
||
)
|
||
session.add(task)
|
||
await session.flush()
|
||
|
||
seen: set[str] = set()
|
||
for value in payload.get("targets", []):
|
||
parsed = await prepare_target(value, mode, platform)
|
||
if parsed["external_id"] in seen:
|
||
continue
|
||
seen.add(parsed["external_id"])
|
||
session.add(
|
||
MonitorTarget(
|
||
task_id=task.id,
|
||
kind=mode,
|
||
external_id=parsed["external_id"],
|
||
xsec_token=parsed["xsec_token"],
|
||
xsec_source=parsed["xsec_source"],
|
||
raw_value=parsed["raw_value"],
|
||
label=parsed["external_id"],
|
||
enabled=True,
|
||
created_at=now,
|
||
)
|
||
)
|
||
|
||
await session.flush()
|
||
return task
|
||
|
||
|
||
async def update_task(session: AsyncSession, task_id: int, payload: Dict[str, Any]) -> MonitorTask:
|
||
task = await session.get(MonitorTask, task_id)
|
||
if task is None:
|
||
raise ValueError(f"Task {task_id} not found")
|
||
|
||
was_enabled = task.enabled
|
||
|
||
for field in (
|
||
"name",
|
||
"enabled",
|
||
"interval_minutes",
|
||
"schedule_mode",
|
||
"schedule_minute",
|
||
"max_notes_count",
|
||
"enable_comments",
|
||
"max_comments_count",
|
||
"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:
|
||
task.schedule_hours = schedule.format_hours(payload["schedule_hours"])
|
||
if payload.get("schedule_days") is not None:
|
||
task.schedule_days = schedule.format_days(payload["schedule_days"])
|
||
|
||
# Replacing targets resets the baseline implicitly: a note set that now
|
||
# includes new ids will simply report them as new on the next run.
|
||
if payload.get("targets") is not None:
|
||
await session.execute(delete(MonitorTarget).where(MonitorTarget.task_id == task_id))
|
||
now = get_current_timestamp()
|
||
seen: set[str] = set()
|
||
for value in payload["targets"]:
|
||
parsed = await prepare_target(value, task.mode, task.platform)
|
||
if parsed["external_id"] in seen:
|
||
continue
|
||
seen.add(parsed["external_id"])
|
||
session.add(
|
||
MonitorTarget(
|
||
task_id=task_id,
|
||
kind=task.mode,
|
||
external_id=parsed["external_id"],
|
||
xsec_token=parsed["xsec_token"],
|
||
xsec_source=parsed["xsec_source"],
|
||
raw_value=parsed["raw_value"],
|
||
label=parsed["external_id"],
|
||
enabled=True,
|
||
created_at=now,
|
||
)
|
||
)
|
||
|
||
# Any change to when the task runs invalidates the pending slot, so recompute
|
||
# it from the merged state rather than working out which field moved.
|
||
# Re-enabling counts as a change too: otherwise a task switched off for a
|
||
# month comes back holding a next_run_at a month in the past and fires the
|
||
# instant it is saved.
|
||
if (SCHEDULE_FIELDS & set(payload)) or (task.enabled and not was_enabled):
|
||
hours = schedule.parse_hours(task.schedule_hours)
|
||
days = schedule.parse_days(task.schedule_days)
|
||
_require_clock_fields(task.schedule_mode, hours, days)
|
||
task.next_run_at = schedule.next_occurrence(
|
||
mode=task.schedule_mode,
|
||
interval_minutes=task.interval_minutes,
|
||
hours=hours,
|
||
days=days,
|
||
minute=task.schedule_minute,
|
||
after_ms=get_current_timestamp(),
|
||
)
|
||
|
||
task.updated_at = get_current_timestamp()
|
||
await session.flush()
|
||
return task
|
||
|
||
|
||
async def delete_task(session: AsyncSession, task_id: int) -> None:
|
||
task = await session.get(MonitorTask, task_id)
|
||
if task is None:
|
||
raise ValueError(f"Task {task_id} not found")
|
||
await session.delete(task)
|
||
|
||
|
||
def trigger_manual_run(task_id: int) -> None:
|
||
"""Fire a run in the background and return immediately.
|
||
|
||
A crawl takes minutes, so the HTTP request must not wait for it. The UI
|
||
follows progress through the logs WebSocket and the run history.
|
||
"""
|
||
task = asyncio.create_task(execute_task(task_id, trigger="manual"))
|
||
_background_runs.add(task)
|
||
task.add_done_callback(_background_runs.discard)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Dashboard queries
|
||
# ---------------------------------------------------------------------------
|
||
|
||
async def _creator_alias_map(session: AsyncSession) -> Dict[tuple, str]:
|
||
"""``(platform, creator_hash) -> 备注``。
|
||
|
||
整体读一次再在内存里取,而不是每条作品查一次 —— 作品列表动辄几十条。备注本身很少,
|
||
表不会大。
|
||
"""
|
||
rows = (await session.scalars(select(MonitorCreatorAlias))).all()
|
||
return {(row.platform, row.creator_hash): row.alias for row in rows if row.alias}
|
||
|
||
|
||
async def set_creator_alias(
|
||
session: AsyncSession, platform: str, creator_hash: str, alias: str
|
||
) -> None:
|
||
"""给博主起备注;传空串就是删掉这条备注(界面上的"清空")。"""
|
||
alias = (alias or "").strip()[:128]
|
||
existing = await session.scalar(
|
||
select(MonitorCreatorAlias).where(
|
||
MonitorCreatorAlias.platform == platform,
|
||
MonitorCreatorAlias.creator_hash == creator_hash,
|
||
)
|
||
)
|
||
|
||
if not alias:
|
||
if existing is not None:
|
||
await session.delete(existing)
|
||
return
|
||
|
||
if existing is None:
|
||
session.add(
|
||
MonitorCreatorAlias(
|
||
platform=platform,
|
||
creator_hash=creator_hash,
|
||
alias=alias,
|
||
updated_at=get_current_timestamp(),
|
||
)
|
||
)
|
||
return
|
||
|
||
existing.alias = alias
|
||
existing.updated_at = get_current_timestamp()
|
||
|
||
|
||
async def _latest_successful_run_id(session: AsyncSession, task_id: int) -> Optional[int]:
|
||
return await session.scalar(
|
||
select(MonitorRun.id)
|
||
.where(
|
||
MonitorRun.task_id == task_id,
|
||
MonitorRun.status.in_((RUN_SUCCESS, RUN_PARTIAL)),
|
||
)
|
||
.order_by(MonitorRun.id.desc())
|
||
.limit(1)
|
||
)
|
||
|
||
|
||
def _delta(current: Optional[int], previous: Optional[int]) -> Optional[int]:
|
||
if current is None or previous is None:
|
||
return None
|
||
return current - previous
|
||
|
||
|
||
async def _note_alias_map(session: AsyncSession) -> Dict[tuple, str]:
|
||
"""``(platform, note_id) -> 作品备注``。和博主备注一个道理,整体读一次。"""
|
||
rows = (await session.scalars(select(MonitorNoteAlias))).all()
|
||
return {(row.platform, row.note_id): row.alias for row in rows if row.alias}
|
||
|
||
|
||
async def set_note_alias(
|
||
session: AsyncSession, platform: str, note_id: str, alias: str
|
||
) -> None:
|
||
"""给作品起备注;空串就是删掉这条备注。"""
|
||
alias = (alias or "").strip()[:128]
|
||
existing = await session.scalar(
|
||
select(MonitorNoteAlias).where(
|
||
MonitorNoteAlias.platform == platform,
|
||
MonitorNoteAlias.note_id == note_id,
|
||
)
|
||
)
|
||
|
||
if not alias:
|
||
if existing is not None:
|
||
await session.delete(existing)
|
||
return
|
||
|
||
if existing is None:
|
||
session.add(
|
||
MonitorNoteAlias(
|
||
platform=platform,
|
||
note_id=note_id,
|
||
alias=alias,
|
||
updated_at=get_current_timestamp(),
|
||
)
|
||
)
|
||
return
|
||
|
||
existing.alias = alias
|
||
existing.updated_at = get_current_timestamp()
|
||
|
||
|
||
# 标签能用的颜色。**必须是写死的字面量** —— Tailwind 靠静态扫描找类名,
|
||
# `text-cyber-neon-${color}` 这种拼出来的类它看不见,线上会全变成无色。
|
||
TAG_COLORS: Dict[str, str] = {
|
||
"cyan": "border-cyber-neon-cyan/40 text-cyber-neon-cyan",
|
||
"pink": "border-cyber-neon-pink/40 text-cyber-neon-pink",
|
||
"green": "border-cyber-neon-green/40 text-cyber-neon-green",
|
||
"orange": "border-cyber-neon-orange/40 text-cyber-neon-orange",
|
||
"muted": "border-cyber-border-DEFAULT text-cyber-text-secondary",
|
||
}
|
||
DEFAULT_TAG_COLOR = "cyan"
|
||
|
||
|
||
async def list_tags(session: AsyncSession) -> List[Dict[str, Any]]:
|
||
"""标签词表,带上各自被用在多少条作品上。
|
||
|
||
带上计数是为了**删之前能看清代价** —— 「这个标签用在 47 条作品上」,和「0 条」,
|
||
点删除时是完全不同的两个决定。
|
||
"""
|
||
counts = dict(
|
||
(
|
||
await session.execute(
|
||
select(MonitorNoteTag.tag_id, func.count()).group_by(MonitorNoteTag.tag_id)
|
||
)
|
||
).all()
|
||
)
|
||
|
||
rows = (
|
||
await session.scalars(
|
||
select(MonitorTag).order_by(MonitorTag.sort_order, MonitorTag.id)
|
||
)
|
||
).all()
|
||
|
||
return [
|
||
{
|
||
"id": row.id,
|
||
"name": row.name,
|
||
"color": row.color or DEFAULT_TAG_COLOR,
|
||
"keywords": row.keywords or "",
|
||
"note_count": counts.get(row.id, 0),
|
||
}
|
||
for row in rows
|
||
]
|
||
|
||
|
||
async def create_tag(
|
||
session: AsyncSession, name: str, color: str = "", keywords: str = ""
|
||
) -> MonitorTag:
|
||
"""新建标签。重名直接拒绝 —— 两个「重点」在筛选列表里是灾难。"""
|
||
name = (name or "").strip()[:32]
|
||
if not name:
|
||
raise ValueError("标签名不能为空")
|
||
|
||
existing = await session.scalar(select(MonitorTag).where(MonitorTag.name == name))
|
||
if existing is not None:
|
||
raise ValueError(f"标签「{name}」已经存在")
|
||
|
||
# 排在最后。用 max+1 而不是 count:删过标签之后 count 会撞上已有的 sort_order。
|
||
last = await session.scalar(select(func.max(MonitorTag.sort_order)))
|
||
tag = MonitorTag(
|
||
name=name,
|
||
color=color if color in TAG_COLORS else DEFAULT_TAG_COLOR,
|
||
keywords=",".join(split_keywords(keywords))[:512],
|
||
sort_order=(last or 0) + 1,
|
||
created_at=get_current_timestamp(),
|
||
)
|
||
session.add(tag)
|
||
await session.flush()
|
||
return tag
|
||
|
||
|
||
async def update_tag(
|
||
session: AsyncSession, tag_id: int, name: str, color: str = "", keywords: str = ""
|
||
) -> MonitorTag:
|
||
tag = await session.get(MonitorTag, tag_id)
|
||
if tag is None:
|
||
raise ValueError(f"标签 {tag_id} 不存在")
|
||
|
||
name = (name or "").strip()[:32]
|
||
if not name:
|
||
raise ValueError("标签名不能为空")
|
||
|
||
clash = await session.scalar(
|
||
select(MonitorTag).where(MonitorTag.name == name, MonitorTag.id != tag_id)
|
||
)
|
||
if clash is not None:
|
||
raise ValueError(f"标签「{name}」已经存在")
|
||
|
||
tag.name = name
|
||
tag.color = color if color in TAG_COLORS else DEFAULT_TAG_COLOR
|
||
tag.keywords = ",".join(split_keywords(keywords))[:512]
|
||
await session.flush()
|
||
return tag
|
||
|
||
|
||
async def delete_tag(session: AsyncSession, tag_id: int) -> int:
|
||
"""删标签,连同它在所有作品上的贴纸(返回清掉了多少条)。
|
||
|
||
**显式删关联,不靠外键级联**:测试跑的是 SQLite,而它默认不启用外键约束 ——
|
||
依赖级联的话,测试全绿、线上才对,或者反过来。
|
||
"""
|
||
tag = await session.get(MonitorTag, tag_id)
|
||
if tag is None:
|
||
raise ValueError(f"标签 {tag_id} 不存在")
|
||
|
||
removed = await session.execute(
|
||
delete(MonitorNoteTag).where(MonitorNoteTag.tag_id == tag_id)
|
||
)
|
||
await session.delete(tag)
|
||
return removed.rowcount or 0
|
||
|
||
|
||
async def _note_tag_map(session: AsyncSession) -> Dict[tuple, List[Dict[str, Any]]]:
|
||
"""``(platform, note_id) -> [标签]``。整体读一次,贴纸本来就不多。"""
|
||
rows = (
|
||
await session.execute(
|
||
select(MonitorNoteTag.platform, MonitorNoteTag.note_id, MonitorTag)
|
||
.join(MonitorTag, MonitorTag.id == MonitorNoteTag.tag_id)
|
||
.order_by(MonitorTag.sort_order, MonitorTag.id)
|
||
)
|
||
).all()
|
||
|
||
result: Dict[tuple, List[Dict[str, Any]]] = {}
|
||
for platform, note_id, tag in rows:
|
||
result.setdefault((platform, note_id), []).append(
|
||
{"id": tag.id, "name": tag.name, "color": tag.color or DEFAULT_TAG_COLOR}
|
||
)
|
||
return result
|
||
|
||
|
||
async def set_note_tags(
|
||
session: AsyncSession, platform: str, note_id: str, tag_ids: Sequence[int]
|
||
) -> List[Dict[str, Any]]:
|
||
"""把一条作品的标签**整体替换**成这一组。
|
||
|
||
整体替换而不是增删单条:界面给的是「这条作品现在的标签」,一个复选框对话框点完
|
||
保存就是一次全量提交,比对齐两边的差集简单也不容易错。
|
||
"""
|
||
wanted = {int(tag_id) for tag_id in tag_ids}
|
||
|
||
# 只认词表里真有的 id —— 前端传了脏 id 就静静忽略,别在关联表里留下孤儿。
|
||
known = set(
|
||
(await session.scalars(select(MonitorTag.id).where(MonitorTag.id.in_(wanted)))).all()
|
||
if wanted
|
||
else []
|
||
)
|
||
wanted &= known
|
||
|
||
existing = set(
|
||
(
|
||
await session.scalars(
|
||
select(MonitorNoteTag.tag_id).where(
|
||
MonitorNoteTag.platform == platform,
|
||
MonitorNoteTag.note_id == note_id,
|
||
)
|
||
)
|
||
).all()
|
||
)
|
||
|
||
for tag_id in existing - wanted:
|
||
await session.execute(
|
||
delete(MonitorNoteTag).where(
|
||
MonitorNoteTag.platform == platform,
|
||
MonitorNoteTag.note_id == note_id,
|
||
MonitorNoteTag.tag_id == tag_id,
|
||
)
|
||
)
|
||
|
||
now = get_current_timestamp()
|
||
for tag_id in wanted - existing:
|
||
session.add(
|
||
MonitorNoteTag(
|
||
platform=platform,
|
||
note_id=note_id,
|
||
tag_id=tag_id,
|
||
created_at=now,
|
||
)
|
||
)
|
||
|
||
await session.flush()
|
||
tags = await _note_tag_map(session)
|
||
return tags.get((platform, note_id), [])
|
||
|
||
|
||
async def _latest_creator_stats(
|
||
session: AsyncSession,
|
||
task_ids: Optional[Sequence[int]] = None,
|
||
creator_hashes: Optional[Sequence[str]] = None,
|
||
) -> Dict[tuple, "MonitorCreatorStat"]:
|
||
"""``(task_id, creator_hash) -> 最近一条``账号级快照。
|
||
|
||
两个参数都是**可选过滤**:传 None 就是不限。``list_notes`` 两个都给(只要手里
|
||
这批作品涉及的博主),``list_creators`` 只给任务(要的是全部博主,包括一条作品
|
||
都没有的那些)。
|
||
|
||
按 run_id 而不是 captured_at 取「最近」:和作品指标用的是同一个口径,两者放一起
|
||
看才不会出现「作品数据来自第 8 轮、粉丝数来自第 9 轮」这种对不上的情况。
|
||
"""
|
||
if task_ids is not None and not task_ids:
|
||
return {}
|
||
if creator_hashes is not None and not creator_hashes:
|
||
return {}
|
||
|
||
query = select(MonitorCreatorStat).order_by(MonitorCreatorStat.run_id.desc())
|
||
if task_ids is not None:
|
||
query = query.where(MonitorCreatorStat.task_id.in_(list(task_ids)))
|
||
if creator_hashes is not None:
|
||
query = query.where(MonitorCreatorStat.creator_hash.in_(list(creator_hashes)))
|
||
|
||
latest: Dict[tuple, MonitorCreatorStat] = {}
|
||
for row in (await session.scalars(query)).all():
|
||
latest.setdefault((row.task_id, row.creator_hash), row) # 已按 run_id 倒序
|
||
return latest
|
||
|
||
|
||
def _window_order(note: MonitorNote) -> tuple:
|
||
"""开窗排序:按**发布时间**倒序。
|
||
|
||
采集端 ``aweme/post`` 拿的就是最新 N 条,界面的窗口必须和它口径一致 —— 否则会出现
|
||
「显示着的这条其实已经采不到了」。
|
||
|
||
**时间不知道的排最前(永不隐藏)**:因为解析不出日期就让一条作品从列表里消失,比
|
||
多显示一条糟得多。
|
||
"""
|
||
return (note.published_at is None, note.published_at or 0)
|
||
|
||
|
||
async def _within_creator_window(
|
||
session: AsyncSession, notes: List[MonitorNote]
|
||
) -> List[MonitorNote]:
|
||
"""每个博主只留**最新 N 条**,N 取任务上的 ``max_notes_count``。
|
||
|
||
**库里一条都不删。** 作品栏是「我正在盯的窗口」,库是账本:掉出窗口的作品采集端就
|
||
再也取不到了(它取的是最新 N 条),指标会冻在最后一次而**它看上去和正在跟踪的
|
||
作品一模一样** —— 那才是真正会骗人的地方。趋势图、报表、导出读的仍然是全量。
|
||
|
||
只对**博主模式**开窗:笔记模式的 ``max_notes_count`` 管的是「每条目标拉多少」,
|
||
而它的目标本身就是一件作品,不存在「一个博主的第 21 条」。
|
||
"""
|
||
task_ids = {note.task_id for note in notes}
|
||
tasks = {
|
||
row.id: row
|
||
for row in (
|
||
await session.scalars(
|
||
select(MonitorTask).where(MonitorTask.id.in_(list(task_ids)))
|
||
)
|
||
).all()
|
||
}
|
||
|
||
by_creator: Dict[tuple, List[MonitorNote]] = {}
|
||
for note in notes:
|
||
by_creator.setdefault((note.task_id, note.creator_hash), []).append(note)
|
||
|
||
kept: List[MonitorNote] = []
|
||
for (note_task_id, _creator_hash), group in by_creator.items():
|
||
task = tasks.get(note_task_id)
|
||
if task is None or task.mode != MODE_CREATOR:
|
||
kept.extend(group)
|
||
continue
|
||
group.sort(key=_window_order, reverse=True)
|
||
kept.extend(group[: task.max_notes_count])
|
||
return kept
|
||
|
||
|
||
async def list_notes(
|
||
session: AsyncSession,
|
||
task_id: Optional[int] = None,
|
||
only_new: bool = False,
|
||
limit: int = 200,
|
||
platform: Optional[str] = None,
|
||
*,
|
||
windowed: bool = False,
|
||
tag_ids: Optional[Sequence[int]] = None,
|
||
) -> List[Dict[str, Any]]:
|
||
"""Tracked notes with their latest metrics and change vs the previous run.
|
||
|
||
``windowed`` 打开后只返回每个博主最新 ``max_notes_count`` 条(见
|
||
``_within_creator_window``)。**默认关闭**:导出要的是全量账本,而默认开启的话,
|
||
忘了传这个参数的那条路会静默少数据。
|
||
"""
|
||
query = select(MonitorNote).order_by(MonitorNote.last_seen_at.desc())
|
||
# 开窗时**不能**在这里 limit:得先把每个博主的窗开出来,顺序反了的话,全局上限会把
|
||
# 某个博主最新的那几条挤掉,剩下的还都是别人的。
|
||
if not windowed:
|
||
query = query.limit(limit)
|
||
if task_id is not None:
|
||
query = query.where(MonitorNote.task_id == task_id)
|
||
if platform is not None:
|
||
scoped = await platform_task_ids(session, platform)
|
||
if not scoped:
|
||
return []
|
||
query = query.where(MonitorNote.task_id.in_(scoped))
|
||
|
||
if tag_ids:
|
||
# 命中**任意一个**选中的标签。作品 id 在平台内唯一,而这里的 query 本来就已经
|
||
# 被任务/平台圈定了,所以只按 note_id 关联就够。
|
||
query = query.where(
|
||
MonitorNote.note_id.in_(
|
||
select(MonitorNoteTag.note_id).where(
|
||
MonitorNoteTag.tag_id.in_([int(t) for t in tag_ids])
|
||
)
|
||
)
|
||
)
|
||
|
||
notes = list((await session.scalars(query)).all())
|
||
if not notes:
|
||
return []
|
||
|
||
if windowed:
|
||
notes = await _within_creator_window(session, notes)
|
||
# 开完窗再截全局上限。窗口内的作品本来就不多,这里的 200 只是兜底。
|
||
notes = notes[:limit]
|
||
if not notes:
|
||
return []
|
||
|
||
note_ids = [note.note_id for note in notes]
|
||
|
||
# Fetch every snapshot for these notes in one go and gather the two most
|
||
# recent per note, rather than issuing two queries per note.
|
||
snapshots = list(
|
||
(
|
||
await session.scalars(
|
||
select(MonitorNoteMetric)
|
||
.where(MonitorNoteMetric.note_id.in_(note_ids))
|
||
.order_by(MonitorNoteMetric.note_id, MonitorNoteMetric.run_id.desc())
|
||
)
|
||
).all()
|
||
)
|
||
by_note: Dict[str, List[MonitorNoteMetric]] = {}
|
||
for snapshot in snapshots:
|
||
by_note.setdefault(snapshot.note_id, []).append(snapshot)
|
||
|
||
latest_run_ids: Dict[int, Optional[int]] = {}
|
||
result: List[Dict[str, Any]] = []
|
||
|
||
# 博主的备注。键是 (platform, creator_hash) —— 作品的 platform 挂在它的任务上。
|
||
task_platform = {
|
||
row.id: row.platform
|
||
for row in (
|
||
await session.execute(
|
||
select(MonitorTask.id, MonitorTask.platform).where(
|
||
MonitorTask.id.in_({note.task_id for note in notes})
|
||
)
|
||
)
|
||
).all()
|
||
}
|
||
aliases = await _creator_alias_map(session)
|
||
note_aliases = await _note_alias_map(session)
|
||
note_tags = await _note_tag_map(session)
|
||
# 账号级指标(粉丝 / 总获赞 / 作品数)。**挂在作品上一起返回**,因为界面上就是按博主
|
||
# 归组显示的 —— 让前端为了一个组头再发一轮请求没道理。同一个博主的所有作品拿到的是
|
||
# 同一条(键里带 task_id,所以跨任务不会串)。没有的(小红书那条路不产生它)就是 null,
|
||
# 前端据此整块不显示,而不是显示一个 0。
|
||
creator_stats = await _latest_creator_stats(
|
||
session,
|
||
[note.task_id for note in notes],
|
||
[note.creator_hash for note in notes if note.creator_hash],
|
||
)
|
||
|
||
for note in notes:
|
||
series = by_note.get(note.note_id, [])
|
||
current = series[0] if series else None
|
||
previous = series[1] if len(series) > 1 else None
|
||
|
||
if only_new:
|
||
if note.task_id not in latest_run_ids:
|
||
latest_run_ids[note.task_id] = await _latest_successful_run_id(session, note.task_id)
|
||
if note.first_seen_run_id != latest_run_ids[note.task_id]:
|
||
continue
|
||
|
||
stat = creator_stats.get((note.task_id, note.creator_hash))
|
||
|
||
result.append(
|
||
{
|
||
"task_id": note.task_id,
|
||
"note_id": note.note_id,
|
||
"title": note.title,
|
||
"note_url": note.note_url,
|
||
# 作品的发布时间(爬虫侧:小红书叫 time、抖音叫 create_time)。
|
||
# 和 first_seen_at 不是一回事 —— 那是**我们第一次看到它**的时间;把一个
|
||
# 早就存在的作品加进监控时,两者能差好几个月。可能为 null(平台没给,
|
||
# 或者值解析不出来),所以前端要能显示成「—」。
|
||
"published_at": note.published_at,
|
||
# 按博主分组用。creator_hash 是唯一稳定的创作者标识(原始 user_id
|
||
# 被爬虫刻意匿名化了),creator_name 是昵称本身 —— 本仓库关掉了脱敏
|
||
# (见 config.MASK_NICKNAME),所以就是原文。
|
||
"creator_hash": note.creator_hash,
|
||
"creator_name": note.creator_name,
|
||
# 人自己起的备注,界面上优先显示它 —— 昵称认不出是谁,哈希更认不出。
|
||
"creator_alias": aliases.get(
|
||
(task_platform.get(note.task_id, ""), note.creator_hash), ""
|
||
),
|
||
# 这条作品自己的备注。和博主备注是两件事:博主备注回答"这是谁",它回答
|
||
# "这条我要盯着"。
|
||
"note_alias": note_aliases.get(
|
||
(task_platform.get(note.task_id, ""), note.note_id), ""
|
||
),
|
||
# 贴在这条作品上的标签。备注是自由文字(一句话说明),标签是从设置里那份
|
||
# 词表选的分类 —— 两者互补,不是一回事。
|
||
"tags": note_tags.get((task_platform.get(note.task_id, ""), note.note_id), []),
|
||
# 博主账号级指标 —— 作品列表给不了的东西。三个值都可能为 null(平台没采
|
||
# 到、或者这条作品来自不产生它的数据源),前端据此整块不画。
|
||
"creator_fans": stat.fans if stat else None,
|
||
"creator_total_favorited": stat.total_favorited if stat else None,
|
||
"creator_works": stat.works_count if stat else None,
|
||
"creator_stats_at": stat.captured_at if stat else None,
|
||
# 优先给本地缓存地址:远程地址带签名、会过期(实测隔天即 403),
|
||
# 本地那份不会。没有缓存时才退回远程,至少让图先显示出来。
|
||
"cover": covers.cover_url(note.note_id, note.cover),
|
||
"first_seen_at": note.first_seen_at,
|
||
"last_seen_at": note.last_seen_at,
|
||
"is_new": note.first_seen_run_id == latest_run_ids.get(note.task_id),
|
||
"metrics": {
|
||
"liked_count": current.liked_count if current else None,
|
||
"comment_count": current.comment_count if current else None,
|
||
"collected_count": current.collected_count if current else None,
|
||
"share_count": current.share_count if current else None,
|
||
},
|
||
"deltas": {
|
||
"liked_count": _delta(
|
||
current.liked_count if current else None,
|
||
previous.liked_count if previous else None,
|
||
),
|
||
"comment_count": _delta(
|
||
current.comment_count if current else None,
|
||
previous.comment_count if previous else None,
|
||
),
|
||
"collected_count": _delta(
|
||
current.collected_count if current else None,
|
||
previous.collected_count if previous else None,
|
||
),
|
||
"share_count": _delta(
|
||
current.share_count if current else None,
|
||
previous.share_count if previous else None,
|
||
),
|
||
},
|
||
"snapshot_count": len(series),
|
||
}
|
||
)
|
||
|
||
return result
|
||
|
||
|
||
async def list_creators(
|
||
session: AsyncSession,
|
||
task_id: Optional[int] = None,
|
||
platform: Optional[str] = None,
|
||
) -> List[Dict[str, Any]]:
|
||
"""作品栏里要显示的**博主** —— **包括一条作品都没有的**。
|
||
|
||
分组原先是从作品推出来的(按作品的 creator_hash 归组),于是没有作品的博主根本
|
||
不会出现在列表里:目标加了、资料也采到了、粉丝数就躺在库里,界面上什么都看不见。
|
||
而「这个号在涨粉、只是最近没发作品」恰恰是最该看见的一种情况 —— 藏起来正好藏反了。
|
||
|
||
所以来源换成 **账号快照 ∪ 作品**:
|
||
|
||
* 有快照没作品 → 一个 0 篇的组,粉丝数照常显示;
|
||
* 有作品没快照 → 一个没有账号指标的组(小红书那条路不产生快照,就是这种情况)。
|
||
|
||
``creator_alias`` 从作品备注那张表来;``note_count`` / ``last_activity_at`` 用来
|
||
排序,让最近还在动的博主排在前面。
|
||
"""
|
||
scope: Optional[List[int]] = None
|
||
if task_id is not None:
|
||
scope = [task_id]
|
||
elif platform is not None:
|
||
scope = await platform_task_ids(session, platform)
|
||
if not scope:
|
||
return []
|
||
|
||
# 作品一侧:谁有作品、有几篇、最后一次是什么时候。
|
||
work_query = (
|
||
select(
|
||
MonitorNote.task_id,
|
||
MonitorNote.creator_hash,
|
||
func.count().label("note_count"),
|
||
func.max(MonitorNote.last_seen_at).label("last_seen_at"),
|
||
func.max(MonitorNote.creator_name).label("creator_name"),
|
||
func.max(MonitorNote.creator_id).label("creator_id"),
|
||
)
|
||
.where(MonitorNote.creator_hash != "")
|
||
.group_by(MonitorNote.task_id, MonitorNote.creator_hash)
|
||
)
|
||
if scope is not None:
|
||
work_query = work_query.where(MonitorNote.task_id.in_(scope))
|
||
|
||
work: Dict[tuple, Dict[str, Any]] = {}
|
||
for row in (await session.execute(work_query)).all():
|
||
work[(row.task_id, row.creator_hash)] = {
|
||
"note_count": row.note_count,
|
||
"last_seen_at": row.last_seen_at,
|
||
"creator_name": row.creator_name or "",
|
||
"creator_id": row.creator_id or "",
|
||
}
|
||
|
||
stats = await _latest_creator_stats(session, task_ids=scope)
|
||
if not work and not stats:
|
||
return []
|
||
|
||
# 备注是按 (platform, creator_hash) 存的,所以要知道每个博主属于哪个平台。
|
||
involved = {key[0] for key in set(work) | set(stats)}
|
||
task_platform = {
|
||
row.id: row.platform
|
||
for row in (
|
||
await session.execute(
|
||
select(MonitorTask.id, MonitorTask.platform).where(
|
||
MonitorTask.id.in_(list(involved))
|
||
)
|
||
)
|
||
).all()
|
||
}
|
||
aliases = await _creator_alias_map(session)
|
||
|
||
result: List[Dict[str, Any]] = []
|
||
for key in set(work) | set(stats):
|
||
row_task, creator_hash = key
|
||
work_row = work.get(key)
|
||
stat = stats.get(key)
|
||
result.append(
|
||
{
|
||
"task_id": row_task,
|
||
"creator_hash": creator_hash,
|
||
# 昵称**优先取账号快照**里的。快照每次采集都从资料接口重写一遍,是这一行
|
||
# 最新的一份;作品上的名字只会跟着「这一轮采到的那几条」更新,掉出采集
|
||
# 窗口的老作品可能还留着旧名字。博主改名之后取作品的会显示旧名。
|
||
# 没有快照的(小红书那条路不产生快照)才退回作品上的名字。
|
||
"creator_name": (stat.nickname if stat else "")
|
||
or (work_row or {}).get("creator_name")
|
||
or "",
|
||
"creator_alias": aliases.get(
|
||
(task_platform.get(row_task, ""), creator_hash), ""
|
||
),
|
||
# 主页跳转。拿不到主页 id(小红书不落创作者资料、或者这个博主还没采过
|
||
# 资料)就是空串,界面不画按钮 —— 而不是给一个点开 404 的链接。
|
||
#
|
||
# **作品上的 id 是账号快照的兜底**:作品模式(以及超级编导导入)只拉
|
||
# 作品详情、不拉创作者资料,快照一行都没有 —— 但详情里的
|
||
# ``author.sec_uid`` 已经落在作品上了。没有这层兜底,这类任务里每个博主
|
||
# 都缺主页链接,而这恰恰是它们唯一能跳的地方。
|
||
"creator_url": adapters.creator_url(
|
||
task_platform.get(row_task, ""),
|
||
(stat.creator_id if stat else "")
|
||
or (work_row or {}).get("creator_id")
|
||
or "",
|
||
),
|
||
"note_count": (work_row or {}).get("note_count", 0),
|
||
"creator_fans": stat.fans if stat else None,
|
||
"creator_total_favorited": stat.total_favorited if stat else None,
|
||
"creator_works": stat.works_count if stat else None,
|
||
"creator_stats_at": stat.captured_at if stat else None,
|
||
# 排序用:作品最近出现的时间,或者账号指标的采集时间,取晚的那个。
|
||
"last_activity_at": max(
|
||
(work_row or {}).get("last_seen_at") or 0,
|
||
stat.captured_at if stat else 0,
|
||
),
|
||
}
|
||
)
|
||
|
||
result.sort(key=lambda row: row["last_activity_at"], reverse=True)
|
||
return result
|
||
|
||
|
||
async def note_series(session: AsyncSession, note_id: str, task_id: Optional[int] = None) -> List[Dict[str, Any]]:
|
||
"""Metric time series for one note."""
|
||
query = (
|
||
select(MonitorNoteMetric)
|
||
.where(MonitorNoteMetric.note_id == note_id)
|
||
.order_by(MonitorNoteMetric.run_id)
|
||
)
|
||
if task_id is not None:
|
||
query = query.where(MonitorNoteMetric.task_id == task_id)
|
||
|
||
return [
|
||
{
|
||
"run_id": row.run_id,
|
||
"captured_at": row.captured_at,
|
||
"liked_count": row.liked_count,
|
||
"comment_count": row.comment_count,
|
||
"collected_count": row.collected_count,
|
||
"share_count": row.share_count,
|
||
}
|
||
for row in (await session.scalars(query)).all()
|
||
]
|
||
|
||
|
||
async def _note_meta_map(
|
||
session: AsyncSession, note_ids: List[str]
|
||
) -> Dict[str, Dict[str, Any]]:
|
||
"""Look up note title/cover/url for a set of note ids.
|
||
|
||
Fetched as one query and joined in Python rather than as a SQL join: the
|
||
comment table has no foreign key to the note table (both are keyed by the
|
||
platform's note id, per task), and a single IN() is easier to follow here.
|
||
"""
|
||
if not note_ids:
|
||
return {}
|
||
|
||
rows = (
|
||
await session.scalars(select(MonitorNote).where(MonitorNote.note_id.in_(set(note_ids))))
|
||
).all()
|
||
return {
|
||
row.note_id: {
|
||
"note_title": row.title,
|
||
"note_cover": covers.cover_url(row.note_id, row.cover),
|
||
"note_url": row.note_url,
|
||
"published_at": row.published_at,
|
||
"task_id": row.task_id,
|
||
# 博主维度也带上,评论流才能按 博主 -> 作品 -> 评论 三级展开。
|
||
"creator_hash": row.creator_hash,
|
||
"creator_name": row.creator_name,
|
||
}
|
||
for row in rows
|
||
}
|
||
|
||
|
||
async def list_comments(
|
||
session: AsyncSession,
|
||
task_id: Optional[int] = None,
|
||
note_id: Optional[str] = None,
|
||
limit: int = 200,
|
||
platform: Optional[str] = None,
|
||
) -> List[Dict[str, Any]]:
|
||
"""Comments, each carrying the note it belongs to.
|
||
|
||
The note association is the point: without it a comment stream is unreadable,
|
||
since a bare note_id tells the operator nothing.
|
||
"""
|
||
query = select(MonitorComment).order_by(MonitorComment.first_seen_at.desc()).limit(limit)
|
||
if task_id is not None:
|
||
query = query.where(MonitorComment.task_id == task_id)
|
||
if note_id is not None:
|
||
query = query.where(MonitorComment.note_id == note_id)
|
||
if platform is not None:
|
||
scoped = await platform_task_ids(session, platform)
|
||
if not scoped:
|
||
return []
|
||
query = query.where(MonitorComment.task_id.in_(scoped))
|
||
|
||
comments = list((await session.scalars(query)).all())
|
||
meta = await _note_meta_map(session, [row.note_id for row in comments])
|
||
|
||
return [
|
||
{
|
||
"task_id": row.task_id,
|
||
"note_id": row.note_id,
|
||
"comment_id": row.comment_id,
|
||
"content": row.content,
|
||
"nickname": row.nickname,
|
||
"create_time": row.create_time,
|
||
"like_count": row.like_count,
|
||
"sub_comment_count": row.sub_comment_count,
|
||
"first_seen_at": row.first_seen_at,
|
||
"note_title": meta.get(row.note_id, {}).get("note_title", ""),
|
||
"note_cover": meta.get(row.note_id, {}).get("note_cover", ""),
|
||
"note_url": meta.get(row.note_id, {}).get("note_url", ""),
|
||
"note_creator_hash": meta.get(row.note_id, {}).get("creator_hash", ""),
|
||
"note_creator_name": meta.get(row.note_id, {}).get("creator_name", ""),
|
||
"note_published_at": meta.get(row.note_id, {}).get("published_at"),
|
||
}
|
||
for row in comments
|
||
]
|
||
|
||
|
||
async def comment_note_groups(
|
||
session: AsyncSession, task_id: Optional[int] = None, platform: Optional[str] = None
|
||
) -> List[Dict[str, Any]]:
|
||
"""Notes that have comments, newest first, with their comment counts.
|
||
|
||
Feeds the comment filter dropdown: the operator picks a work by title, so
|
||
the counts need to be visible before choosing.
|
||
"""
|
||
scoped_ids: Optional[List[int]] = None
|
||
if platform is not None:
|
||
scoped_ids = await platform_task_ids(session, platform)
|
||
if not scoped_ids:
|
||
return []
|
||
|
||
count_query = select(
|
||
MonitorComment.note_id, func.count().label("comment_count")
|
||
).group_by(MonitorComment.note_id)
|
||
if task_id is not None:
|
||
count_query = count_query.where(MonitorComment.task_id == task_id)
|
||
if scoped_ids is not None:
|
||
count_query = count_query.where(MonitorComment.task_id.in_(scoped_ids))
|
||
|
||
counts = {row.note_id: row.comment_count for row in (await session.execute(count_query)).all()}
|
||
if not counts:
|
||
return []
|
||
|
||
latest_query = (
|
||
select(MonitorComment.note_id, func.max(MonitorComment.first_seen_at).label("latest"))
|
||
.where(MonitorComment.note_id.in_(set(counts)))
|
||
.group_by(MonitorComment.note_id)
|
||
)
|
||
if task_id is not None:
|
||
latest_query = latest_query.where(MonitorComment.task_id == task_id)
|
||
if scoped_ids is not None:
|
||
latest_query = latest_query.where(MonitorComment.task_id.in_(scoped_ids))
|
||
latest = {row.note_id: row.latest for row in (await session.execute(latest_query)).all()}
|
||
|
||
meta = await _note_meta_map(session, list(counts))
|
||
|
||
groups = [
|
||
{
|
||
"note_id": note_id,
|
||
"note_title": meta.get(note_id, {}).get("note_title", ""),
|
||
"note_cover": meta.get(note_id, {}).get("note_cover", ""),
|
||
"note_url": meta.get(note_id, {}).get("note_url", ""),
|
||
"creator_hash": meta.get(note_id, {}).get("creator_hash", ""),
|
||
"creator_name": meta.get(note_id, {}).get("creator_name", ""),
|
||
"comment_count": count,
|
||
"latest_at": latest.get(note_id, 0),
|
||
}
|
||
for note_id, count in counts.items()
|
||
]
|
||
groups.sort(key=lambda group: group["latest_at"], reverse=True)
|
||
return groups
|
||
|
||
|
||
async def list_events(
|
||
session: AsyncSession,
|
||
task_id: Optional[int] = None,
|
||
event_type: Optional[str] = None,
|
||
since_id: Optional[int] = None,
|
||
limit: int = 200,
|
||
platform: Optional[str] = None,
|
||
) -> List[Dict[str, Any]]:
|
||
query = select(MonitorEvent).order_by(MonitorEvent.id.desc()).limit(limit)
|
||
if task_id is not None:
|
||
query = query.where(MonitorEvent.task_id == task_id)
|
||
if event_type is not None:
|
||
query = query.where(MonitorEvent.type == event_type)
|
||
if since_id is not None:
|
||
query = query.where(MonitorEvent.id > since_id)
|
||
if platform is not None:
|
||
scoped = await platform_task_ids(session, platform)
|
||
if not scoped:
|
||
return []
|
||
query = query.where(MonitorEvent.task_id.in_(scoped))
|
||
|
||
return [
|
||
{
|
||
"id": row.id,
|
||
"task_id": row.task_id,
|
||
"run_id": row.run_id,
|
||
"type": row.type,
|
||
"severity": row.severity,
|
||
"target_kind": row.target_kind,
|
||
"target_id": row.target_id,
|
||
"title": row.title,
|
||
"created_at": row.created_at,
|
||
"is_read": row.is_read,
|
||
}
|
||
for row in (await session.scalars(query)).all()
|
||
]
|
||
|
||
|
||
async def list_runs(session: AsyncSession, task_id: int, limit: int = 50) -> List[Dict[str, Any]]:
|
||
rows = (
|
||
await session.scalars(
|
||
select(MonitorRun)
|
||
.where(MonitorRun.task_id == task_id)
|
||
.order_by(MonitorRun.id.desc())
|
||
.limit(limit)
|
||
)
|
||
).all()
|
||
|
||
return [
|
||
{
|
||
"id": row.id,
|
||
"task_id": row.task_id,
|
||
"status": row.status,
|
||
"trigger": row.trigger,
|
||
"queued_at": row.queued_at,
|
||
"started_at": row.started_at,
|
||
"finished_at": row.finished_at,
|
||
"exit_code": row.exit_code,
|
||
"notes_fetched": row.notes_fetched,
|
||
"comments_fetched": row.comments_fetched,
|
||
"new_notes": row.new_notes,
|
||
"new_comments": row.new_comments,
|
||
"is_baseline": row.is_baseline,
|
||
"max_comments_count": row.max_comments_count,
|
||
"error_message": row.error_message,
|
||
}
|
||
for row in rows
|
||
]
|
||
|
||
|
||
async def list_tasks(
|
||
session: AsyncSession, platform: Optional[str] = None
|
||
) -> List[Dict[str, Any]]:
|
||
query = select(MonitorTask).order_by(MonitorTask.id)
|
||
if platform is not None:
|
||
query = query.where(MonitorTask.platform == platform)
|
||
|
||
tasks = list((await session.scalars(query)).all())
|
||
if not tasks:
|
||
return []
|
||
|
||
counts = dict(
|
||
(
|
||
await session.execute(
|
||
select(MonitorTarget.task_id, func.count())
|
||
.group_by(MonitorTarget.task_id)
|
||
)
|
||
).all()
|
||
)
|
||
unread = dict(
|
||
(
|
||
await session.execute(
|
||
select(MonitorEvent.task_id, func.count())
|
||
.where(MonitorEvent.is_read.is_(False))
|
||
.group_by(MonitorEvent.task_id)
|
||
)
|
||
).all()
|
||
)
|
||
|
||
return [
|
||
{
|
||
"id": task.id,
|
||
"name": task.name,
|
||
"platform": task.platform,
|
||
"mode": task.mode,
|
||
"enabled": task.enabled,
|
||
"interval_minutes": task.interval_minutes,
|
||
**_schedule_fields(task),
|
||
"max_notes_count": task.max_notes_count,
|
||
"enable_comments": task.enable_comments,
|
||
"max_comments_count": task.max_comments_count,
|
||
"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,
|
||
"last_error": task.last_error,
|
||
"last_notified_at": task.last_notified_at,
|
||
"target_count": counts.get(task.id, 0),
|
||
"targets": [
|
||
{"id": t.id, "external_id": t.external_id, "raw_value": t.raw_value, "enabled": t.enabled}
|
||
for t in task.targets
|
||
],
|
||
"unread_events": unread.get(task.id, 0),
|
||
}
|
||
for task in tasks
|
||
]
|
||
|
||
|
||
def _schedule_fields(task: MonitorTask) -> Dict[str, Any]:
|
||
"""The schedule columns, plus the sentence the task list renders.
|
||
|
||
The label is composed here rather than in the frontend so the list and the
|
||
editor cannot drift on what a given schedule means.
|
||
"""
|
||
hours = schedule.parse_hours(task.schedule_hours)
|
||
days = schedule.parse_days(task.schedule_days)
|
||
return {
|
||
"schedule_mode": task.schedule_mode,
|
||
"schedule_hours": hours,
|
||
"schedule_days": days,
|
||
"schedule_minute": task.schedule_minute,
|
||
"schedule_label": schedule.describe(
|
||
mode=task.schedule_mode,
|
||
interval_minutes=task.interval_minutes,
|
||
hours=hours,
|
||
days=days,
|
||
minute=task.schedule_minute,
|
||
),
|
||
}
|
||
|
||
|
||
async def overview(session: AsyncSession, platform: Optional[str] = None) -> Dict[str, Any]:
|
||
"""Headline numbers for the dashboard tiles, scoped to one platform."""
|
||
now = get_current_timestamp()
|
||
day_ago = now - 24 * 60 * 60 * 1000
|
||
|
||
# Nothing but the task table carries a platform column, so the other counts
|
||
# are scoped through the platform's task ids.
|
||
scoped: Optional[List[int]] = None
|
||
if platform is not None:
|
||
scoped = await platform_task_ids(session, platform)
|
||
|
||
def by_task(stmt, column):
|
||
return stmt if scoped is None else stmt.where(column.in_(scoped))
|
||
|
||
task_count = select(func.count()).select_from(MonitorTask)
|
||
if platform is not None:
|
||
task_count = task_count.where(MonitorTask.platform == platform)
|
||
|
||
enabled_count = select(func.count()).select_from(MonitorTask).where(
|
||
MonitorTask.enabled.is_(True)
|
||
)
|
||
if platform is not None:
|
||
enabled_count = enabled_count.where(MonitorTask.platform == platform)
|
||
|
||
return {
|
||
"platform": platform,
|
||
"tasks": await session.scalar(task_count) or 0,
|
||
"enabled_tasks": await session.scalar(enabled_count) or 0,
|
||
"notes": await session.scalar(
|
||
by_task(select(func.count()).select_from(MonitorNote), MonitorNote.task_id)
|
||
)
|
||
or 0,
|
||
"comments": await session.scalar(
|
||
by_task(select(func.count()).select_from(MonitorComment), MonitorComment.task_id)
|
||
)
|
||
or 0,
|
||
"events_24h": await session.scalar(
|
||
by_task(
|
||
select(func.count())
|
||
.select_from(MonitorEvent)
|
||
.where(MonitorEvent.created_at >= day_ago),
|
||
MonitorEvent.task_id,
|
||
)
|
||
)
|
||
or 0,
|
||
"unread_events": await session.scalar(
|
||
by_task(
|
||
select(func.count())
|
||
.select_from(MonitorEvent)
|
||
.where(MonitorEvent.is_read.is_(False)),
|
||
MonitorEvent.task_id,
|
||
)
|
||
)
|
||
or 0,
|
||
"running_runs": await session.scalar(
|
||
by_task(
|
||
select(func.count())
|
||
.select_from(MonitorRun)
|
||
.where(MonitorRun.status == "running"),
|
||
MonitorRun.task_id,
|
||
)
|
||
)
|
||
or 0,
|
||
}
|
||
|
||
|
||
async def mark_events_read(session: AsyncSession, task_id: Optional[int] = None) -> int:
|
||
query = select(MonitorEvent).where(MonitorEvent.is_read.is_(False))
|
||
if task_id is not None:
|
||
query = query.where(MonitorEvent.task_id == task_id)
|
||
rows = list((await session.scalars(query)).all())
|
||
for row in rows:
|
||
row.is_read = True
|
||
return len(rows)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 标签矩阵(日期 × 博主)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 账号池状态(外部服务)
|
||
# ---------------------------------------------------------------------------
|
||
#
|
||
# 报表要在博主名字后面带上「账号正常 / 账号异常 / 账号安全待提升」这类状态,数据来自
|
||
# 另一套账号池服务。**由后端去取,不让浏览器直连**:token 不该发到前端,而且跨域也麻烦。
|
||
#
|
||
# 地址和 token 走环境变量;没配就静默跳过(报表照常出,只是没有状态)。
|
||
# 缓存 60 秒:报表会被反复刷新,而账号状态是分钟级的。
|
||
|
||
_ACCOUNT_STATUS_TTL_SECONDS = 60.0
|
||
_account_status_cache: Optional[Tuple[float, Dict[str, str]]] = None
|
||
|
||
|
||
def _reset_account_status_cache() -> None:
|
||
"""测试钩子:丢掉缓存,避免用例之间互相污染。"""
|
||
global _account_status_cache
|
||
_account_status_cache = None
|
||
|
||
|
||
async def _fetch_account_pool() -> List[Dict[str, Any]]:
|
||
url = os.getenv("MC_ACCOUNT_POOL_URL", "").strip()
|
||
if not url:
|
||
return []
|
||
token = os.getenv("MC_ACCOUNT_POOL_TOKEN", "").strip()
|
||
headers = {"X-Account-Token": token} if token else {}
|
||
async with httpx.AsyncClient(timeout=3.0) as client:
|
||
response = await client.get(url, headers=headers)
|
||
response.raise_for_status()
|
||
return (response.json() or {}).get("accounts") or []
|
||
|
||
|
||
async def account_status_map() -> Dict[str, str]:
|
||
"""昵称 → 账号状态。取不到就返回空 dict —— 报表不能因为外部服务挂了而打不开。"""
|
||
global _account_status_cache
|
||
|
||
now = time.monotonic()
|
||
if (
|
||
_account_status_cache is not None
|
||
and now - _account_status_cache[0] < _ACCOUNT_STATUS_TTL_SECONDS
|
||
):
|
||
return _account_status_cache[1]
|
||
|
||
try:
|
||
accounts = await _fetch_account_pool()
|
||
except Exception as exc: # noqa: BLE001 - 外部服务,任何失败都只降级
|
||
print(f"[monitor.matrix] 账号池读取失败,本次不带状态:{exc}", flush=True)
|
||
# 失败不清空旧缓存:服务抖一下不该让报表上的状态全消失。
|
||
return _account_status_cache[1] if _account_status_cache else {}
|
||
|
||
merged: Dict[str, List[str]] = {}
|
||
for account in accounts:
|
||
nickname = (account.get("nickname") or "").strip()
|
||
status = (account.get("account_status") or "").strip()
|
||
if not nickname or not status:
|
||
continue
|
||
# 同名不同号时把状态并起来,别静默只留一个。
|
||
bucket = merged.setdefault(nickname, [])
|
||
if status not in bucket:
|
||
bucket.append(status)
|
||
|
||
statuses = {name: " / ".join(values) for name, values in merged.items()}
|
||
_account_status_cache = (now, statuses)
|
||
return statuses
|
||
|
||
|
||
async def daily_tag_matrix(
|
||
session: AsyncSession,
|
||
platform: str,
|
||
days: int,
|
||
task_id: Optional[int] = None,
|
||
) -> Dict[str, Any]:
|
||
"""日期 × 博主 → 当天发出去的作品标签。给 ``/report/matrix`` 用。
|
||
|
||
**为什么分组放在 Python 里做。** MySQL 5.7 没有 PIVOT,而列数随博主变化;用 SQL
|
||
拼动态列只能靠 PREPARE 拼一整段字符串,既没法参数化,也没法在测试用的 SQLite 上
|
||
跑。这里只读两次(作品、标签),分组交给 Python —— 一个窗口内的作品量级是几百条,
|
||
代价可以忽略。
|
||
|
||
返回**长表结构**,转置由前端做:
|
||
|
||
{"dates": ["2026-10-21", ...], # 新到旧
|
||
"creators": [{"hash": ..., "name": ..., "fans": 1200,
|
||
"total_favorited": 83000,
|
||
"latest_published_at": 1780000000000}], # 按昵称排序
|
||
"cells": {"2026-10-21": {"<hash>": {
|
||
"count": 2, "tags": ["大字报", "养号"],
|
||
"likes": 120, "comments": 8, "collected": 30, "shares": 4,
|
||
"details": [{"title": "…", "url": "https://…", "tags": ["大字报"],
|
||
"likes": 80, "comments": 5, "collected": 20, "shares": 4},
|
||
{"title": "…", "url": "https://…", "tags": ["养号"],
|
||
"likes": 40, "comments": 3, "collected": 10, "shares": 0}],
|
||
# 按发布时间正序
|
||
}}}}
|
||
|
||
``likes/comments/collected/shares`` 是当天这些作品**最近一轮**指标的和;
|
||
指标未知时是 ``None``(不是 0),前端显示成「—」。``task_id`` 非空时只统计那一个任务。
|
||
"""
|
||
if task_id is not None:
|
||
# 只看一个任务。顺带把平台也校验一遍 —— 传错平台时宁可空,也别给出别的平台的数。
|
||
task_ids = list(
|
||
await session.scalars(
|
||
select(MonitorTask.id).where(
|
||
MonitorTask.id == task_id, MonitorTask.platform == platform
|
||
)
|
||
)
|
||
)
|
||
else:
|
||
task_ids = await platform_task_ids(session, platform)
|
||
|
||
empty = {
|
||
"platform": platform,
|
||
"days": days,
|
||
"task_id": task_id,
|
||
"dates": [],
|
||
"creators": [],
|
||
"cells": {},
|
||
}
|
||
if not task_ids:
|
||
return empty
|
||
|
||
# 日期列**按完整区间生成**,不是只取「有作品的那几天」。否则某天断更,那一列会
|
||
# 悄无声息地消失,看图的人会以为是漏采 —— 空白本身也是信息。
|
||
first_day = datetime.now().replace(
|
||
hour=0, minute=0, second=0, microsecond=0
|
||
) - timedelta(days=max(1, days) - 1)
|
||
dates = [
|
||
(first_day + timedelta(days=offset)).strftime("%Y-%m-%d")
|
||
for offset in range(max(1, days))
|
||
][::-1]
|
||
since = int(first_day.timestamp() * 1000)
|
||
|
||
notes = (
|
||
await session.execute(
|
||
select(
|
||
MonitorNote.task_id,
|
||
MonitorNote.note_id,
|
||
MonitorNote.title,
|
||
MonitorNote.note_url,
|
||
MonitorNote.creator_hash,
|
||
MonitorNote.creator_name,
|
||
MonitorNote.published_at,
|
||
)
|
||
.where(
|
||
MonitorNote.task_id.in_(task_ids),
|
||
MonitorNote.published_at.is_not(None),
|
||
MonitorNote.published_at >= since,
|
||
)
|
||
.order_by(MonitorNote.published_at.desc())
|
||
)
|
||
).all()
|
||
|
||
note_ids = {row.note_id for row in notes}
|
||
|
||
# 标签一次取完,按 note_id 归组;顺序跟词表里的 sort_order 一致。
|
||
tags_by_note: Dict[str, List[str]] = {}
|
||
tag_order: Dict[str, int] = {}
|
||
if note_ids:
|
||
tag_rows = (
|
||
await session.execute(
|
||
select(MonitorNoteTag.note_id, MonitorTag.name, MonitorTag.sort_order)
|
||
.join(MonitorTag, MonitorTag.id == MonitorNoteTag.tag_id)
|
||
.where(
|
||
MonitorNoteTag.platform == platform,
|
||
MonitorNoteTag.note_id.in_(note_ids),
|
||
)
|
||
.order_by(MonitorTag.sort_order, MonitorTag.id)
|
||
)
|
||
).all()
|
||
for note_id, name, sort_order in tag_rows:
|
||
tags_by_note.setdefault(note_id, []).append(name)
|
||
tag_order.setdefault(name, sort_order)
|
||
|
||
# 指标:每篇作品取**最近一轮**(run_id 最大)。没有指标行的作品不参与求和 ——
|
||
# 未知和 0 是两回事,格子的提示里会显示成「—」而不是「0」。
|
||
metric_rows = (
|
||
await session.execute(
|
||
select(
|
||
MonitorNoteMetric.task_id,
|
||
MonitorNoteMetric.note_id,
|
||
MonitorNoteMetric.run_id,
|
||
MonitorNoteMetric.liked_count,
|
||
MonitorNoteMetric.comment_count,
|
||
MonitorNoteMetric.collected_count,
|
||
MonitorNoteMetric.share_count,
|
||
).where(
|
||
MonitorNoteMetric.task_id.in_(task_ids),
|
||
MonitorNoteMetric.note_id.in_(note_ids),
|
||
)
|
||
)
|
||
).all()
|
||
latest_metric: Dict[tuple, Any] = {}
|
||
for metric in metric_rows:
|
||
key = (metric.task_id, metric.note_id)
|
||
current = latest_metric.get(key)
|
||
if current is None or metric.run_id > current.run_id:
|
||
latest_metric[key] = metric
|
||
|
||
# 博主名单取**账号快照 ∪ 作品**,和界面一致。只在快照里出现的号也要占一行 ——
|
||
# 典型是资料读成纯数字昵称、作品数为 0 的那几个;只从作品里取的话它们会整行消失。
|
||
stat_rows = (
|
||
await session.execute(
|
||
select(
|
||
MonitorCreatorStat.creator_hash,
|
||
MonitorCreatorStat.nickname,
|
||
MonitorCreatorStat.captured_at,
|
||
MonitorCreatorStat.fans,
|
||
MonitorCreatorStat.total_favorited,
|
||
MonitorCreatorStat.latest_published_at,
|
||
).where(
|
||
MonitorCreatorStat.task_id.in_(task_ids),
|
||
MonitorCreatorStat.creator_hash != "",
|
||
)
|
||
)
|
||
).all()
|
||
latest_nickname: Dict[str, tuple] = {}
|
||
# 粉丝数是给博主列显示用的「最近一次已知值」。某一轮没解析出来(None)不让它把
|
||
# 之前的好数字盖掉 —— 一个号有几千粉丝,不会因为这一轮没读到就变成不知道。
|
||
latest_fans: Dict[str, tuple] = {}
|
||
# 主页上的「获赞总数」,和粉丝数一样取最近一次读到的值。
|
||
latest_likes: Dict[str, tuple] = {}
|
||
# 主页第一条(最新)视频的发布时间。采集时问过主页,这条可能不在监控目标里。
|
||
latest_video: Dict[str, tuple] = {}
|
||
for stat in stat_rows:
|
||
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]:
|
||
latest_fans[stat.creator_hash] = (stat.fans, stat.captured_at)
|
||
if stat.total_favorited is not None:
|
||
current_likes = latest_likes.get(stat.creator_hash)
|
||
if current_likes is None or stat.captured_at > current_likes[1]:
|
||
latest_likes[stat.creator_hash] = (
|
||
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)」。实测线上有两个号就是这么丢的名字。
|
||
if not stat.nickname:
|
||
continue
|
||
current = latest_nickname.get(stat.creator_hash)
|
||
if current is None or stat.captured_at > current[1]:
|
||
latest_nickname[stat.creator_hash] = (stat.nickname, stat.captured_at)
|
||
|
||
known: Dict[str, str] = {}
|
||
for row in notes:
|
||
key = row.creator_hash or f"note:{row.note_id}"
|
||
if row.creator_name:
|
||
known[key] = row.creator_name
|
||
else:
|
||
known.setdefault(key, f"未知({key[:6]})")
|
||
# 快照里的名字优先于作品里的 —— 它来自资料接口,是最新的。
|
||
for hash_, (name, _captured) in latest_nickname.items():
|
||
known[hash_] = name
|
||
|
||
cells: Dict[str, Dict[str, Dict[str, Any]]] = {}
|
||
# 同一个作品可能挂在多个任务下(monitor_note 的唯一键是 (task_id, note_id)),
|
||
# 不按 note_id 去重会把计数和指标都翻倍。
|
||
seen: set = set()
|
||
|
||
for row in notes:
|
||
note_key = (row.creator_hash, row.note_id)
|
||
if note_key in seen:
|
||
continue
|
||
seen.add(note_key)
|
||
|
||
day = datetime.fromtimestamp((row.published_at or 0) / 1000).strftime("%Y-%m-%d")
|
||
creator_key = row.creator_hash or f"note:{row.note_id}"
|
||
|
||
bucket = cells.setdefault(day, {}).setdefault(
|
||
creator_key,
|
||
{
|
||
"count": 0,
|
||
"tags": [],
|
||
"likes": None,
|
||
"comments": None,
|
||
"collected": None,
|
||
"shares": None,
|
||
# 逐条明细:并集看不出「哪个标签属于哪条视频」,这里补上。
|
||
"details": [],
|
||
},
|
||
)
|
||
bucket["count"] += 1
|
||
metric = latest_metric.get((row.task_id, row.note_id))
|
||
# 逐条明细带**各自的**指标。一格合并了多条时,并集只说明「这天整体怎么样」,
|
||
# 哪条是爆款要看每条自己的数字 —— 悬停提示里直接看得到。
|
||
bucket["details"].append(
|
||
{
|
||
"title": row.title or row.note_id,
|
||
# 点标题能直接跳过去。链接是入库时按平台拼好的,这里原样带出来。
|
||
"url": row.note_url or "",
|
||
"tags": list(tags_by_note.get(row.note_id, [])),
|
||
"likes": metric.liked_count if metric is not None else None,
|
||
"comments": metric.comment_count if metric is not None else None,
|
||
"collected": metric.collected_count if metric is not None else None,
|
||
"shares": metric.share_count if metric is not None else None,
|
||
}
|
||
)
|
||
for tag in tags_by_note.get(row.note_id, []):
|
||
if tag not in bucket["tags"]:
|
||
bucket["tags"].append(tag)
|
||
|
||
if metric is not None:
|
||
for column, key in (
|
||
("liked_count", "likes"),
|
||
("comment_count", "comments"),
|
||
("collected_count", "collected"),
|
||
("share_count", "shares"),
|
||
):
|
||
value = getattr(metric, column)
|
||
if value is not None:
|
||
bucket[key] = (bucket[key] or 0) + value
|
||
|
||
# 一个格子可能合并了多天里的多条作品、多个标签。统一按**词表顺序**排 ——
|
||
# 否则同样的数据,换个遍历顺序就换了标签顺序,看起来像数据变了。
|
||
for day_cells in cells.values():
|
||
for bucket in day_cells.values():
|
||
bucket["tags"].sort(key=lambda name: tag_order.get(name, 10**6))
|
||
# 作品是按发布时间倒序取回来的,明细按时间正序更好读(1、2、3…)。
|
||
bucket["details"].reverse()
|
||
|
||
# 兜底:库里这个博主**已有作品里最新的**发布时间。首选是采集时从主页拿到的
|
||
# 「第一条视频」(它可能根本不在监控目标里),主页那次没问到时才用它。
|
||
tracked_rows = (
|
||
await session.execute(
|
||
select(MonitorNote.creator_hash, func.max(MonitorNote.published_at))
|
||
.where(
|
||
MonitorNote.task_id.in_(task_ids),
|
||
MonitorNote.published_at.is_not(None),
|
||
MonitorNote.creator_hash != "",
|
||
)
|
||
.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
|
||
}
|
||
|
||
creators = [
|
||
{
|
||
"hash": hash_,
|
||
"name": name,
|
||
# 没有账号快照的博主(作品模式刚导入、还没跑过一轮)就是 None,
|
||
# 前端据此不画那个数字,而不是显示 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,
|
||
),
|
||
}
|
||
for hash_, name in known.items()
|
||
]
|
||
creators.sort(key=lambda item: item["name"])
|
||
|
||
# 账号池状态只有抖音那套池子有;取不到就是空串,前端不加括号。
|
||
if platform == adapters.PLATFORM_DY:
|
||
statuses = await account_status_map()
|
||
for creator in creators:
|
||
creator["account_status"] = statuses.get(creator["name"].strip(), "")
|
||
|
||
return {
|
||
"platform": platform,
|
||
"days": days,
|
||
"task_id": task_id,
|
||
"dates": dates,
|
||
"creators": creators,
|
||
"cells": cells,
|
||
}
|