feat(monitor): 粘贴视频链接换出博主主页
运营手上常常只有一条作品的分享链接,可监控任务认的是主页里的 sec_uid。 - 从整段分享文案里抠链接(链接前后都是字,按行切切不开),短链先展开, 再从中取作品 id,最后用详情接口换 author.sec_uid - 一次最多 20 条,串行 + 0.4 秒间隔;单条失败只在那一条上报错,不连累整批 - normalize_aweme 补上 creator_id:哈希拼不出主页地址,顺带让以后入库的 抖音作品也带主页链接 - 监控页左上角「视频转主页」,支持逐条复制和一键复制全部(http 下没有 navigator.clipboard,走 execCommand 兜底)
This commit is contained in:
@@ -442,6 +442,9 @@ def normalize_aweme(aweme: Dict[str, Any]) -> Dict[str, Any]:
|
||||
# **秒**。adapters.time_scale 会把它换成毫秒,和 store 写出来的形态一致。
|
||||
"create_time": _as_int(aweme.get("create_time")),
|
||||
"creator_hash": anonymize_user_id(uid or author.get("sec_uid") or ""),
|
||||
# 主页 id(sec_uid)。**哈希拼不出主页地址**,而详情接口的返回里现成就有这一段
|
||||
# —— 不带出来,库里抖音作品的主页链接就全是空的。
|
||||
"creator_id": str(author.get("sec_uid") or ""),
|
||||
"nickname": nickname,
|
||||
"liked_count": str(_as_int(statistics.get("digg_count"))),
|
||||
"comment_count": str(_as_int(statistics.get("comment_count"))),
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""视频链接 → 博主主页链接。
|
||||
|
||||
运营手上经常只有一条作品的分享链接(甚至只是「复制打开抖音」那一整段文案),却要
|
||||
把发它的号加进监控 —— 监控任务认的是主页里的 ``sec_uid``,不认作品 id。
|
||||
|
||||
所以这里的全部工作就是三步,一步都不能省:
|
||||
|
||||
1. 从一段文本里**抠出链接**(分享文案里链接前后都是字,按行切根本切不开);
|
||||
2. **短链展开** —— ``v.douyin.com/xxx`` 只有一个跳转头,不展开就看不到作品 id;
|
||||
3. 用作品详情接口换出 ``author.sec_uid``(实测返回里有),再拼成主页地址。
|
||||
|
||||
**为什么不用分享页 HTML 解析**:``iesdouyin.com/share/video/{id}`` 里的
|
||||
``_ROUTER_DATA`` 是内部结构,改版就断,而且拿不到登录态下的完整字段。详情接口本来
|
||||
就是采集在用的那条路,登录态、UA、签名都已经配好。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from . import adapters, douyin_api, service
|
||||
|
||||
# 一次最多解析这么多条。限流不是怕算不过来 —— 是怕一不小心粘进来几百条,把详情接口
|
||||
# 打成一串风控信号。前端一次贴十几条是正常用量。
|
||||
MAX_LINKS = 20
|
||||
# 每两条之间歇一下。同一个登录态连续请求,节律太密比数量更容易被识别。
|
||||
REQUEST_GAP_SECONDS = 0.4
|
||||
|
||||
_URL_RE = re.compile(r"https?://[^\s,。;、))\"'<>]+")
|
||||
# 19 位作品 id,但放宽到 15–20:平台偶尔给别的位数,只按 19 位写会漏。
|
||||
_BARE_ID_RE = re.compile(r"^\d{15,20}$")
|
||||
_AWEME_ID_RES = (
|
||||
re.compile(r"/(?:share/)?video/(\d{15,20})"),
|
||||
re.compile(r"[?&]modal_id=(\d{15,20})"),
|
||||
)
|
||||
|
||||
|
||||
def extract_candidates(text: str) -> List[str]:
|
||||
"""从粘进来的文本里取出链接或裸 id,保持原顺序。
|
||||
|
||||
一行里出现多个链接时全部取出:分享文案经常把「网页版」和「App」两个链接一起带上。
|
||||
既不是链接也不是纯数字的行直接丢掉 —— 它们要么是中文说明,要么是用户误粘的东西,
|
||||
逐条报错只会把真正有用的几条埋掉。
|
||||
"""
|
||||
candidates: List[str] = []
|
||||
for line in (text or "").splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped:
|
||||
continue
|
||||
urls = _URL_RE.findall(stripped)
|
||||
if urls:
|
||||
candidates.extend(urls)
|
||||
continue
|
||||
if _BARE_ID_RE.match(stripped):
|
||||
candidates.append(stripped)
|
||||
return candidates
|
||||
|
||||
|
||||
def aweme_id_from_url(value: str) -> str:
|
||||
"""从(已经展开过的)地址里抠作品 id;认不出返回空串。"""
|
||||
for pattern in _AWEME_ID_RES:
|
||||
match = pattern.search(value)
|
||||
if match:
|
||||
return match.group(1)
|
||||
stripped = value.strip()
|
||||
if _BARE_ID_RE.match(stripped):
|
||||
return stripped
|
||||
return ""
|
||||
|
||||
|
||||
async def _aweme_id(value: str) -> str:
|
||||
"""短链先展开,再抠 id。"""
|
||||
expanded = value
|
||||
if value.startswith("http"):
|
||||
expanded = await service.expand_short_link(value, adapters.PLATFORM_DY)
|
||||
return aweme_id_from_url(expanded)
|
||||
|
||||
|
||||
def _blank(value: str) -> Dict[str, Any]:
|
||||
return {
|
||||
"input": value,
|
||||
"aweme_id": "",
|
||||
"ok": False,
|
||||
"nickname": "",
|
||||
"sec_uid": "",
|
||||
"profile_url": "",
|
||||
"error": "",
|
||||
}
|
||||
|
||||
|
||||
async def resolve(text: str) -> Dict[str, Any]:
|
||||
"""把一段文本里的视频链接逐条换成博主主页。
|
||||
|
||||
返回 ``{"results": [...], "truncated": bool}``。单条失败**不影响**其余几条 ——
|
||||
批量粘贴时挂一条就把整批丢掉,比不提供这个功能还难用。
|
||||
"""
|
||||
candidates = extract_candidates(text)
|
||||
truncated = len(candidates) > MAX_LINKS
|
||||
candidates = candidates[:MAX_LINKS]
|
||||
|
||||
results: List[Dict[str, Any]] = []
|
||||
seen: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for index, value in enumerate(candidates):
|
||||
if index:
|
||||
await asyncio.sleep(REQUEST_GAP_SECONDS)
|
||||
item = _blank(value)
|
||||
results.append(item)
|
||||
|
||||
try:
|
||||
aweme_id = await _aweme_id(value)
|
||||
except Exception as exc: # 短链展开是网络操作,失败也要落到这一条上
|
||||
item["error"] = f"链接展开失败:{exc}"
|
||||
continue
|
||||
|
||||
if not aweme_id:
|
||||
item["error"] = "认不出作品 id(支持抖音视频链接、分享短链、15–20 位作品 id)"
|
||||
continue
|
||||
item["aweme_id"] = aweme_id
|
||||
|
||||
# 同一条作品粘了两遍:直接复用上一次的结果,不再打一次接口。
|
||||
if aweme_id in seen:
|
||||
item.update({k: v for k, v in seen[aweme_id].items() if k != "input"})
|
||||
continue
|
||||
|
||||
try:
|
||||
record = await douyin_api.video_detail(aweme_id)
|
||||
except Exception as exc:
|
||||
item["error"] = str(exc) or "接口没有返回这条作品"
|
||||
continue
|
||||
|
||||
sec_uid = str(record.get("creator_id") or "")
|
||||
item.update(
|
||||
{
|
||||
"ok": bool(sec_uid),
|
||||
"nickname": str(record.get("nickname") or ""),
|
||||
"sec_uid": sec_uid,
|
||||
"profile_url": adapters.creator_url(adapters.PLATFORM_DY, sec_uid),
|
||||
}
|
||||
)
|
||||
if not sec_uid:
|
||||
item["error"] = "接口返回里没有 sec_uid,拿不到主页地址"
|
||||
seen[aweme_id] = item
|
||||
|
||||
return {"results": results, "truncated": truncated}
|
||||
@@ -39,6 +39,7 @@ from ..monitor import (
|
||||
service,
|
||||
tagrules,
|
||||
upstream,
|
||||
video_link,
|
||||
)
|
||||
from ..monitor import identities as identity_pool
|
||||
from ..monitor.db import get_session
|
||||
@@ -69,6 +70,7 @@ from ..schemas.monitor import (
|
||||
TagPayload,
|
||||
MonitorTaskCreate,
|
||||
MonitorTaskUpdate,
|
||||
VideoLinksPayload,
|
||||
WebhookPayload,
|
||||
WebhookTestPayload,
|
||||
)
|
||||
@@ -942,6 +944,23 @@ async def send_daily_digest_now(platform: str = Query(default=PLATFORM_XHS)):
|
||||
return {"ok": True, "rows": count, "detail": detail}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 视频链接 → 博主主页
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# 纯查询,不写库:拿到主页地址之后要不要建监控任务,由人决定。
|
||||
|
||||
|
||||
@router.post("/video-links")
|
||||
async def resolve_video_links(payload: VideoLinksPayload):
|
||||
"""把粘贴进来的视频链接/分享文案换成博主主页地址。
|
||||
|
||||
一次最多 20 条,逐条串行请求详情接口。单条失败只在那一条上写 ``error``,
|
||||
其余照常返回 —— 批量粘贴时最不需要的就是「一条挂全批挂」。
|
||||
"""
|
||||
return await video_link.resolve(payload.text)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 身份池
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -146,6 +146,16 @@ class WebhookTestPayload(BaseModel):
|
||||
url: Optional[str] = Field(default=None, description="不传则使用已保存的地址")
|
||||
|
||||
|
||||
class VideoLinksPayload(BaseModel):
|
||||
"""一整段粘贴内容,一行一条链接(分享文案也直接粘)。
|
||||
|
||||
``max_length`` 挡的是误粘 —— 真按这个上限解析也没意义,一次最多 20 条,
|
||||
超出的部分接口会标 ``truncated`` 让前端明说。
|
||||
"""
|
||||
|
||||
text: str = Field(default="", max_length=20000)
|
||||
|
||||
|
||||
class IdentityCreate(BaseModel):
|
||||
"""新增一个采集身份(一份登录态)。
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import asyncio
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api.monitor import douyin_api
|
||||
from api.monitor import adapters, douyin_api
|
||||
|
||||
|
||||
class TestCookieParsing:
|
||||
@@ -105,6 +105,26 @@ class TestNormalizeAweme:
|
||||
# 指标按 store 的形态落成字符串,交给 ingest 的 parse_count 解析。
|
||||
assert record["liked_count"] == "3"
|
||||
assert record["collected_count"] == "2"
|
||||
# 这条 payload 里没有 sec_uid:主页 id 就空着,不许拿 uid 冒充。
|
||||
assert record["creator_id"] == ""
|
||||
|
||||
def test_creator_id_is_the_sec_uid_not_the_uid(self):
|
||||
"""主页链接只能由 sec_uid 拼出来 —— uid 是数字、creator_hash 是单向哈希。"""
|
||||
record = douyin_api.normalize_aweme(
|
||||
{
|
||||
"aweme_id": "1",
|
||||
"author": {
|
||||
"uid": "776719710825195",
|
||||
"sec_uid": "MS4wLjABAAAAcmv4-Oaxe7FN4bdQECz1knSBzKb50uhnykbLIArdkk7",
|
||||
"nickname": "AA建材王总",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert record["creator_id"] == "MS4wLjABAAAAcmv4-Oaxe7FN4bdQECz1knSBzKb50uhnykbLIArdkk7"
|
||||
assert adapters.creator_url("dy", record["creator_id"]).startswith(
|
||||
"https://www.douyin.com/user/"
|
||||
)
|
||||
|
||||
def test_hashtags_come_from_text_extra_not_the_truncated_desc(self):
|
||||
"""`desc` 会在话题列表中途被截断,后半段话题只在 `text_extra` 里。
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""视频链接 → 博主主页:链接抠取、id 解析、批量解析的容错。"""
|
||||
|
||||
import pytest
|
||||
|
||||
from api.monitor import douyin_api, service, video_link
|
||||
|
||||
SEC_UID = "MS4wLjABAAAAcmv4-Oaxe7FN4bdQECz1knSBzKb50uhnykbLIArdkk7ennhVy6Gpwp11XkVIDPgY"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_gap(monkeypatch):
|
||||
"""测试里不需要真的等那 0.4 秒节流。"""
|
||||
monkeypatch.setattr(video_link, "REQUEST_GAP_SECONDS", 0)
|
||||
|
||||
|
||||
def test_extract_candidates_pulls_links_out_of_share_text():
|
||||
text = """7.42 复制打开抖音,看看【锋哥的作品】 https://v.douyin.com/iAbCdEf/ 复制此链接
|
||||
https://www.douyin.com/video/7353137957861084427
|
||||
7353137957861084427
|
||||
|
||||
这一行是说明文字,应该被忽略
|
||||
"""
|
||||
assert video_link.extract_candidates(text) == [
|
||||
"https://v.douyin.com/iAbCdEf/",
|
||||
"https://www.douyin.com/video/7353137957861084427",
|
||||
"7353137957861084427",
|
||||
]
|
||||
|
||||
|
||||
def test_a_line_with_two_links_yields_both():
|
||||
text = "https://v.douyin.com/aaa/ https://v.douyin.com/bbb/"
|
||||
|
||||
assert len(video_link.extract_candidates(text)) == 2
|
||||
|
||||
|
||||
def test_aweme_id_from_url_handles_the_known_shapes():
|
||||
assert video_link.aweme_id_from_url("https://www.douyin.com/video/7353137957861084427") == (
|
||||
"7353137957861084427"
|
||||
)
|
||||
# 短链展开后落到的分享页
|
||||
assert video_link.aweme_id_from_url(
|
||||
"https://www.iesdouyin.com/share/video/7353137957861084427/?region=CN"
|
||||
) == "7353137957861084427"
|
||||
# 直播/精选页那种把作品挂在 modal 参数上的
|
||||
assert video_link.aweme_id_from_url(
|
||||
"https://www.douyin.com/discover?modal_id=7353137957861084427"
|
||||
) == "7353137957861084427"
|
||||
assert video_link.aweme_id_from_url("7353137957861084427") == "7353137957861084427"
|
||||
|
||||
|
||||
def test_aweme_id_from_url_rejects_a_creator_link():
|
||||
"""主页链接不是作品链接 —— 认不出来就该空着,而不是瞎猜一个 id。"""
|
||||
assert video_link.aweme_id_from_url(f"https://www.douyin.com/user/{SEC_UID}") == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_builds_a_profile_url(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "锋哥苏州寻宝藏小店", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
|
||||
|
||||
assert result["truncated"] is False
|
||||
item = result["results"][0]
|
||||
assert item["ok"] is True
|
||||
assert item["nickname"] == "锋哥苏州寻宝藏小店"
|
||||
assert item["profile_url"] == f"https://www.douyin.com/user/{SEC_UID}"
|
||||
assert item["error"] == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_short_links_are_expanded_before_parsing(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_expand(value, platform):
|
||||
calls.append((value, platform))
|
||||
return "https://www.iesdouyin.com/share/video/7353137957861084427/?region=CN"
|
||||
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "锋哥", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(service, "expand_short_link", fake_expand)
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve("https://v.douyin.com/iAbCdEf/")
|
||||
|
||||
assert calls == [("https://v.douyin.com/iAbCdEf/", "dy")]
|
||||
assert result["results"][0]["aweme_id"] == "7353137957861084427"
|
||||
assert result["results"][0]["ok"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_same_video_twice_only_hits_the_api_once(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_detail(aweme_id, **_):
|
||||
calls.append(aweme_id)
|
||||
return {"aweme_id": aweme_id, "nickname": "锋哥", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve(
|
||||
"https://www.douyin.com/video/7353137957861084427\n"
|
||||
"https://www.douyin.com/video/7353137957861084427"
|
||||
)
|
||||
|
||||
assert calls == ["7353137957861084427"]
|
||||
# 两条输入各自一行结果,但只有一次请求。
|
||||
assert [item["profile_url"] for item in result["results"]] == [
|
||||
f"https://www.douyin.com/user/{SEC_UID}",
|
||||
f"https://www.douyin.com/user/{SEC_UID}",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_one_failure_does_not_sink_the_batch(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
if aweme_id == "1111111111111111111":
|
||||
raise douyin_api.DouyinApiError("接口拒绝了请求")
|
||||
return {"aweme_id": aweme_id, "nickname": "好号", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve(
|
||||
"https://www.douyin.com/video/1111111111111111111\n"
|
||||
"https://www.douyin.com/video/7353137957861084427"
|
||||
)
|
||||
|
||||
first, second = result["results"]
|
||||
assert first["ok"] is False and "接口拒绝了" in first["error"]
|
||||
assert second["ok"] is True and second["profile_url"].endswith(SEC_UID)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_missing_sec_uid_is_reported_not_faked(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "空号", "creator_id": ""}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
|
||||
result = await video_link.resolve("https://www.douyin.com/video/7353137957861084427")
|
||||
|
||||
item = result["results"][0]
|
||||
assert item["ok"] is False
|
||||
assert item["profile_url"] == ""
|
||||
assert "sec_uid" in item["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_more_than_the_limit_is_truncated(monkeypatch):
|
||||
async def fake_detail(aweme_id, **_):
|
||||
return {"aweme_id": aweme_id, "nickname": "x", "creator_id": SEC_UID}
|
||||
|
||||
monkeypatch.setattr(douyin_api, "video_detail", fake_detail)
|
||||
text = "\n".join(f"https://www.douyin.com/video/{1000000000000000000 + i}" for i in range(25))
|
||||
|
||||
result = await video_link.resolve(text)
|
||||
|
||||
assert result["truncated"] is True
|
||||
assert len(result["results"]) == video_link.MAX_LINKS
|
||||
|
||||
|
||||
def test_garbage_input_yields_nothing():
|
||||
assert video_link.extract_candidates("随便说点什么") == []
|
||||
assert video_link.extract_candidates("") == []
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { Activity, BellRing, Download, FileText, MessageSquare, Plus } from 'lucide-react'
|
||||
import { Activity, BellRing, Download, FileText, Link2, MessageSquare, Plus } from 'lucide-react'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -18,6 +18,7 @@ import { RunHistory } from './RunHistory'
|
||||
import { StatTile } from './StatTile'
|
||||
import { TaskCard } from './TaskCard'
|
||||
import { TaskEditorDialog } from './TaskEditorDialog'
|
||||
import { VideoLinkTool } from './VideoLinkTool'
|
||||
|
||||
export function MonitorDashboard() {
|
||||
const { data: overview } = useMonitorOverview()
|
||||
@@ -31,6 +32,7 @@ export function MonitorDashboard() {
|
||||
|
||||
const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null)
|
||||
const [editorOpen, setEditorOpen] = useState(false)
|
||||
const [linkToolOpen, setLinkToolOpen] = useState(false)
|
||||
const [editingTask, setEditingTask] = useState<MonitorTask | null>(null)
|
||||
const [onlyNew, setOnlyNew] = useState(false)
|
||||
// 选中的标签。空数组 = 不筛。
|
||||
@@ -87,10 +89,22 @@ export function MonitorDashboard() {
|
||||
<span className="font-mono text-xs tracking-wider text-cyber-text-primary">
|
||||
监控任务
|
||||
</span>
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
新建
|
||||
</Button>
|
||||
<div className="flex items-center gap-1">
|
||||
{/* 手上只有一条作品链接时,先把它的号找出来 —— 建任务要的是主页里的 sec_uid。 */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setLinkToolOpen(true)}
|
||||
title="粘贴视频链接,换出博主主页"
|
||||
>
|
||||
<Link2 className="w-3 h-3 mr-1" />
|
||||
视频转主页
|
||||
</Button>
|
||||
<Button size="sm" onClick={openCreate}>
|
||||
<Plus className="w-3 h-3 mr-1" />
|
||||
新建
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto terminal-scroll space-y-2 pr-1">
|
||||
@@ -217,6 +231,7 @@ export function MonitorDashboard() {
|
||||
</div>
|
||||
|
||||
<TaskEditorDialog open={editorOpen} onOpenChange={setEditorOpen} task={editingTask} />
|
||||
<VideoLinkTool open={linkToolOpen} onOpenChange={setLinkToolOpen} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { AlertTriangle, Check, Copy, ExternalLink, Link2, Loader2 } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { useResolveVideoLinks } from '@/hooks/useMonitor'
|
||||
import { copyText } from '@/lib/clipboard'
|
||||
|
||||
interface VideoLinkToolProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
const TEXTAREA_CLASS =
|
||||
'w-full rounded-md border border-cyber-border-DEFAULT bg-cyber-bg-tertiary p-2 font-mono text-[11px] text-cyber-text-primary outline-none focus-visible:border-cyber-neon-cyan/50'
|
||||
|
||||
/**
|
||||
* 粘贴视频链接 → 拿博主主页。
|
||||
*
|
||||
* 只读不写:解析出来的主页地址不会自动变成监控任务,建不建由人决定 —— 一次粘十几条
|
||||
* 就顺手建十几个任务,不是这里该干的事。
|
||||
*/
|
||||
export function VideoLinkTool({ open, onOpenChange }: VideoLinkToolProps) {
|
||||
const [text, setText] = useState('')
|
||||
const [copied, setCopied] = useState('')
|
||||
const resolve = useResolveVideoLinks()
|
||||
|
||||
const results = resolve.data?.results ?? []
|
||||
const okCount = results.filter((item) => item.ok).length
|
||||
// 同一个博主发了好几条时只留一行 —— 复制一堆重复地址没有意义。
|
||||
const uniqueProfiles = useMemo(
|
||||
() => Array.from(new Set(results.map((item) => item.profile_url).filter(Boolean))),
|
||||
[results],
|
||||
)
|
||||
|
||||
const copy = async (value: string) => {
|
||||
if (await copyText(value)) {
|
||||
setCopied(value)
|
||||
window.setTimeout(() => setCopied(''), 1500)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 font-mono text-sm">
|
||||
<Link2 className="h-4 w-4 text-cyber-neon-cyan" />
|
||||
视频链接转博主主页
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-[11px] font-mono leading-relaxed">
|
||||
粘贴抖音视频链接或分享文案,一行一条,一次最多 20 条。
|
||||
解析走作品详情接口,需要一个能用的登录态。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
rows={5}
|
||||
placeholder={
|
||||
'https://www.douyin.com/video/7353137957861084427\n' +
|
||||
'7.42 复制打开抖音,看看【某某的作品】 https://v.douyin.com/iAbCdEf/\n' +
|
||||
'7353137957861084427'
|
||||
}
|
||||
className={TEXTAREA_CLASS}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => resolve.mutate(text)}
|
||||
disabled={!text.trim() || resolve.isPending}
|
||||
>
|
||||
{resolve.isPending ? (
|
||||
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Link2 className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
{resolve.isPending ? '解析中…' : '解析'}
|
||||
</Button>
|
||||
|
||||
{results.length > 0 && (
|
||||
<>
|
||||
<span className="font-mono text-[11px] text-cyber-text-muted">
|
||||
共 {results.length} 条,成功 {okCount} 条,去重后 {uniqueProfiles.length} 个博主
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="ml-auto"
|
||||
disabled={uniqueProfiles.length === 0}
|
||||
onClick={() => copy(uniqueProfiles.join('\n'))}
|
||||
>
|
||||
{copied === uniqueProfiles.join('\n') ? (
|
||||
<Check className="mr-1 h-3 w-3" />
|
||||
) : (
|
||||
<Copy className="mr-1 h-3 w-3" />
|
||||
)}
|
||||
复制全部主页
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{resolve.data?.truncated && (
|
||||
<p className="flex items-center gap-1 font-mono text-[11px] text-cyber-neon-orange">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
超过 20 条,只解析了前面的 20 条。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{results.length > 0 && (
|
||||
<div className="max-h-[320px] space-y-1 overflow-y-auto terminal-scroll pr-1">
|
||||
{results.map((item, index) => (
|
||||
<div
|
||||
key={`${item.input}-${index}`}
|
||||
className="flex items-center gap-2 rounded-md border border-cyber-border-subtle bg-cyber-bg-tertiary/60 px-2 py-1.5"
|
||||
>
|
||||
<span
|
||||
className={`h-1.5 w-1.5 flex-shrink-0 rounded-full ${
|
||||
item.ok ? 'bg-cyber-neon-green' : 'bg-cyber-neon-pink'
|
||||
}`}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
{item.ok ? (
|
||||
<>
|
||||
<div className="truncate font-mono text-[11px] text-cyber-text-primary">
|
||||
{item.nickname || '(无昵称)'}
|
||||
</div>
|
||||
<a
|
||||
href={item.profile_url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="block truncate font-mono text-[10px] text-cyber-neon-cyan hover:underline"
|
||||
>
|
||||
{item.profile_url}
|
||||
</a>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="truncate font-mono text-[10px] text-cyber-text-muted">
|
||||
{item.input}
|
||||
</div>
|
||||
<div className="truncate font-mono text-[10px] text-cyber-neon-pink">
|
||||
{item.error || '解析失败'}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{item.ok && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copy(item.profile_url)}
|
||||
title="复制主页链接"
|
||||
>
|
||||
{copied === item.profile_url ? (
|
||||
<Check className="h-3 w-3" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
<a
|
||||
href={item.profile_url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="text-cyber-text-muted hover:text-cyber-neon-cyan"
|
||||
title="在新标签页打开"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -438,6 +438,16 @@ export function useSendDailyDigest() {
|
||||
})
|
||||
}
|
||||
|
||||
// --- 视频链接 → 博主主页 ---------------------------------------------------
|
||||
|
||||
export function useResolveVideoLinks() {
|
||||
return useMutation({
|
||||
mutationFn: async (text: string) => (await monitorApi.resolveVideoLinks(text)).data,
|
||||
// 单条失败在结果里各自有 error,这里只管整批都没走到的情况(网络、鉴权)。
|
||||
onError: (error: Error) => toast.error(`解析失败:${error.message}`),
|
||||
})
|
||||
}
|
||||
|
||||
// --- 博主备注 --------------------------------------------------------------
|
||||
|
||||
export function useSetCreatorAlias() {
|
||||
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
SettingsResponse,
|
||||
TaskCreatePayload,
|
||||
UpstreamStatus,
|
||||
VideoLinkResolveResponse,
|
||||
WebhookStatus,
|
||||
} from '@/types/monitor'
|
||||
import type {
|
||||
@@ -308,6 +309,14 @@ export const monitorApi = {
|
||||
api.get<LoginState>('/monitor/login/state', { params: { force } }),
|
||||
|
||||
getWebhook: () => api.get<WebhookStatus>('/monitor/webhook'),
|
||||
/**
|
||||
* 视频链接/分享文案 → 博主主页。
|
||||
*
|
||||
* 后端逐条串行请求详情接口(一次最多 20 条),所以超时给得比默认的 30 秒宽 ——
|
||||
* 按 30 秒算会把一批本来能解析完的链接误报成失败。
|
||||
*/
|
||||
resolveVideoLinks: (text: string) =>
|
||||
api.post<VideoLinkResolveResponse>('/monitor/video-links', { text }, { timeout: 90_000 }),
|
||||
/** 昨天视频情况图:手动发一次(每天早上那条由后端按设置触发)。 */
|
||||
sendDailyDigest: (platform?: string) =>
|
||||
api.post<{ ok: boolean; rows: number; detail: string }>('/monitor/digest/send', null, {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* 复制文本。
|
||||
*
|
||||
* **必须留兜底**:这个站点是走 http://192.168.x.x:18051 访问的,不是安全上下文,
|
||||
* 浏览器在这种情况下根本不提供 `navigator.clipboard`(不是拒绝,是 undefined)。
|
||||
* 只写新 API 的话,局域网里点「复制」永远没反应。
|
||||
*/
|
||||
export async function copyText(value: string): Promise<boolean> {
|
||||
if (!value) return false
|
||||
|
||||
if (window.isSecureContext && navigator.clipboard) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
return true
|
||||
} catch {
|
||||
// 落到下面的兜底
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const area = document.createElement('textarea')
|
||||
area.value = value
|
||||
// 定位到视口外而不是 display:none —— 隐藏元素选不中,复制会失败。
|
||||
area.style.position = 'fixed'
|
||||
area.style.top = '-1000px'
|
||||
area.style.opacity = '0'
|
||||
document.body.appendChild(area)
|
||||
area.select()
|
||||
const ok = document.execCommand('copy')
|
||||
document.body.removeChild(area)
|
||||
return ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -551,3 +551,24 @@ export interface MonitorIdentity {
|
||||
last_ok_at: number | null
|
||||
last_error: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 「视频链接 → 博主主页」的一条结果。
|
||||
*
|
||||
* `ok` 为 false 时 `error` 一定有值 —— 批量粘贴时每条各自成败,不能整批共用一个错误。
|
||||
*/
|
||||
export interface VideoLinkResult {
|
||||
input: string
|
||||
aweme_id: string
|
||||
ok: boolean
|
||||
nickname: string
|
||||
sec_uid: string
|
||||
profile_url: string
|
||||
error: string
|
||||
}
|
||||
|
||||
export interface VideoLinkResolveResponse {
|
||||
results: VideoLinkResult[]
|
||||
/** 超过一次能解析的上限,后面的没处理 —— 前端要说出来,不能默默截断。 */
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user