feat(monitor): 抖音多身份池 —— 目标按登录态串行分片
把 44 个博主打散给多个抖音号,降低**单个账号**每轮的请求量(约 35 个博主后开始
出现限流是已知现象)。**默认串行,不是并行**:同一个出口 IP 上并发多个 cookie,
平台视角是一台设备在不停换访客,比单账号高频更容易被判异常。并发数做成了设置项,
但要先给每个账号配独立出口 IP 再考虑调大。
新增:
* `monitor_identity` 表:label / source(stored|browser) / cookie / **user_agent** /
client_hints / status / enabled / 冷却字段。cookie 与 UA 必须成套存 —— a_bogus
把 UA 算进签名,空 UA 签出来的请求一定被挡。
* `api/monitor/identities.py`:可用性判定、解析、**Rendezvous Hashing 分片**
(加一个身份只迁移约 1/(n+1) 的目标)、健康状态与指数退避冷却。
* `douyin_api`:四个接口都接受显式 `identity`,走身份池时**不再回读浏览器**(否则
浏览器里的 cookie 会把指定账号顶掉);新增 `shared_fingerprint()` 给粘贴 cookie
的身份兜底 UA。
* `douyin_fetch.collect`:按身份分片执行,分片之间默认串行、可配切换间隔;落盘前
按 note_id 去重(并发时两个分片可能刷到同一件作品)。
* `runner`:池模式下加载身份、不足 `identity_min_available` 就快速失败(不产生请求),
结束后按各自分片结果回写健康。
* 设置项:identity_mode / identity_min_available / identity_switch_delay_sec /
identity_concurrency。
* API:GET/POST/PATCH/DELETE `/api/monitor/identities` + `/{id}/check`(真请求一次,
没有可探测博主时退化成格式检查并在 verified 里标 false)。
* 前端:设置页(仅抖音)新增「多身份(分片采集)」面板。
测试 9 条新增:分片确定性与覆盖、加身份只迁移一小部分、缺 UA/cookie 拒绝、
两次失败进冷却、成功清零、冷却中不可用、采集按身份分片。
This commit is contained in:
@@ -144,6 +144,51 @@ SETTING_SPECS: List[SettingSpec] = [
|
||||
minimum=0,
|
||||
maximum=600,
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_mode",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_STR,
|
||||
label="多身份采集",
|
||||
help=(
|
||||
"single=只用一份登录态(默认);pool=把目标分给身份池里的多个账号。"
|
||||
"池模式是**串行分片**,不是并行 —— 同一个出口 IP 上并发多个 cookie 更容易被风控。"
|
||||
),
|
||||
default="single",
|
||||
choices=["single", "pool"],
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_min_available",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_INT,
|
||||
label="最少可用身份数",
|
||||
help="池模式下可用身份少于这个数就不跑这一轮 —— 别拿一个号硬扛全部目标。",
|
||||
default=1,
|
||||
minimum=1,
|
||||
maximum=20,
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_switch_delay_sec",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_INT,
|
||||
label="身份切换间隔(秒)",
|
||||
help="换下一个账号之前等多久。同一出口上连续切换登录态更像异常流量。",
|
||||
default=30,
|
||||
minimum=0,
|
||||
maximum=600,
|
||||
),
|
||||
SettingSpec(
|
||||
name="identity_concurrency",
|
||||
scope=SCOPE_PLATFORM,
|
||||
type=TYPE_INT,
|
||||
label="身份并发数",
|
||||
help=(
|
||||
"默认 1(串行)。**只有给每个账号配了独立出口 IP 才建议调大** —— "
|
||||
"同一 IP 上并发多个身份,平台视角是一台设备在不停换访客。"
|
||||
),
|
||||
default=1,
|
||||
minimum=1,
|
||||
maximum=8,
|
||||
),
|
||||
SettingSpec(
|
||||
name="enable_ip_proxy",
|
||||
scope=SCOPE_PLATFORM,
|
||||
|
||||
@@ -101,6 +101,9 @@ class BrowserIdentity:
|
||||
cookie: str
|
||||
user_agent: str
|
||||
client_hints: Dict[str, str]
|
||||
# 身份池里的标识:``"browser"`` / ``"id:<n>"`` / ``"legacy"``。只用于日志与分片,
|
||||
# 不参与请求。放在最后且有默认值,现有构造点不用改。
|
||||
identity_key: str = "legacy"
|
||||
|
||||
def headers(self) -> Dict[str, str]:
|
||||
headers = {
|
||||
@@ -299,6 +302,19 @@ def forget_identity() -> None:
|
||||
_identity_cache = None
|
||||
|
||||
|
||||
async def shared_fingerprint() -> Tuple[str, Dict[str, str]]:
|
||||
"""只从浏览器读 UA + client hints,**不要它的 cookie**。
|
||||
|
||||
给「粘贴 cookie」的身份兜底:cookie 来自哪个浏览器我们不知道,至少让 UA 和
|
||||
``sec-ch-ua`` 成套。读不到返回空 —— 调用方应当拒绝创建没有 UA 的身份,因为
|
||||
评论接口的 ``a_bogus`` 要拿 UA 去签名,空 UA 签出来的请求一定被挡。
|
||||
"""
|
||||
identity = await _read_browser()
|
||||
if identity is None:
|
||||
return "", {}
|
||||
return identity.user_agent, identity.client_hints
|
||||
|
||||
|
||||
def _cookie_header(cookie: str) -> str:
|
||||
"""把 ``a=1; b=2`` 形式的 cookie 串规整成请求头用的形状。"""
|
||||
pairs = []
|
||||
@@ -427,14 +443,19 @@ def normalize_aweme(aweme: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
|
||||
async def author_videos(
|
||||
sec_user_id: str, count: int = MAX_PAGE_SIZE, *, cookie: str = ""
|
||||
sec_user_id: str,
|
||||
count: int = MAX_PAGE_SIZE,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""某个博主最新发布的作品(按发布时间倒序),已翻译成 store 的键名。
|
||||
|
||||
用 ``sec_user_id`` 而不是数字 uid:监控任务里存的就是主页链接里的那段 sec_uid,
|
||||
而且这个接口两种都收(爬虫那边用的也是 sec_user_id)。
|
||||
"""
|
||||
identity = await browser_identity(cookie)
|
||||
# 身份池传进来的身份直接用 —— 不要再去读浏览器,那会把别的账号的 cookie 顶进来。
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有")
|
||||
|
||||
@@ -458,13 +479,18 @@ async def author_videos(
|
||||
return [normalize_aweme(aweme) for aweme in awemes]
|
||||
|
||||
|
||||
async def video_detail(aweme_id: str, *, cookie: str = "") -> Dict[str, Any]:
|
||||
async def video_detail(
|
||||
aweme_id: str,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""单条作品的详情,已翻译成 store 的键名。
|
||||
|
||||
这个接口**没有**被那道真校验挡着(实测 200 / 45425 字节),所以在拿不到作品列表时,
|
||||
它是「刷新已知作品指标」的唯一途径。
|
||||
"""
|
||||
identity = await browser_identity(cookie)
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有")
|
||||
|
||||
@@ -481,9 +507,14 @@ async def video_detail(aweme_id: str, *, cookie: str = "") -> Dict[str, Any]:
|
||||
return normalize_aweme(aweme)
|
||||
|
||||
|
||||
async def author_profile(sec_user_id: str, *, cookie: str = "") -> Dict[str, Any]:
|
||||
async def author_profile(
|
||||
sec_user_id: str,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""博主主页指标:昵称 / 粉丝数 / 总获赞 / 作品数。"""
|
||||
identity = await browser_identity(cookie)
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用:浏览器里没有会话,库里的 cookie 也没有")
|
||||
|
||||
@@ -541,14 +572,18 @@ def normalize_comment(comment: Dict[str, Any], aweme_id: str) -> Dict[str, Any]:
|
||||
|
||||
|
||||
async def video_comments(
|
||||
aweme_id: str, count: int = 20, *, cookie: str = ""
|
||||
aweme_id: str,
|
||||
count: int = 20,
|
||||
*,
|
||||
cookie: str = "",
|
||||
identity: Optional[BrowserIdentity] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""一条作品的评论,翻译成 store 的评论键名。
|
||||
|
||||
刻意不带 ``sub_comment_count`` / ``parent_comment_id`` 的猜测值 —— 接口给了就用,
|
||||
没给就留空,不编。
|
||||
"""
|
||||
identity = await browser_identity(cookie)
|
||||
identity = identity or await browser_identity(cookie)
|
||||
if not _has_session(identity.cookie):
|
||||
raise DouyinApiError("抖音登录态不可用")
|
||||
|
||||
|
||||
+149
-11
@@ -29,6 +29,7 @@
|
||||
—— 重采样、差分、事件、通知、报表全都照旧。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -54,12 +55,19 @@ async def collect(
|
||||
targets: Sequence[Any],
|
||||
known_aweme_ids: Iterable[str] = (),
|
||||
cookie: str = "",
|
||||
identities: Sequence[Any] = (),
|
||||
concurrency: int = 1,
|
||||
switch_delay_seconds: float = 0.0,
|
||||
) -> Dict[str, Any]:
|
||||
"""跑一轮抖音采集,把产物写进 ``out_dir`` 下 store 那个目录里。
|
||||
|
||||
参数是散的、不收 ORM 对象:调用方那边 ``task`` 在会话关掉之后就 detached 了,
|
||||
传对象进来迟早会踩到「属性已过期」。
|
||||
|
||||
``identities`` 非空时进入**身份池模式**:目标按 Rendezvous Hashing 分给各个身份,
|
||||
逐个分片执行。默认串行 —— 同一个出口 IP 上并发多个 cookie 比单账号高频更可疑;
|
||||
``concurrency`` 只是留了个口子,有独立出口 IP 之前别调大。
|
||||
|
||||
**不抛异常**:失败也把(可能为空的)产物落下去,并把原因放进 ``errors`` 交给调用方。
|
||||
让调用方去决定这是「一轮正常但没数据」还是「一轮失败」—— 这个判断不该藏在这里。
|
||||
"""
|
||||
@@ -69,12 +77,117 @@ async def collect(
|
||||
# 只有博主模式才有 —— 作品模式的目标是一件作品,没有"这个博主是谁"可问。
|
||||
profiles: List[Dict[str, Any]] = []
|
||||
errors: List[str] = []
|
||||
shards: List[Dict[str, Any]] = []
|
||||
|
||||
# **整个 collect 只去重一次的、跨目标的集合**:退化路径会把「库里已知的全部作品」
|
||||
# 在每个目标下都刷一遍,多个目标就会出现同一件作品好几条记录 —— 而一对一快照的
|
||||
# 唯一键是 (task_id, note_id, run_id),同一条作品在一轮里出现两次会直接撞键。
|
||||
seen_aweme: set = set()
|
||||
|
||||
if identities:
|
||||
from . import identities as identity_pool
|
||||
|
||||
plan = identity_pool.assign(targets, [item.identity_key for item in identities])
|
||||
batches = [
|
||||
(item, plan[item.identity_key])
|
||||
for item in identities
|
||||
if plan[item.identity_key]
|
||||
]
|
||||
|
||||
async def run_batch(identity, shard):
|
||||
return await _collect_batch(
|
||||
shard,
|
||||
identity=identity,
|
||||
mode=mode,
|
||||
limit=limit,
|
||||
want_comments=want_comments,
|
||||
comment_limit=comment_limit,
|
||||
cookie=cookie,
|
||||
known_aweme_ids=known_aweme_ids,
|
||||
seen_aweme=seen_aweme,
|
||||
)
|
||||
|
||||
if concurrency > 1 and len(batches) > 1:
|
||||
results = await asyncio.gather(*(run_batch(i, s) for i, s in batches))
|
||||
else:
|
||||
results = []
|
||||
for index, (identity, shard) in enumerate(batches):
|
||||
results.append(await run_batch(identity, shard))
|
||||
# 换账号之间留一点空档:连续在同一个 IP 上换登录态更像异常流量。
|
||||
if index < len(batches) - 1 and switch_delay_seconds > 0:
|
||||
await asyncio.sleep(switch_delay_seconds)
|
||||
|
||||
for (identity, shard), result in zip(batches, results):
|
||||
notes.extend(result["notes"])
|
||||
comments.extend(result["comments"])
|
||||
profiles.extend(result["profiles"])
|
||||
errors.extend(result["errors"])
|
||||
shards.append(
|
||||
{
|
||||
"key": identity.identity_key,
|
||||
"targets": result["targets"],
|
||||
"notes": len(result["notes"]),
|
||||
"comments": len(result["comments"]),
|
||||
"errors": list(result["errors"]),
|
||||
}
|
||||
)
|
||||
else:
|
||||
result = await _collect_batch(
|
||||
targets,
|
||||
identity=None,
|
||||
mode=mode,
|
||||
limit=limit,
|
||||
want_comments=want_comments,
|
||||
comment_limit=comment_limit,
|
||||
cookie=cookie,
|
||||
known_aweme_ids=known_aweme_ids,
|
||||
seen_aweme=seen_aweme,
|
||||
)
|
||||
notes.extend(result["notes"])
|
||||
comments.extend(result["comments"])
|
||||
profiles.extend(result["profiles"])
|
||||
errors.extend(result["errors"])
|
||||
|
||||
# 并发跑分片时,两个分片可能各自刷新到同一件已知作品 —— 落盘前去一次重,
|
||||
# 否则唯一键 (task_id, note_id, run_id) 会撞。
|
||||
deduped: List[Dict[str, Any]] = []
|
||||
seen_note_ids: set = set()
|
||||
for note in notes:
|
||||
note_id = note.get("aweme_id")
|
||||
if note_id and note_id in seen_note_ids:
|
||||
continue
|
||||
if note_id:
|
||||
seen_note_ids.add(note_id)
|
||||
deduped.append(note)
|
||||
|
||||
jsonl_dir = _write_artifacts(out_dir, platform, mode, deduped, comments, profiles)
|
||||
return {
|
||||
"notes": len(deduped),
|
||||
"comments": len(comments),
|
||||
"errors": errors,
|
||||
"jsonl_dir": str(jsonl_dir),
|
||||
"shards": shards,
|
||||
}
|
||||
|
||||
|
||||
async def _collect_batch(
|
||||
targets: Sequence[Any],
|
||||
*,
|
||||
identity: Any,
|
||||
mode: str,
|
||||
limit: int,
|
||||
want_comments: bool,
|
||||
comment_limit: int,
|
||||
cookie: str,
|
||||
known_aweme_ids: Iterable[str],
|
||||
seen_aweme: set,
|
||||
) -> Dict[str, Any]:
|
||||
"""一个身份负责的那一片目标。错误只往自己的列表里记,由调用方合并。"""
|
||||
notes: List[Dict[str, Any]] = []
|
||||
comments: List[Dict[str, Any]] = []
|
||||
profiles: List[Dict[str, Any]] = []
|
||||
errors: List[str] = []
|
||||
|
||||
for target in targets:
|
||||
external_id = target.external_id
|
||||
|
||||
@@ -84,15 +197,27 @@ async def collect(
|
||||
# 刷新库里已知的作品(新作品发现不了)。
|
||||
if mode == MODE_NOTE:
|
||||
try:
|
||||
videos = [await douyin_api.video_detail(external_id, cookie=cookie)]
|
||||
videos = [
|
||||
await douyin_api.video_detail(
|
||||
external_id, cookie=cookie, identity=identity
|
||||
)
|
||||
]
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取作品 {external_id} 失败:{exc}")
|
||||
videos = []
|
||||
else:
|
||||
videos = await _creator_works(
|
||||
external_id, limit, known_aweme_ids, seen_aweme, cookie, errors
|
||||
external_id,
|
||||
limit,
|
||||
known_aweme_ids,
|
||||
seen_aweme,
|
||||
cookie,
|
||||
errors,
|
||||
identity,
|
||||
)
|
||||
profile = await _creator_profile(
|
||||
external_id, videos, cookie, errors, identity
|
||||
)
|
||||
profile = await _creator_profile(external_id, videos, cookie, errors)
|
||||
if profile is not None:
|
||||
profiles.append(profile)
|
||||
|
||||
@@ -107,18 +232,21 @@ async def collect(
|
||||
try:
|
||||
comments.extend(
|
||||
await douyin_api.video_comments(
|
||||
aweme_id, count=comment_limit, cookie=cookie
|
||||
aweme_id,
|
||||
count=comment_limit,
|
||||
cookie=cookie,
|
||||
identity=identity,
|
||||
)
|
||||
)
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取作品 {aweme_id} 的评论失败:{exc}")
|
||||
|
||||
jsonl_dir = _write_artifacts(out_dir, platform, mode, notes, comments, profiles)
|
||||
return {
|
||||
"notes": len(notes),
|
||||
"comments": len(comments),
|
||||
"notes": notes,
|
||||
"comments": comments,
|
||||
"profiles": profiles,
|
||||
"errors": errors,
|
||||
"jsonl_dir": str(jsonl_dir),
|
||||
"targets": len(targets),
|
||||
}
|
||||
|
||||
|
||||
@@ -127,6 +255,7 @@ async def _creator_profile(
|
||||
videos: Sequence[Dict[str, Any]],
|
||||
cookie: str,
|
||||
errors: List[str],
|
||||
identity: Any = None,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""问一次博主的账号级指标。拿不到就算了 —— **不能因为顺手的附加信息失败,
|
||||
就把这一轮本来采到的作品也判成失败。**
|
||||
@@ -137,7 +266,9 @@ async def _creator_profile(
|
||||
那种情况下也只剩它了。
|
||||
"""
|
||||
try:
|
||||
profile = await douyin_api.author_profile(sec_user_id, cookie=cookie)
|
||||
profile = await douyin_api.author_profile(
|
||||
sec_user_id, cookie=cookie, identity=identity
|
||||
)
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取博主 {sec_user_id} 的资料失败:{exc}")
|
||||
return None
|
||||
@@ -158,6 +289,7 @@ async def _creator_works(
|
||||
seen_aweme: set,
|
||||
cookie: str,
|
||||
errors: List[str],
|
||||
identity: Any = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""一个博主的作品:先要列表,列表被挡时退化成刷新已知作品。
|
||||
|
||||
@@ -165,7 +297,9 @@ async def _creator_works(
|
||||
带上 dummy 值回 200 + 空 body。所以这里拿不到**新**作品,只能保住已知的。
|
||||
"""
|
||||
try:
|
||||
return await douyin_api.author_videos(sec_user_id, count=limit, cookie=cookie)
|
||||
return await douyin_api.author_videos(
|
||||
sec_user_id, count=limit, cookie=cookie, identity=identity
|
||||
)
|
||||
except douyin_api.DouyinApiError as exc:
|
||||
errors.append(f"拉取博主 {sec_user_id} 的作品列表失败:{exc}")
|
||||
|
||||
@@ -174,7 +308,11 @@ async def _creator_works(
|
||||
if aweme_id in seen_aweme:
|
||||
continue
|
||||
try:
|
||||
refreshed.append(await douyin_api.video_detail(aweme_id, cookie=cookie))
|
||||
refreshed.append(
|
||||
await douyin_api.video_detail(
|
||||
aweme_id, cookie=cookie, identity=identity
|
||||
)
|
||||
)
|
||||
except douyin_api.DouyinApiError as detail_exc:
|
||||
errors.append(f"刷新作品 {aweme_id} 失败:{detail_exc}")
|
||||
return refreshed
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份池:多个登录态之间的选取、分片与健康状态。
|
||||
|
||||
**为什么是「串行分片」而不是「并行抓取」。** 抖音按 *账号 + IP + 设备指纹* 联合判定,
|
||||
在同一个出口 IP 上并发跑多个 cookie,比单账号高频请求更容易被判成异常 —— 平台视角是
|
||||
一台设备在不停换访客。所以默认一次只跑一个身份,靠**把目标分给不同账号**来降低每个
|
||||
账号的请求量;并发数由调用方决定(默认 1),有独立出口 IP 之前别调大。
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any, Dict, List, Optional, Sequence
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from . import douyin_api
|
||||
from .models import (
|
||||
IDENTITY_SOURCE_BROWSER,
|
||||
IDENTITY_STATUS_COOLDOWN,
|
||||
IDENTITY_STATUS_EXPIRED,
|
||||
IDENTITY_STATUS_OK,
|
||||
MonitorIdentity,
|
||||
)
|
||||
|
||||
IDENTITY_KEY_BROWSER = "browser"
|
||||
# 连续失败几次才进冷却。一次失败可能只是网络抖动,不值得把账号停半小时。
|
||||
COOLDOWN_AFTER_FAILURES = 2
|
||||
COOLDOWN_BASE_MS = 30 * 60_000
|
||||
COOLDOWN_MAX_MS = 180 * 60_000
|
||||
|
||||
|
||||
def key_for(row: MonitorIdentity) -> str:
|
||||
"""身份在本轮里的稳定标识。``browser`` 只有一个,其它按行 id。"""
|
||||
if row.source == IDENTITY_SOURCE_BROWSER:
|
||||
return IDENTITY_KEY_BROWSER
|
||||
return f"id:{row.id}"
|
||||
|
||||
|
||||
def is_available(row: MonitorIdentity, now: Optional[int] = None) -> bool:
|
||||
if not row.enabled or row.status == IDENTITY_STATUS_EXPIRED:
|
||||
return False
|
||||
now = now or get_current_timestamp()
|
||||
return not row.cooldown_until or row.cooldown_until <= now
|
||||
|
||||
|
||||
async def load_available(
|
||||
session: AsyncSession, platform: str, now: Optional[int] = None
|
||||
) -> List[MonitorIdentity]:
|
||||
now = now or get_current_timestamp()
|
||||
rows = (
|
||||
await session.scalars(
|
||||
select(MonitorIdentity)
|
||||
.where(MonitorIdentity.platform == platform)
|
||||
.order_by(MonitorIdentity.id)
|
||||
)
|
||||
).all()
|
||||
return [row for row in rows if is_available(row, now)]
|
||||
|
||||
|
||||
async def resolve(row: MonitorIdentity) -> douyin_api.BrowserIdentity:
|
||||
"""把一行身份变成请求真正要用的那份。
|
||||
|
||||
失败抛 ``ValueError``(消息直接给人看),由调用方决定是跳过这个身份还是整轮失败。
|
||||
"""
|
||||
if row.source == IDENTITY_SOURCE_BROWSER:
|
||||
identity = await douyin_api.browser_identity(force=True)
|
||||
if "sessionid=" not in (identity.cookie or ""):
|
||||
raise ValueError("浏览器里没有可用的抖音登录态")
|
||||
return douyin_api.BrowserIdentity(
|
||||
cookie=identity.cookie,
|
||||
user_agent=identity.user_agent,
|
||||
client_hints=identity.client_hints,
|
||||
identity_key=key_for(row),
|
||||
)
|
||||
|
||||
try:
|
||||
hints = json.loads(row.client_hints or "{}")
|
||||
except ValueError:
|
||||
hints = {}
|
||||
if not row.cookie.strip():
|
||||
raise ValueError("这份身份没有 cookie")
|
||||
if not row.user_agent.strip():
|
||||
# 评论接口的 a_bogus 把 UA 算进去,空 UA 签出来的请求一定被挡。
|
||||
raise ValueError("这份身份没有 UA —— 评论签名要用它")
|
||||
return douyin_api.BrowserIdentity(
|
||||
cookie=row.cookie,
|
||||
user_agent=row.user_agent,
|
||||
client_hints=hints if isinstance(hints, dict) else {},
|
||||
identity_key=key_for(row),
|
||||
)
|
||||
|
||||
|
||||
def _score(identity_key: str, external_id: str) -> int:
|
||||
digest = hashlib.blake2b(
|
||||
f"{identity_key}:{external_id}".encode("utf-8"), digest_size=8
|
||||
).digest()
|
||||
return int.from_bytes(digest, "big")
|
||||
|
||||
|
||||
def assign(targets: Sequence[Any], keys: Sequence[str]) -> Dict[str, List[Any]]:
|
||||
"""用 Rendezvous Hashing 把目标分给身份。
|
||||
|
||||
比取模好在:加一个身份时只有约 1/(n+1) 的目标会迁移,而不是全部重排;同一组
|
||||
身份和目标的分配结果是确定的,便于排查和 A/B。
|
||||
|
||||
身份列表为空时返回空 —— 调用方应当先确保至少有一个可用身份。
|
||||
"""
|
||||
buckets: Dict[str, List[Any]] = {key: [] for key in keys}
|
||||
if not keys:
|
||||
return buckets
|
||||
for target in targets:
|
||||
external = getattr(target, "external_id", None) or str(target)
|
||||
best = max(keys, key=lambda key: _score(key, external))
|
||||
buckets[best].append(target)
|
||||
return buckets
|
||||
|
||||
|
||||
async def record_result(
|
||||
session: AsyncSession,
|
||||
row: MonitorIdentity,
|
||||
*,
|
||||
ok: bool,
|
||||
error: str = "",
|
||||
now: Optional[int] = None,
|
||||
) -> None:
|
||||
"""一轮分片跑完之后更新健康状态。
|
||||
|
||||
**空 body / 403 只算限流,不算 cookie 失效** —— 前者冷却后还能用,后者才需要
|
||||
人工重新粘贴。这一层区分放在调用方:``ok=False`` 走冷却,``expired=True`` 才置
|
||||
``expired``。
|
||||
"""
|
||||
now = now or get_current_timestamp()
|
||||
row.last_checked_at = now
|
||||
|
||||
if ok:
|
||||
row.status = IDENTITY_STATUS_OK
|
||||
row.consecutive_failures = 0
|
||||
row.cooldown_until = None
|
||||
row.last_ok_at = now
|
||||
row.last_error = None
|
||||
row.updated_at = now
|
||||
return
|
||||
|
||||
row.consecutive_failures = (row.consecutive_failures or 0) + 1
|
||||
row.last_error = (error or "")[:500]
|
||||
row.updated_at = now
|
||||
if row.consecutive_failures >= COOLDOWN_AFTER_FAILURES:
|
||||
delay = min(
|
||||
COOLDOWN_BASE_MS * (2 ** (row.consecutive_failures - COOLDOWN_AFTER_FAILURES)),
|
||||
COOLDOWN_MAX_MS,
|
||||
)
|
||||
row.status = IDENTITY_STATUS_COOLDOWN
|
||||
row.cooldown_until = now + delay
|
||||
|
||||
|
||||
def mark_expired(row: MonitorIdentity, error: str, now: Optional[int] = None) -> None:
|
||||
"""明确的登录态失效:需要人工重新粘贴,冷却没用。"""
|
||||
now = now or get_current_timestamp()
|
||||
row.status = IDENTITY_STATUS_EXPIRED
|
||||
row.last_checked_at = now
|
||||
row.last_error = (error or "")[:500]
|
||||
row.updated_at = now
|
||||
|
||||
|
||||
def to_dict(row: MonitorIdentity) -> Dict[str, Any]:
|
||||
"""对外形状。**绝不含 cookie 原文**,只给 has_cookie。"""
|
||||
return {
|
||||
"id": row.id,
|
||||
"platform": row.platform,
|
||||
"label": row.label,
|
||||
"source": row.source,
|
||||
"has_cookie": bool(row.cookie),
|
||||
"user_agent": row.user_agent,
|
||||
"status": row.status,
|
||||
"enabled": row.enabled,
|
||||
"consecutive_failures": row.consecutive_failures,
|
||||
"cooldown_until": row.cooldown_until,
|
||||
"last_checked_at": row.last_checked_at,
|
||||
"last_ok_at": row.last_ok_at,
|
||||
"last_error": row.last_error,
|
||||
}
|
||||
@@ -503,6 +503,61 @@ SETTING_UPSTREAM_STATE = "system.upstream_check_state"
|
||||
# 更新推一遍,直到有人去合并为止;而上游真又动了的时候应该再推一次。
|
||||
SETTING_UPSTREAM_NOTIFIED_TIP = "system.upstream_notified_tip"
|
||||
|
||||
# --- 身份池 -----------------------------------------------------------------
|
||||
|
||||
IDENTITY_STATUS_OK = "ok"
|
||||
IDENTITY_STATUS_COOLDOWN = "cooldown"
|
||||
IDENTITY_STATUS_EXPIRED = "expired"
|
||||
IDENTITY_STATUS_DISABLED = "disabled"
|
||||
|
||||
IDENTITY_SOURCE_STORED = "stored"
|
||||
IDENTITY_SOURCE_BROWSER = "browser"
|
||||
|
||||
|
||||
class MonitorIdentity(MonitorBase):
|
||||
"""一个可用于采集的登录态。
|
||||
|
||||
**为什么 cookie 必须和 UA 一起存**:抖音的 ``a_bogus`` 签名把 UA 算进去
|
||||
(``libs/douyin.js``),而网关又把 cookie / UA / sec-ch-ua 当成同一台设备的
|
||||
指纹。只存 cookie、套用另一套 UA,签名和指纹都对不上,接口只会回 200 + 空 body。
|
||||
|
||||
``source="browser"`` 表示用 CDP 浏览器**当前**登录态,此时 ``cookie`` 留空、每次
|
||||
运行时现读;``source="stored"`` 才是粘贴进来的那一份。
|
||||
"""
|
||||
|
||||
__tablename__ = "monitor_identity"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("platform", "label", name="uq_monitor_identity_label"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
platform: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="dy", index=True
|
||||
)
|
||||
label: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
source: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default=IDENTITY_SOURCE_STORED
|
||||
)
|
||||
# **永不回显**:接口只返回 has_cookie。
|
||||
cookie: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
user_agent: Mapped[str] = mapped_column(String(512), nullable=False, default="")
|
||||
client_hints: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
|
||||
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default=IDENTITY_STATUS_OK
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
# 冷却退避用:连续失败 N 次后冷却,成功后清零。
|
||||
consecutive_failures: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
cooldown_until: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
last_checked_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
last_ok_at: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
last_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
|
||||
created_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
updated_at: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
|
||||
|
||||
# Pre-namespacing keys, kept only so the startup migration can find and move
|
||||
# them. Nothing should read these directly.
|
||||
LEGACY_SETTING_KEY_RENAMES = {
|
||||
|
||||
+99
-20
@@ -41,6 +41,7 @@ from ..schemas import (
|
||||
)
|
||||
from ..services import crawler_manager
|
||||
from . import adapters, app_settings, covers, douyin_fetch, notify
|
||||
from . import identities as identity_pool
|
||||
from .db import get_session
|
||||
from .ingest import IngestResult, diagnose_failure, ingest_run
|
||||
from .models import (
|
||||
@@ -49,6 +50,7 @@ from .models import (
|
||||
RUN_PENDING,
|
||||
RUN_RUNNING,
|
||||
RUN_TIMEOUT,
|
||||
MonitorIdentity,
|
||||
MonitorNote,
|
||||
MonitorRun,
|
||||
MonitorTarget,
|
||||
@@ -205,6 +207,34 @@ async def execute_task(task_id: int, trigger: str = "manual") -> IngestResult:
|
||||
)
|
||||
)
|
||||
|
||||
# 身份池只在抖音上有意义(小红书走子进程)。池模式是**串行分片**:把目标分给
|
||||
# 多个账号,降低每个账号的请求量,不是并行提速。
|
||||
identity_rows = []
|
||||
identity_min_available = 1
|
||||
identity_switch_delay = 0
|
||||
identity_concurrency = 1
|
||||
if platform == adapters.PLATFORM_DY:
|
||||
identity_mode = await app_settings.get_value(
|
||||
session, "identity_mode", platform, "single"
|
||||
)
|
||||
if identity_mode == "pool":
|
||||
identity_rows = await identity_pool.load_available(session, platform)
|
||||
identity_min_available = int(
|
||||
await app_settings.get_value(
|
||||
session, "identity_min_available", platform, 1
|
||||
)
|
||||
)
|
||||
identity_switch_delay = int(
|
||||
await app_settings.get_value(
|
||||
session, "identity_switch_delay_sec", platform, 30
|
||||
)
|
||||
)
|
||||
identity_concurrency = int(
|
||||
await app_settings.get_value(
|
||||
session, "identity_concurrency", platform, 1
|
||||
)
|
||||
)
|
||||
|
||||
# --- Phase 2: run the collection outside any transaction ------------------
|
||||
# 抖音走**进程内 HTTP 客户端**,不起 Playwright 子进程:那边会构造一大串自相矛盾的
|
||||
# 浏览器指纹参数(参数说 Mac + Chrome 125、UA 说 Linux + Chrome 155),网关回一个
|
||||
@@ -219,33 +249,82 @@ async def execute_task(task_id: int, trigger: str = "manual") -> IngestResult:
|
||||
run.status = RUN_RUNNING
|
||||
run.started_at = get_current_timestamp()
|
||||
|
||||
# 身份行在会话关掉之后是 detached 的,但 expire_on_commit=False,字段还能读。
|
||||
# 解析放到这里(会话之外)—— source="browser" 要连 CDP,可能慢。
|
||||
resolved_identities = []
|
||||
resolved_ids = []
|
||||
for row in identity_rows:
|
||||
try:
|
||||
resolved_identities.append(await identity_pool.resolve(row))
|
||||
resolved_ids.append(row.id)
|
||||
except ValueError as exc:
|
||||
print(f"[monitor.runner] 身份「{row.label}」本轮不可用:{exc}", flush=True)
|
||||
|
||||
in_process_tail: List[str] = []
|
||||
if platform == adapters.PLATFORM_DY:
|
||||
try:
|
||||
# 也要有超时。爬虫那条路靠 run_and_wait(timeout=...) 兜底,这条路没有子进程、
|
||||
# 没人管 —— 里面**任何一次卡住都会让 run 永远停在「运行中」**(真踩过:
|
||||
# page.evaluate 打在一个卡死的标签页上不返回)。
|
||||
fetched = await asyncio.wait_for(
|
||||
douyin_fetch.collect(
|
||||
out_dir,
|
||||
platform=platform,
|
||||
mode=mode,
|
||||
limit=max_notes_count,
|
||||
want_comments=enable_comments,
|
||||
comment_limit=max_comments_count,
|
||||
targets=targets,
|
||||
known_aweme_ids=known_aweme_ids,
|
||||
cookie=cookie,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
if identity_rows and len(resolved_identities) < identity_min_available:
|
||||
# 快速失败:宁可这一轮不跑,也别拿一个号硬扛全部目标。
|
||||
fetched = {
|
||||
"notes": 0,
|
||||
"comments": 0,
|
||||
"errors": [f"抖音采集超过 {timeout_seconds} 秒仍未完成,已放弃这一轮"],
|
||||
"errors": [
|
||||
f"可用抖音身份不足:{len(resolved_identities)}/{identity_min_available}"
|
||||
"(其余的已失效或在冷却中)"
|
||||
],
|
||||
"jsonl_dir": "",
|
||||
"shards": [],
|
||||
}
|
||||
else:
|
||||
try:
|
||||
# 也要有超时。爬虫那条路靠 run_and_wait(timeout=...) 兜底,这条路没有子进程、
|
||||
# 没人管 —— 里面**任何一次卡住都会让 run 永远停在「运行中」**(真踩过:
|
||||
# page.evaluate 打在一个卡死的标签页上不返回)。
|
||||
fetched = await asyncio.wait_for(
|
||||
douyin_fetch.collect(
|
||||
out_dir,
|
||||
platform=platform,
|
||||
mode=mode,
|
||||
limit=max_notes_count,
|
||||
want_comments=enable_comments,
|
||||
comment_limit=max_comments_count,
|
||||
targets=targets,
|
||||
known_aweme_ids=known_aweme_ids,
|
||||
cookie=cookie,
|
||||
identities=resolved_identities,
|
||||
concurrency=identity_concurrency,
|
||||
switch_delay_seconds=identity_switch_delay,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
fetched = {
|
||||
"notes": 0,
|
||||
"comments": 0,
|
||||
"errors": [f"抖音采集超过 {timeout_seconds} 秒仍未完成,已放弃这一轮"],
|
||||
"jsonl_dir": "",
|
||||
"shards": [],
|
||||
}
|
||||
|
||||
# 每个身份的健康按它自己那一片的结果算:有产物就算成功(哪怕带着退化错误),
|
||||
# 一条没采到且全是错误才算失败。
|
||||
if resolved_ids:
|
||||
shards_by_key = {
|
||||
shard.get("key"): shard for shard in (fetched.get("shards") or [])
|
||||
}
|
||||
async with get_session() as session:
|
||||
for row_id in resolved_ids:
|
||||
row = await session.get(MonitorIdentity, row_id)
|
||||
if row is None:
|
||||
continue
|
||||
shard = shards_by_key.get(identity_pool.key_for(row))
|
||||
if shard is None:
|
||||
continue
|
||||
await identity_pool.record_result(
|
||||
session,
|
||||
row,
|
||||
ok=bool(shard["notes"]) or not shard["errors"],
|
||||
error=";".join(shard["errors"]),
|
||||
)
|
||||
in_process_tail = list(fetched["errors"])
|
||||
# 一条都没采到 = 这一轮失败,并把**真因**当作退出诊断传下去。否则它会掉进
|
||||
# ingest 的「疑似登录失效」分支 —— 又骗人一次,正是这套东西一直在犯的毛病。
|
||||
|
||||
+184
-2
@@ -18,13 +18,19 @@
|
||||
|
||||
"""HTTP API for scheduled monitoring tasks."""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Response
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from ..monitor import covers, notify, qrlogin, report, service, tagrules, upstream
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..monitor import covers, douyin_api, notify, qrlogin, report, service, tagrules, upstream
|
||||
from ..monitor import identities as identity_pool
|
||||
from ..monitor.db import get_session
|
||||
from ..monitor.platforms import PLATFORM_XHS
|
||||
from ..monitor.settings import (
|
||||
@@ -35,10 +41,19 @@ from ..monitor.settings import (
|
||||
set_cookie,
|
||||
set_setting,
|
||||
)
|
||||
from ..monitor.models import SETTING_WECOM_WEBHOOK, MonitorTask
|
||||
from ..monitor.models import (
|
||||
IDENTITY_SOURCE_STORED,
|
||||
IDENTITY_STATUS_OK,
|
||||
SETTING_WECOM_WEBHOOK,
|
||||
MonitorIdentity,
|
||||
MonitorTarget,
|
||||
MonitorTask,
|
||||
)
|
||||
from ..schemas.monitor import (
|
||||
CookiePayload,
|
||||
CreatorAliasPayload,
|
||||
IdentityCreate,
|
||||
IdentityUpdate,
|
||||
NoteAliasPayload,
|
||||
NoteTagsPayload,
|
||||
TagPayload,
|
||||
@@ -879,3 +894,170 @@ async def run_upstream_check():
|
||||
没有推过的那批提交会留给下一次「定时检查」推 —— 推送状态记的是 tip,不是「推过没」。
|
||||
"""
|
||||
return await upstream.run_check(notify_when_new=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 身份池
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# 多个登录态分片采集用。**接口永远不返回 cookie 原文**,只给 has_cookie —— 这是
|
||||
# 从运营模块那边沿用下来的约定。
|
||||
|
||||
|
||||
@router.get("/identities")
|
||||
async def list_identities(platform: str = Query(default=PLATFORM_XHS)):
|
||||
async with get_session() as session:
|
||||
rows = (
|
||||
await session.scalars(
|
||||
select(MonitorIdentity)
|
||||
.where(MonitorIdentity.platform == platform)
|
||||
.order_by(MonitorIdentity.id)
|
||||
)
|
||||
).all()
|
||||
return {"identities": [identity_pool.to_dict(row) for row in rows]}
|
||||
|
||||
|
||||
@router.post("/identities", status_code=201)
|
||||
async def create_identity(payload: IdentityCreate):
|
||||
"""新增一份登录态。
|
||||
|
||||
UA 留空时会尝试从 CDP 浏览器借一份指纹 —— cookie 仍用用户贴的这一份。再读不到
|
||||
就拒绝:评论签名要拿 UA,空 UA 的请求一定被挡。
|
||||
"""
|
||||
if payload.platform != "dy":
|
||||
raise HTTPException(status_code=400, detail="目前只有抖音支持多身份")
|
||||
|
||||
user_agent = payload.user_agent.strip()
|
||||
hints = dict(payload.client_hints)
|
||||
if not user_agent:
|
||||
user_agent, shared_hints = await douyin_api.shared_fingerprint()
|
||||
hints = hints or dict(shared_hints)
|
||||
if not user_agent:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"拿不到 UA。请手动填写 user_agent(要和 cookie 来自同一个浏览器),"
|
||||
"或先让 CDP 浏览器登录抖音。"
|
||||
),
|
||||
)
|
||||
|
||||
label = payload.label.strip()
|
||||
now = get_current_timestamp()
|
||||
async with get_session() as session:
|
||||
exists = await session.scalar(
|
||||
select(MonitorIdentity.id).where(
|
||||
MonitorIdentity.platform == payload.platform,
|
||||
MonitorIdentity.label == label,
|
||||
)
|
||||
)
|
||||
if exists:
|
||||
raise HTTPException(status_code=409, detail="同名身份已存在")
|
||||
|
||||
row = MonitorIdentity(
|
||||
platform=payload.platform,
|
||||
label=label,
|
||||
source=IDENTITY_SOURCE_STORED,
|
||||
cookie=payload.cookie.strip(),
|
||||
user_agent=user_agent,
|
||||
client_hints=json.dumps(hints, ensure_ascii=False),
|
||||
status=IDENTITY_STATUS_OK,
|
||||
enabled=True,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
return identity_pool.to_dict(row)
|
||||
|
||||
|
||||
@router.patch("/identities/{identity_id}")
|
||||
async def update_identity(identity_id: int, payload: IdentityUpdate):
|
||||
async with get_session() as session:
|
||||
row = await session.get(MonitorIdentity, identity_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="身份不存在")
|
||||
|
||||
if payload.label is not None:
|
||||
row.label = payload.label.strip()
|
||||
if payload.user_agent is not None:
|
||||
row.user_agent = payload.user_agent.strip()
|
||||
if payload.cookie is not None:
|
||||
row.cookie = payload.cookie.strip()
|
||||
# 换了 cookie,旧状态作废 —— 之前冷却/失效的原因可能已经不存在了。
|
||||
row.status = IDENTITY_STATUS_OK
|
||||
row.consecutive_failures = 0
|
||||
row.cooldown_until = None
|
||||
row.last_error = None
|
||||
if payload.enabled is not None:
|
||||
row.enabled = payload.enabled
|
||||
row.updated_at = get_current_timestamp()
|
||||
await session.flush()
|
||||
return identity_pool.to_dict(row)
|
||||
|
||||
|
||||
@router.delete("/identities/{identity_id}")
|
||||
async def delete_identity(identity_id: int):
|
||||
async with get_session() as session:
|
||||
row = await session.get(MonitorIdentity, identity_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="身份不存在")
|
||||
await session.delete(row)
|
||||
return {"deleted": identity_id}
|
||||
|
||||
|
||||
@router.post("/identities/{identity_id}/check")
|
||||
async def check_identity(identity_id: int):
|
||||
"""真去用这份身份请求一次。
|
||||
|
||||
优先拿该平台一个启用中的博主目标做探针(``author_profile``,1 个请求);没有目标
|
||||
时退化成「cookie 里有没有 sessionid」,并在 ``verified`` 里标 False —— 别把格式
|
||||
检查说成验证通过。
|
||||
"""
|
||||
async with get_session() as session:
|
||||
row = await session.get(MonitorIdentity, identity_id)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="身份不存在")
|
||||
platform = row.platform
|
||||
probe = await session.scalar(
|
||||
select(MonitorTarget.external_id)
|
||||
.join(MonitorTask, MonitorTask.id == MonitorTarget.task_id)
|
||||
.where(
|
||||
MonitorTask.platform == platform,
|
||||
MonitorTask.enabled.is_(True),
|
||||
MonitorTarget.kind == "creator",
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
error = ""
|
||||
verified = bool(probe)
|
||||
ok = False
|
||||
try:
|
||||
identity = await identity_pool.resolve(row)
|
||||
except ValueError as exc:
|
||||
identity = None
|
||||
error = str(exc)
|
||||
|
||||
if identity is not None:
|
||||
if probe:
|
||||
try:
|
||||
await douyin_api.author_profile(probe, identity=identity)
|
||||
ok = True
|
||||
except Exception as exc: # noqa: BLE001 - 任何失败都只是「这份身份不可用」
|
||||
error = f"{type(exc).__name__}: {exc}"[:300]
|
||||
else:
|
||||
ok = "sessionid=" in identity.cookie
|
||||
if not ok:
|
||||
error = "cookie 里没有 sessionid"
|
||||
|
||||
async with get_session() as session:
|
||||
live = await session.get(MonitorIdentity, identity_id)
|
||||
if live is not None:
|
||||
await identity_pool.record_result(session, live, ok=ok, error=error)
|
||||
return {
|
||||
"ok": ok,
|
||||
"verified": verified,
|
||||
"error": error,
|
||||
"identity": identity_pool.to_dict(live),
|
||||
}
|
||||
return {"ok": ok, "verified": verified, "error": error, "identity": None}
|
||||
|
||||
+22
-1
@@ -18,7 +18,7 @@
|
||||
|
||||
"""Request models for the monitoring API."""
|
||||
|
||||
from typing import List, Literal, Optional
|
||||
from typing import Dict, List, Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
@@ -144,3 +144,24 @@ class WebhookPayload(BaseModel):
|
||||
|
||||
class WebhookTestPayload(BaseModel):
|
||||
url: Optional[str] = Field(default=None, description="不传则使用已保存的地址")
|
||||
|
||||
|
||||
class IdentityCreate(BaseModel):
|
||||
"""新增一个采集身份(一份登录态)。
|
||||
|
||||
``user_agent`` 最好和 cookie 来自同一个浏览器。留空时后端会尝试从 CDP 浏览器
|
||||
读一份指纹兜底;再读不到就拒绝 —— 评论接口的 a_bogus 要拿 UA 去签名。
|
||||
"""
|
||||
|
||||
platform: str = Field(default="dy", max_length=16)
|
||||
label: str = Field(min_length=1, max_length=128)
|
||||
cookie: str = Field(min_length=1)
|
||||
user_agent: str = Field(default="", max_length=512)
|
||||
client_hints: Dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class IdentityUpdate(BaseModel):
|
||||
label: Optional[str] = Field(default=None, min_length=1, max_length=128)
|
||||
cookie: Optional[str] = Field(default=None)
|
||||
user_agent: Optional[str] = Field(default=None, max_length=512)
|
||||
enabled: Optional[bool] = None
|
||||
|
||||
Reference in New Issue
Block a user