feat(monitor): 保存目标时把分享短链解成完整链接
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

短链粘进来会被原样存成 external_id,而那是采集时唯一拿去请求的东西 —— 于是永远
抓不到东西(真事:任务 22 的 xhslink 短链,还报成了「疑似登录态失效」)。

做法:**GET 且不跟随跳转,直接读第一个 Location**。
  * 小红书的 xhslink.cn/o/xxx —— 第一个 Location 就是
    xiaohongshu.com/user/profile/<id>?xsec_token=...&xsec_source=...,要的都在里面。
    跟到底反而会丢:它会一路跳到登录页。
  * 抖音的 v.douyin.com 同样是 302 + Location;码不存在时跳到首页,那就解不出来。

解不出来时**返回原值、不报错** —— 链接校验已经按用户要求关掉了,再造一个拒绝点
自相矛盾。代价(那个目标抓不到东西)由 ingest 直说,不静默。

解析本身仍是纯函数,网络那一步单独放在 expand_short_link;两个调用点走
prepare_target。raw_value 记的仍是**用户当初粘的原文**(短链),不是解开后的地址 ——
解错目标时靠它回溯。

测试里的跳转 URL 用的是实测到的真实响应,不是编的。
This commit is contained in:
2026-10-14 08:09:09 +08:00
parent f6276ec314
commit 0a8f6e64c9
4 changed files with 276 additions and 2 deletions
+63 -2
View File
@@ -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/<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]:
@@ -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"])