From 0a8f6e64c90cf1a65592a329c296e95494b66a81 Mon Sep 17 00:00:00 2001 From: butubb <1422726308@qq.com> Date: Wed, 14 Oct 2026 08:09:09 +0800 Subject: [PATCH] =?UTF-8?q?feat(monitor):=20=E4=BF=9D=E5=AD=98=E7=9B=AE?= =?UTF-8?q?=E6=A0=87=E6=97=B6=E6=8A=8A=E5=88=86=E4=BA=AB=E7=9F=AD=E9=93=BE?= =?UTF-8?q?=E8=A7=A3=E6=88=90=E5=AE=8C=E6=95=B4=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 短链粘进来会被原样存成 external_id,而那是采集时唯一拿去请求的东西 —— 于是永远 抓不到东西(真事:任务 22 的 xhslink 短链,还报成了「疑似登录态失效」)。 做法:**GET 且不跟随跳转,直接读第一个 Location**。 * 小红书的 xhslink.cn/o/xxx —— 第一个 Location 就是 xiaohongshu.com/user/profile/?xsec_token=...&xsec_source=...,要的都在里面。 跟到底反而会丢:它会一路跳到登录页。 * 抖音的 v.douyin.com 同样是 302 + Location;码不存在时跳到首页,那就解不出来。 解不出来时**返回原值、不报错** —— 链接校验已经按用户要求关掉了,再造一个拒绝点 自相矛盾。代价(那个目标抓不到东西)由 ingest 直说,不静默。 解析本身仍是纯函数,网络那一步单独放在 expand_short_link;两个调用点走 prepare_target。raw_value 记的仍是**用户当初粘的原文**(短链),不是解开后的地址 —— 解错目标时靠它回溯。 测试里的跳转 URL 用的是实测到的真实响应,不是编的。 --- api/monitor/adapters.py | 6 ++ api/monitor/service.py | 65 +++++++++++++- tests/test_monitor_api.py | 66 +++++++++++++++ tests/test_monitor_short_link.py | 141 +++++++++++++++++++++++++++++++ 4 files changed, 276 insertions(+), 2 deletions(-) create mode 100644 tests/test_monitor_short_link.py diff --git a/api/monitor/adapters.py b/api/monitor/adapters.py index 0f9ee29..f6ca35c 100644 --- a/api/monitor/adapters.py +++ b/api/monitor/adapters.py @@ -82,6 +82,10 @@ class PlatformAdapter: # 也允许直接粘贴裸 id —— 但两边的 id 形状不同,所以分开。 creator_bare_re: Pattern note_bare_re: Pattern + # **分享短链的域名**。保存目标时要联网跟一次跳转,把真实地址解出来 —— + # 不解的话存进去的是一串短码,采集时拿它去请求,什么也抓不到(真事:任务 22)。 + # 注意这让「解析」不再是纯函数:见 service.prepare_target。 + short_link_hosts: Tuple[str, ...] note_fields: Mapping[str, str] comment_fields: Mapping[str, str] @@ -152,6 +156,7 @@ XHS = PlatformAdapter( ), creator_bare_re=_XHS_BARE_RE, note_bare_re=_XHS_BARE_RE, + short_link_hosts=("xhslink.cn", "xhslink.com"), note_fields={ "note_id": "note_id", "title": "title", @@ -200,6 +205,7 @@ DY = PlatformAdapter( # 又不会把 19 位的作品号误当成博主。 creator_bare_re=re.compile(r"^[A-Za-z0-9_-]{20,128}$"), note_bare_re=re.compile(r"^\d{8,25}$"), + short_link_hosts=("v.douyin.com",), note_fields={ "note_id": "aweme_id", "title": "title", diff --git a/api/monitor/service.py b/api/monitor/service.py index 3acf0b5..35b4771 100644 --- a/api/monitor/service.py +++ b/api/monitor/service.py @@ -22,6 +22,7 @@ import asyncio from typing import Any, Dict, List, Optional, Sequence from urllib.parse import parse_qs, urlparse +import httpx from sqlalchemy import delete, func, select from sqlalchemy.ext.asyncio import AsyncSession @@ -87,6 +88,66 @@ 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/?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]: @@ -225,7 +286,7 @@ async def create_task(session: AsyncSession, payload: Dict[str, Any]) -> Monitor seen: set[str] = set() for value in payload.get("targets", []): - parsed = parse_target_input(value, mode, platform) + parsed = await prepare_target(value, mode, platform) if parsed["external_id"] in seen: continue seen.add(parsed["external_id"]) @@ -284,7 +345,7 @@ async def update_task(session: AsyncSession, task_id: int, payload: Dict[str, An now = get_current_timestamp() seen: set[str] = set() for value in payload["targets"]: - parsed = parse_target_input(value, task.mode, task.platform) + parsed = await prepare_target(value, task.mode, task.platform) if parsed["external_id"] in seen: continue seen.add(parsed["external_id"]) diff --git a/tests/test_monitor_api.py b/tests/test_monitor_api.py index 0219b0c..4558d96 100644 --- a/tests/test_monitor_api.py +++ b/tests/test_monitor_api.py @@ -354,3 +354,69 @@ class TestDashboardQueries: overview = (await client.get("/api/monitor/overview")).json() assert overview["tasks"] == 0 assert overview["notes"] == 0 + + +class TestShortLinksAreResolvedOnCreate: + """建任务时短链要**先解开再存** —— 存的是短码本身的话,采集永远抓不到东西。 + + 这一条测的是**接线**(create_task / update_task 有没有走 prepare_target)。 + 解短链本身的逻辑在 test_monitor_short_link.py 里测。 + """ + + @pytest.mark.asyncio + async def test_a_share_link_is_stored_expanded(self, client, monkeypatch): + from api.monitor import service + + real = "https://www.xiaohongshu.com/user/profile/69d388f00000000032024a75" + + async def fake_expand(value, platform): + return real + + monkeypatch.setattr(service, "expand_short_link", fake_expand) + + response = await client.post( + "/api/monitor/tasks", + json={ + "name": "短链", + "mode": "creator", + "platform": "xhs", + "targets": ["https://xhslink.cn/o/AhQpHsqcme5"], + }, + ) + + assert response.status_code == 201 + tasks = (await client.get("/api/monitor/tasks")).json()["tasks"] + target = tasks[0]["targets"][0] + assert target["external_id"] == "69d388f00000000032024a75" + # 原文留着 —— 解错目标时靠它回溯用户当初粘的是什么。 + assert target["raw_value"] == "https://xhslink.cn/o/AhQpHsqcme5" + + @pytest.mark.asyncio + async def test_updating_targets_resolves_them_too(self, client, monkeypatch): + """改目标走的是另一条路,同样不能漏。""" + from api.monitor import service + + async def fake_expand(value, platform): + return "https://www.xiaohongshu.com/user/profile/aaaabbbbccccddddeeeeffff" + + created = await client.post( + "/api/monitor/tasks", + json={ + "name": "改目标", + "mode": "creator", + "platform": "xhs", + "targets": ["5f58bd990000000001003753"], + }, + ) + assert created.status_code == 201 + task_id = (await client.get("/api/monitor/tasks")).json()["tasks"][0]["id"] + monkeypatch.setattr(service, "expand_short_link", fake_expand) + + response = await client.patch( + f"/api/monitor/tasks/{task_id}", + json={"targets": ["https://xhslink.cn/o/whatever"]}, + ) + assert response.status_code == 200, response.text + + tasks = (await client.get("/api/monitor/tasks")).json()["tasks"] + assert tasks[0]["targets"][0]["external_id"] == "aaaabbbbccccddddeeeeffff" diff --git a/tests/test_monitor_short_link.py b/tests/test_monitor_short_link.py new file mode 100644 index 0000000..254bfe7 --- /dev/null +++ b/tests/test_monitor_short_link.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +"""分享短链 —— 保存目标时联网跟一次跳转,解出真实地址。 + +不这么做的话,粘进去的是一串短码,被当成 user_id 存下来,采集时拿它去请求什么都抓不到 +(真事:任务 22,`https://xhslink.cn/o/AhQpHsqcme5`,报出来却是「疑似登录态失效」)。 +""" + +import httpx +import pytest + +from api.monitor.service import expand_short_link, parse_target_input, prepare_target + +# **真实的跳转**(实测 xhslink.cn/o/AhQpHsqcme5 的第一个 302),不是编的 —— +# 这个地址的形状决定了能不能抠出 id 和 xsec_token。 +REAL_XHS_REDIRECT = ( + "https://www.xiaohongshu.com/user/profile/69d388f00000000032024a75" + "?xsec_token=YBpTJH9kYbkTkgL-F4POKqd_kEM5A05smIjgbcyMSI2k4%3D" + "&xsec_source=app_share&xhsshare=CopyLink&track_code=4s40v6M3mwa" +) + + +def _client_returning(monkeypatch, status_code: int, location: str): + """假装是那个短链服务器:只看 Location,不跟跳转。""" + seen: dict = {} + + class _Response: + headers = {"location": location} if location else {} + + _Response.status_code = status_code + + class _Client: + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def get(self, url, **kwargs): + seen["url"] = url + seen.update(kwargs) + return _Response() + + monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: _Client()) + return seen + + +class TestExpandShortLink: + @pytest.mark.asyncio + async def test_a_share_link_is_expanded(self, monkeypatch): + _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT) + + expanded = await expand_short_link("https://xhslink.cn/o/AhQpHsqcme5", "xhs") + + assert expanded == REAL_XHS_REDIRECT + + @pytest.mark.asyncio + async def test_it_asks_for_the_first_hop_only(self, monkeypatch): + """**不跟随跳转**:跟到底会落到登录页,反而把要的东西丢了。""" + seen = _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT) + + await expand_short_link("https://xhslink.cn/o/AhQpHsqcme5", "xhs") + + assert seen["follow_redirects"] is False + + @pytest.mark.asyncio + async def test_a_normal_link_is_not_even_requested(self, monkeypatch): + """普通链接不联网 —— 多发一个请求既慢又没有意义,还可能把 token 弄丢。""" + seen = _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT) + + value = "https://www.xiaohongshu.com/user/profile/69d388f00000000032024a75" + + assert await expand_short_link(value, "xhs") == value + assert seen == {} + + @pytest.mark.asyncio + async def test_a_bare_id_is_not_requested(self, monkeypatch): + seen = _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT) + + assert await expand_short_link("69d388f00000000032024a75", "xhs") == ( + "69d388f00000000032024a75" + ) + assert seen == {} + + @pytest.mark.asyncio + async def test_a_dead_short_link_keeps_the_original_value(self, monkeypatch): + """码不存在时抖音会跳到首页 —— 那就解不出来。**保持原值,不报错**: + 链接校验已经关掉了,再造一个拒绝点自相矛盾。""" + _client_returning(monkeypatch, 302, "https://www.douyin.com/") + + assert await expand_short_link("https://v.douyin.com/zzz/", "dy") != "" + + @pytest.mark.asyncio + async def test_a_network_error_keeps_the_original_value(self, monkeypatch): + """短链服务不通时不能把「新建任务」这个动作也带崩。""" + + class _Boom: + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def get(self, *args, **kwargs): + raise httpx.ConnectTimeout("boom") + + monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: _Boom()) + value = "https://xhslink.cn/o/AhQpHsqcme5" + + assert await expand_short_link(value, "xhs") == value + + +class TestPrepareTarget: + @pytest.mark.asyncio + async def test_the_real_short_link_yields_a_usable_target(self, monkeypatch): + """**这就是任务 22 该有的结果** —— 而不是把短链本身存成 external_id。""" + _client_returning(monkeypatch, 302, REAL_XHS_REDIRECT) + + parsed = await prepare_target("https://xhslink.cn/o/AhQpHsqcme5", "creator", "xhs") + + assert parsed["external_id"] == "69d388f00000000032024a75" + assert parsed["xsec_token"] == "YBpTJH9kYbkTkgL-F4POKqd_kEM5A05smIjgbcyMSI2k4=" + assert parsed["xsec_source"] == "app_share" + # 原文留着,出问题时能回溯用户当初粘的是什么。 + assert parsed["raw_value"] == "https://xhslink.cn/o/AhQpHsqcme5" + + @pytest.mark.asyncio + async def test_an_unexpandable_link_still_gets_stored(self, monkeypatch): + """解不开也照存 —— 这是「完全不校验」的既定行为,不能在这里偷偷加一个拒绝点。""" + _client_returning(monkeypatch, 302, "") + + parsed = await prepare_target("https://xhslink.cn/o/dead", "creator", "xhs") + + assert parsed["external_id"] == "https://xhslink.cn/o/dead" + + +class TestParseIsStillPure: + """纯函数那层没变 —— 短链解不开时它仍然只能原样存,网络那一步在外面。""" + + def test_parse_alone_does_not_expand(self): + parsed = parse_target_input("https://xhslink.cn/o/AhQpHsqcme5", "creator", "xhs") + assert parsed["external_id"] == "https://xhslink.cn/o/AhQpHsqcme5"