@vitex/tcm-cli 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -97,11 +97,22 @@ tcm logout
97
97
  | 退出码 | 含义 |
98
98
  | --- | --- |
99
99
  | `0` | 成功 |
100
- | `1` | 业务/网络/授权错误(`ApiError`) |
100
+ | `1` | 业务/网络/授权错误(`ApiError`),或本地工具执行失败(`ToolError`,见下) |
101
101
  | `2` | 参数或用法错误(`UsageError`) |
102
102
 
103
103
  业务失败(HTTP 200 但 `code !== 1`)与 HTTP 非 2xx 都会被视为失败。触发限流时后端返回 `HTTP 429`,错误的 `data.retryAfterMs` 给出建议重试等待毫秒数。
104
104
 
105
+ `tool` 分组下的命令在本地直接抓第三方页面(不经过 TCM 后端),失败时 `type` 为具体原因:
106
+
107
+ ```json
108
+ { "error": { "type": "FetchError", "message": "抓取抖音页面失败(…):HTTP 404", "status": 404 } }
109
+ ```
110
+
111
+ | `type` | 含义 |
112
+ | --- | --- |
113
+ | `FetchError` | 网络失败 / 超时 / HTTP 非 2xx,带 `status` |
114
+ | `ParseError` | 页面结构不符(视频不存在、被风控、抖音改版) |
115
+
105
116
  ## 参数约定
106
117
 
107
118
  - 标量:`--pageNum 1`、`--status NORMAL`
@@ -128,11 +139,9 @@ tcm logout
128
139
 
129
140
  - `tcm user list` — 分页查询用户(管理员)
130
141
  - `tcm user me` — 当前登录用户
131
- - `tcm user create` — 新建用户(返回仅此一次可见的明文密码)
142
+ - `tcm user create` — 新建用户
132
143
  - `tcm user update` — 编辑用户
133
- - `tcm user reset-password` — 重置用户密码
134
144
  - `tcm user api-key` — 获取当前用户 API Key(旧 Key 立即失效)
135
- - `tcm user change-password` — 修改当前用户密码
136
145
 
137
146
  ### workbench — 工作台统计
138
147
 
@@ -147,6 +156,8 @@ tcm logout
147
156
 
148
157
  `list`、`get`、`create`、`update`、`status`、`names`、`summary`、`logs`、`statistics`
149
158
 
159
+ 机器对象带两个 IP 字段:`ip` 是内网 IP,`publicIp` 是 Agent 心跳时探测的公网出口 IP(探测失败为 `null`,不携带该字段的旧 Agent 也是 `null`)。`machine list` / `machine get` 与工作台 `workbench machine-cards` 都返回 `publicIp`;`--keyword` 只匹配 `ip`(内网)等文本字段,不能按 `publicIp` 搜索。
160
+
150
161
  ### account — 账号
151
162
 
152
163
  `list`、`get`、`update`、`status`、`toggle-verify`、`brief`、`summary`、`logs`、`cookies`
@@ -182,6 +193,30 @@ tcm logout
182
193
  - `draft`:`list`、`create`、`create-urls`、`discard`
183
194
  - `item`:`list`
184
195
 
196
+ ### tool — 本地取数工具
197
+
198
+ 本地执行、直接抓第三方公开页面,**不经过 TCM 后端、不需要登录、不写库**。
199
+
200
+ - `tcm tool seo_video_detail --id <awemeId>` — 按视频 ID 取抖音 SEO 版视频页:视频(文案 / 封面 / 发布时间 / 时长 / 点赞 / 评论 / 收藏 / 分享)、达人(昵称 / secUid / 获赞 / 粉丝)、首屏 10 条评论
201
+ - 也支持 `--url <链接或分享文案>`(短链会自动跟随跳转)与 `--html <本地文件>`(离线解析已保存的页面)
202
+ - `--proxy <user:pass@host:port>` 可让抓取走公司 HTTP 代理(如 `--proxy proxy:xxxx@10.175.4.62:8081`)
203
+ - 点赞 / 收藏 / 分享来自页面展示文本(`5.4万` → `54000`),是**近似值**;评论数取 ld+json 的精确值
204
+ - 只有首屏 10 条一级评论,没有视频直链 / 音乐 / 弹幕
205
+
206
+ ```bash
207
+ # 按 ID
208
+ tcm tool seo_video_detail --id 7701278853448142120 --compact
209
+
210
+ # 按链接(分享文案也行)
211
+ tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120
212
+
213
+ # 走 HTTP 代理(user:pass@host:port)
214
+ tcm tool seo_video_detail --id 7701278853448142120 --proxy "proxy:617a6e1e066d3d31@10.175.4.62:8081"
215
+
216
+ # 离线重放(排查页面改版用)
217
+ tcm tool seo_video_detail --html ./page.html --compact
218
+ ```
219
+
185
220
  每个命令都支持 `--help` 查看完整参数,例如:
186
221
 
187
222
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitex/tcm-cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "TCM 控制台命令行工具(面向 agent,JSON 输入输出)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,6 +16,7 @@ import hotComment from './hot-comment.js'
16
16
  import material from './material.js'
17
17
  import draft from './draft.js'
18
18
  import item from './item.js'
19
+ import tool from './tool.js'
19
20
  import { topCommands } from './auth.js'
20
21
 
21
22
  export const groups = {
@@ -37,6 +38,7 @@ export const groups = {
37
38
  material,
38
39
  draft,
39
40
  item,
41
+ tool,
40
42
  }
41
43
 
42
44
  export { topCommands }
@@ -6,7 +6,7 @@ export default {
6
6
  list: {
7
7
  summary: '分页查询机器',
8
8
  params: {
9
- keyword: string('关键词'),
9
+ keyword: string('关键词(匹配名称/备注/主机名/用户名/内网 IP/MAC)'),
10
10
  os: string('操作系统:MAC / WINDOWS / LINUX'),
11
11
  statuses: array('状态多选:INIT / NORMAL / HIDDEN'),
12
12
  health: string('健康状态:ONLINE / OFFLINE'),
@@ -0,0 +1,51 @@
1
+ import { UsageError } from '../args.js'
2
+ import { DEFAULT_TIMEOUT_MS } from '../config.js'
3
+ import { parseProxy } from '../proxy.js'
4
+ import { seoVideoDetail } from '../seo-video.js'
5
+ import { string } from './common.js'
6
+
7
+ function timeoutMs(global) {
8
+ const raw = global?.timeout
9
+ if (raw === undefined) return DEFAULT_TIMEOUT_MS
10
+ const value = Number(raw)
11
+ if (!Number.isFinite(value) || value <= 0) {
12
+ throw new UsageError('--timeout 需要是正整数(毫秒)')
13
+ }
14
+ return value
15
+ }
16
+
17
+ export default {
18
+ summary: '本地取数工具(抓第三方公开页面,不写 TCM)',
19
+ commands: {
20
+ seo_video_detail: {
21
+ summary: '按视频 ID 取抖音视频详情:视频 / 达人 / 首屏评论',
22
+ auth: false,
23
+ params: {
24
+ id: string('视频 ID(awemeId,按字符串传,19 位数字)'),
25
+ url: string('视频链接(也接受分享文案;短链会自动跟随跳转)'),
26
+ html: string('解析本地已保存的 HTML(离线调试,忽略 --id / --url)'),
27
+ proxy: string('走 HTTP 代理,格式 proxy:password@host:port'),
28
+ },
29
+ examples: [
30
+ 'tcm tool seo_video_detail --id 7701278853448142120',
31
+ 'tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120',
32
+ 'tcm tool seo_video_detail --url "7.43 复制打开抖音… https://v.douyin.com/xxxx/" --compact',
33
+ 'tcm tool seo_video_detail --id 7701278853448142120 --proxy "proxy:617a6e1e066d3d31@10.175.4.62:8081"',
34
+ 'tcm tool seo_video_detail --html ./page.html --compact',
35
+ ],
36
+ async run({ values, global }) {
37
+ const id = values.id?.trim()
38
+ const url = values.url?.trim()
39
+ const htmlPath = values.html?.trim()
40
+ const proxy = parseProxy(values.proxy)
41
+
42
+ if (!htmlPath) {
43
+ if (!id && !url) throw new UsageError('需要 --id 或 --url(--html 用于解析本地文件)')
44
+ if (id && url) throw new UsageError('--id 和 --url 只能传一个')
45
+ }
46
+
47
+ return seoVideoDetail({ id, url, htmlPath, timeoutMs: timeoutMs(global), proxy })
48
+ },
49
+ },
50
+ },
51
+ }
@@ -18,38 +18,30 @@ export default {
18
18
  build: () => get('/api/user/me'),
19
19
  },
20
20
  create: {
21
- summary: '新建用户(返回仅此一次可见的明文密码)',
21
+ summary: '新建用户',
22
22
  params: {
23
23
  name: string('用户名', { required: true }),
24
+ email: string('登录邮箱', { required: true }),
24
25
  description: string('备注'),
25
26
  roles: array('角色,例如 ADMIN', { items: 'string' }),
26
27
  },
27
- build: (p) => post('/api/user/create', pick(p, ['name', 'description', 'roles'])),
28
+ build: (p) => post('/api/user/create', pick(p, ['name', 'email', 'description', 'roles'])),
28
29
  },
29
30
  update: {
30
31
  summary: '编辑用户',
31
32
  params: {
32
33
  id: id('用户 ID'),
33
34
  name: string('用户名', { required: true }),
35
+ email: string('登录邮箱', { required: true }),
34
36
  description: string('备注'),
35
37
  roles: array('角色,例如 ADMIN', { items: 'string' }),
36
38
  },
37
- build: (p) => post('/api/user/update', pick(p, ['id', 'name', 'description', 'roles'])),
38
- },
39
- 'reset-password': {
40
- summary: '重置用户密码(返回仅此一次可见的明文密码)',
41
- params: { id: id('用户 ID') },
42
- build: (p) => post('/api/user/resetpassword', pick(p, ['id'])),
39
+ build: (p) => post('/api/user/update', pick(p, ['id', 'name', 'email', 'description', 'roles'])),
43
40
  },
44
41
  'api-key': {
45
42
  summary: '获取当前用户 API Key(旧 Key 立即失效)',
46
43
  params: {},
47
44
  build: () => post('/api/user/apikey'),
48
45
  },
49
- 'change-password': {
50
- summary: '修改当前用户密码',
51
- params: { password: string('新密码', { required: true }) },
52
- build: (p) => post('/api/user/changepassword', pick(p, ['password'])),
53
- },
54
46
  },
55
47
  }
package/src/index.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  parseCommandArgs,
8
8
  } from './args.js'
9
9
  import { groups, topCommands } from './commands/index.js'
10
+ import { ToolError } from './tool-error.js'
10
11
 
11
12
  const GLOBAL_OPTIONS = {
12
13
  help: { type: 'boolean', short: 'h' },
@@ -133,6 +134,13 @@ function handleError(error, compact) {
133
134
  if (error instanceof UsageError) {
134
135
  type = 'UsageError'
135
136
  exitCode = 2
137
+ } else if (error instanceof ToolError) {
138
+ type = error.type || 'ToolError'
139
+ body = {
140
+ message: error.message,
141
+ ...(error.status !== null && error.status !== undefined ? { status: error.status } : {}),
142
+ ...(error.data ? { data: error.data } : {}),
143
+ }
136
144
  } else if (error instanceof ApiError) {
137
145
  type = 'ApiError'
138
146
  body = { message: error.message, code: error.code, status: error.status, data: error.data }
package/src/proxy.js ADDED
@@ -0,0 +1,227 @@
1
+ /**
2
+ * 极简 HTTP 代理支持(CONNECT 隧道)。CLI 零运行时依赖,所以不用 undici 的 ProxyAgent。
3
+ *
4
+ * `--proxy` 只接受 `user:pass@host:port`(对应 fetcher proxies.json 里的同一台代理)。
5
+ */
6
+ import http from 'node:http'
7
+ import net from 'node:net'
8
+ import tls from 'node:tls'
9
+ import zlib from 'node:zlib'
10
+ import { UsageError } from './args.js'
11
+ import { ToolError } from './tool-error.js'
12
+
13
+ const MAX_REDIRECTS = 5
14
+ const REDIRECT_CODES = new Set([301, 302, 303, 307, 308])
15
+
16
+ function hostPort(host, port, raw) {
17
+ const text = String(host ?? '').trim()
18
+ if (!text) throw new UsageError(`--proxy 缺少 host:${raw}`)
19
+ const value = Number(String(port ?? '').trim())
20
+ if (!Number.isInteger(value) || value <= 0 || value > 65535) {
21
+ throw new UsageError(`--proxy 的 port 需要是 1-65535:${raw}`)
22
+ }
23
+ return { host: text, port: value }
24
+ }
25
+
26
+ /** 代理地址字符串 -> { host, port, username, password };空值返回 null。只支持 user:pass@host:port。 */
27
+ export function parseProxy(text) {
28
+ if (text === undefined || text === null) return null
29
+ const raw = String(text).trim()
30
+ if (!raw) return null
31
+
32
+ const at = raw.lastIndexOf('@')
33
+ const credentials = at === -1 ? '' : raw.slice(0, at)
34
+ const server = at === -1 ? '' : raw.slice(at + 1)
35
+ const separator = server.lastIndexOf(':')
36
+ const colon = credentials.indexOf(':')
37
+ if (raw.includes('://') || at === -1 || colon <= 0 || separator <= 0) {
38
+ throw new UsageError(`--proxy 只支持 user:pass@host:port 格式:${raw}`)
39
+ }
40
+
41
+ const username = credentials.slice(0, colon)
42
+ const password = credentials.slice(colon + 1)
43
+ const { host, port } = hostPort(server.slice(0, separator), server.slice(separator + 1), raw)
44
+ return { host, port, username, password }
45
+ }
46
+
47
+ export function proxyLabel(proxy) {
48
+ return `${proxy.host}:${proxy.port}`
49
+ }
50
+
51
+ function tunnel(proxy, target, timeoutMs) {
52
+ return new Promise((resolve, reject) => {
53
+ const socket = net.connect({ host: proxy.host, port: proxy.port })
54
+ let done = false
55
+ const timer = setTimeout(() => fail(new Error(`连接代理超时(${timeoutMs}ms)`)), timeoutMs)
56
+
57
+ function fail(error) {
58
+ if (done) return
59
+ done = true
60
+ clearTimeout(timer)
61
+ socket.destroy()
62
+ reject(error)
63
+ }
64
+
65
+ socket.once('error', fail)
66
+ socket.once('connect', () => {
67
+ const authority = `${target.hostname}:${target.port || (target.protocol === 'https:' ? 443 : 80)}`
68
+ const lines = [`CONNECT ${authority} HTTP/1.1`, `Host: ${authority}`]
69
+ if (proxy.username || proxy.password) {
70
+ const token = Buffer.from(`${proxy.username ?? ''}:${proxy.password ?? ''}`).toString('base64')
71
+ lines.push(`Proxy-Authorization: Basic ${token}`)
72
+ }
73
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`)
74
+
75
+ let buffer = Buffer.alloc(0)
76
+ const onData = (chunk) => {
77
+ buffer = Buffer.concat([buffer, chunk])
78
+ const end = buffer.indexOf('\r\n\r\n')
79
+ if (end === -1) {
80
+ if (buffer.length > 16 * 1024) fail(new Error('代理返回的 CONNECT 响应头过大'))
81
+ return
82
+ }
83
+ socket.off('data', onData)
84
+ socket.off('error', fail)
85
+ const head = buffer.subarray(0, end).toString('latin1')
86
+ const status = Number(head.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/)?.[1])
87
+ if (status !== 200) {
88
+ fail(new Error(`代理拒绝隧道:${head.split('\r\n')[0] || '无响应'}`))
89
+ return
90
+ }
91
+ done = true
92
+ clearTimeout(timer)
93
+ // 后面交给 http 请求,出错由请求自己处理;这里只兜底,避免未监听的 'error' 让进程崩溃
94
+ socket.on('error', () => {})
95
+ const rest = buffer.subarray(end + 4)
96
+ if (rest.length) socket.unshift(rest)
97
+ resolve(socket)
98
+ }
99
+ socket.on('data', onData)
100
+ })
101
+ })
102
+ }
103
+
104
+ function secure(socket, target, timeoutMs) {
105
+ return new Promise((resolve, reject) => {
106
+ const options = { socket }
107
+ if (net.isIP(target.hostname) === 0) options.servername = target.hostname
108
+ const tlsSocket = tls.connect(options)
109
+ const timer = setTimeout(() => {
110
+ tlsSocket.destroy()
111
+ reject(new Error(`TLS 握手超时(${timeoutMs}ms)`))
112
+ }, timeoutMs)
113
+ tlsSocket.once('secureConnect', () => {
114
+ clearTimeout(timer)
115
+ resolve(tlsSocket)
116
+ })
117
+ tlsSocket.once('error', (error) => {
118
+ clearTimeout(timer)
119
+ reject(error)
120
+ })
121
+ })
122
+ }
123
+
124
+ function decodeBody(buffer, encoding) {
125
+ const name = String(encoding || '').trim().toLowerCase()
126
+ try {
127
+ if (name === 'gzip') return zlib.gunzipSync(buffer)
128
+ if (name === 'deflate') return zlib.inflateSync(buffer)
129
+ if (name === 'br') return zlib.brotliDecompressSync(buffer)
130
+ } catch {
131
+ return buffer
132
+ }
133
+ return buffer
134
+ }
135
+
136
+ /** 把已建好的隧道 socket 交给 http 请求(Node 会忽略 ClientRequest 上的 createConnection,只能是 Agent)。 */
137
+ class TunnelAgent extends http.Agent {
138
+ constructor(socket) {
139
+ super({ keepAlive: false, maxSockets: 1 })
140
+ this.tunneled = socket
141
+ }
142
+
143
+ createConnection() {
144
+ const socket = this.tunneled
145
+ this.tunneled = null
146
+ return socket
147
+ }
148
+ }
149
+
150
+ function requestOverSocket(target, { headers, socket, timeoutMs }) {
151
+ return new Promise((resolve, reject) => {
152
+ const req = http.request(
153
+ {
154
+ method: 'GET',
155
+ host: target.hostname,
156
+ port: target.port || (target.protocol === 'https:' ? 443 : 80),
157
+ path: `${target.pathname}${target.search}`,
158
+ headers,
159
+ agent: new TunnelAgent(socket),
160
+ },
161
+ (res) => {
162
+ const chunks = []
163
+ res.on('data', (chunk) => chunks.push(chunk))
164
+ res.on('error', reject)
165
+ res.on('end', () => {
166
+ resolve({
167
+ status: res.statusCode,
168
+ headers: res.headers,
169
+ body: decodeBody(Buffer.concat(chunks), res.headers['content-encoding']).toString('utf8'),
170
+ })
171
+ })
172
+ },
173
+ )
174
+ req.setTimeout(timeoutMs, () => req.destroy(new Error(`请求超时(${timeoutMs}ms)`)))
175
+ req.on('error', reject)
176
+ req.end()
177
+ })
178
+ }
179
+
180
+ /**
181
+ * 经 HTTP 代理 GET 一个 URL,自动跟随重定向。
182
+ * 网络/代理错误抛 ToolError(FetchError);HTTP 非 2xx 原样返回状态码,由调用方决定文案。
183
+ */
184
+ export async function fetchThroughProxy(url, { headers = {}, timeoutMs = 30000, proxy }) {
185
+ let target
186
+ try {
187
+ target = new URL(url)
188
+ } catch {
189
+ throw new UsageError(`不是合法 URL:${url}`)
190
+ }
191
+
192
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
193
+ let response
194
+ try {
195
+ const raw = await tunnel(proxy, target, timeoutMs)
196
+ try {
197
+ const socket = target.protocol === 'https:' ? await secure(raw, target, timeoutMs) : raw
198
+ try {
199
+ response = await requestOverSocket(target, {
200
+ headers: { 'Accept-Encoding': 'identity', ...headers },
201
+ socket,
202
+ timeoutMs,
203
+ })
204
+ } finally {
205
+ socket.destroy()
206
+ }
207
+ } finally {
208
+ raw.destroy()
209
+ }
210
+ } catch (error) {
211
+ const reason = error?.message || '网络请求失败'
212
+ throw new ToolError(`抓取抖音页面失败(${target.toString()}):代理 ${proxyLabel(proxy)} ${reason}`, {
213
+ type: 'FetchError',
214
+ data: { proxy: proxyLabel(proxy) },
215
+ })
216
+ }
217
+
218
+ const location = response.headers?.location
219
+ if (REDIRECT_CODES.has(response.status) && location) {
220
+ target = new URL(location, target)
221
+ continue
222
+ }
223
+ return { status: response.status, html: response.body, finalUrl: target.toString() }
224
+ }
225
+
226
+ throw new ToolError(`抓取抖音页面失败(${url}):重定向超过 ${MAX_REDIRECTS} 次`, { type: 'FetchError' })
227
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * 抖音 SEO 版视频页解析(本地执行,不经 TCM 后端)。
3
+ *
4
+ * 原理:用搜索引擎 UA 直接 GET 视频页,抖音会回一份带 SEO 数据的 SSR HTML:
5
+ * - `<script type="application/ld+json">` 里的 VideoObject:文案、封面、发布时间、时长、
6
+ * 评论总数、达人信息、首屏 10 条评论;
7
+ * - 首屏 DOM 里的统计块:点赞 / 评论 / 收藏 / 分享(`5.4万` 这种缩写,文本展示值)。
8
+ * 两者合起来就是一条视频的完整公开快照。不需要 Cookie,也没有签名接口。
9
+ */
10
+ import fs from 'node:fs'
11
+ import { UsageError } from './args.js'
12
+ import { fetchThroughProxy } from './proxy.js'
13
+ import { ToolError } from './tool-error.js'
14
+
15
+ export const SEO_UA = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
16
+ const VIDEO_PAGE = 'https://www.douyin.com/video/'
17
+ const BASE_URL = 'https://www.douyin.com'
18
+
19
+ /** 从视频链接 / 分享文案里抠出 awemeId。 */
20
+ export function videoIdFrom(text) {
21
+ if (!text) return null
22
+ const value = String(text)
23
+ const match = value.match(/\/(?:video|share\/video|note)\/(\d{10,25})/) || value.match(/^\s*(\d{10,25})\s*$/)
24
+ return match ? match[1] : null
25
+ }
26
+
27
+ /** 抖音缩写数字 -> 整数:'5.4万' -> 54000、'4587' -> 4587、'1.2亿' -> 120000000。 */
28
+ export function abbrevToInt(text) {
29
+ if (text === null || text === undefined) return null
30
+ const match = String(text).replace(/,/g, '').trim().match(/^([\d.]+)\s*([万亿wWkK]?)$/)
31
+ if (!match) return null
32
+ const unit = { 万: 10000, w: 10000, W: 10000, 亿: 100000000, k: 1000, K: 1000, '': 1 }[match[2]]
33
+ return Math.round(Number(match[1]) * unit)
34
+ }
35
+
36
+ /** ISO 8601 时长 -> 秒:'PT0H1M8S' -> 68。 */
37
+ export function isoDurationSeconds(value) {
38
+ const match = String(value || '').match(/^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?$/)
39
+ if (!match) return null
40
+ const [h, m, s] = match.slice(1).map((part) => (part ? Number(part) : 0))
41
+ return Math.floor(h * 3600 + m * 60 + s)
42
+ }
43
+
44
+ /** 修掉抖音在带时区的时间后面多写的 Z:'2026-10-27T17:35:19+08:00Z' -> '…+08:00'。 */
45
+ export function normalizeIsoTime(value) {
46
+ if (!value) return null
47
+ const text = String(value)
48
+ return /[+-]\d{2}:\d{2}Z$/.test(text) ? text.slice(0, -1) : text
49
+ }
50
+
51
+ export function absoluteUrl(url, base = BASE_URL) {
52
+ if (!url) return null
53
+ const text = String(url)
54
+ if (/^https?:\/\//i.test(text)) return text
55
+ return text.startsWith('/') ? `${base}${text}` : text
56
+ }
57
+
58
+ export function secUidFrom(url) {
59
+ const match = String(url || '').match(/\/user\/(MS4wLjABAAAA[\w-]+)/)
60
+ return match ? match[1] : null
61
+ }
62
+
63
+ /** interactionStatistic 里的动作类型可能是字符串、{ '@type' } 对象或 { value },统一成字符串。 */
64
+ function interactionName(item) {
65
+ const type = item?.interactionType
66
+ if (!type) return ''
67
+ if (typeof type === 'string') return type
68
+ return String(type['@type'] ?? type.value ?? JSON.stringify(type))
69
+ }
70
+
71
+ /** interactionStatistic 里按 LikeAction / FollowAction 取数,兼容单个对象与数组。 */
72
+ function counterOf(statistic, action) {
73
+ const items = Array.isArray(statistic) ? statistic : statistic ? [statistic] : []
74
+ for (const item of items) {
75
+ if (interactionName(item).includes(action)) {
76
+ return item?.userInteractionCount ?? null
77
+ }
78
+ }
79
+ return null
80
+ }
81
+
82
+ /** 取出 ld+json 里的 VideoObject(页面里可能有多段 ld+json)。 */
83
+ export function parseVideoObject(html) {
84
+ const text = String(html || '')
85
+ const blocks = text.matchAll(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)
86
+ for (const block of blocks) {
87
+ let parsed
88
+ try {
89
+ parsed = JSON.parse(block[1])
90
+ } catch {
91
+ continue
92
+ }
93
+ if (parsed && typeof parsed === 'object' && parsed['@type'] === 'VideoObject') return parsed
94
+ }
95
+ const message = /VideoObject/.test(text)
96
+ ? '页面里的 ld+json VideoObject 不是合法 JSON(抖音可能改版)'
97
+ : '页面里没有 ld+json VideoObject:可能不是搜索引擎 UA 返回的页面、视频不存在/已删除,或抖音改版'
98
+ throw new ToolError(message, { type: 'ParseError' })
99
+ }
100
+
101
+ /**
102
+ * 首屏统计块里的四个数——ld+json 里没有。
103
+ * 结构固定:前三格是 `<span class="hIpNkUXt">`(赞 / 评 / 藏),
104
+ * 分享格是 `data-e2e="video-share-icon-container"` 里的 `<span class="sB3y0d3B">`。
105
+ */
106
+ export function domStats(html) {
107
+ const block = String(html || '').match(/<div class="pWR86eZK">([\s\S]*?)<div class="o9W_EAcI">/)
108
+ if (!block) return {}
109
+ const seg = block[1]
110
+ const shorts = [...seg.matchAll(/<span class="hIpNkUXt">([^<]+)<\/span>/g)].map((m) => m[1])
111
+ const share = [...seg.matchAll(/<span class="sB3y0d3B">([^<]+)<\/span>/g)].map((m) => m[1])
112
+ const stats = {}
113
+ const keys = ['like_count', 'comment_count', 'collect_count']
114
+ keys.forEach((key, index) => {
115
+ if (shorts[index] !== undefined) stats[key] = abbrevToInt(shorts[index])
116
+ })
117
+ if (share[0] !== undefined) stats.share_count = abbrevToInt(share[0])
118
+ return stats
119
+ }
120
+
121
+ /** 把 VideoObject + DOM 统计转成对外输出结构。 */
122
+ export function buildSnapshot({ videoObject, videoId, html }) {
123
+ const vo = videoObject || {}
124
+ const creator = vo.creator || {}
125
+ const stats = domStats(html)
126
+
127
+ // description 只从 name 解析:去掉站名尾巴「- 抖音」和 #话题
128
+ const name = String(vo.name || '')
129
+ const head = name.replace(/\s+-\s+抖音$/, '').trim()
130
+ const description = head.replace(/#[^\s#]+/g, ' ').replace(/\s{2,}/g, ' ').trim() || head || null
131
+
132
+ const comments = (Array.isArray(vo.comment) ? vo.comment : []).map((comment) => {
133
+ const user = comment?.creator || {}
134
+ return {
135
+ text: comment?.text ?? null,
136
+ user: {
137
+ name: user.name ?? null,
138
+ sec_uid: secUidFrom(user.url),
139
+ profile_url: absoluteUrl(user.url),
140
+ },
141
+ like_count: counterOf(comment?.interactionStatistic, 'LikeAction'),
142
+ }
143
+ })
144
+
145
+ return {
146
+ video: {
147
+ id: videoId,
148
+ description,
149
+ cover_urls: Array.isArray(vo.thumbnailUrl) ? vo.thumbnailUrl : [],
150
+ publish_time: normalizeIsoTime(vo.uploadDate),
151
+ duration_seconds: isoDurationSeconds(vo.duration),
152
+ // 点赞/收藏/分享只能从 DOM 展示文本解析(万/亿 缩写 -> 整数,近似值);
153
+ // 评论数优先用 ld+json 的精确值,缺失时回退 DOM
154
+ like_count: stats.like_count ?? null,
155
+ comment_count: vo.commentCount ?? stats.comment_count ?? null,
156
+ collect_count: stats.collect_count ?? null,
157
+ share_count: stats.share_count ?? null,
158
+ },
159
+ creator: {
160
+ name: creator.name ?? null,
161
+ sec_uid: secUidFrom(creator.url),
162
+ profile_url: absoluteUrl(creator.url),
163
+ like_count: counterOf(creator.interactionStatistic, 'LikeAction'),
164
+ follower_count: counterOf(creator.interactionStatistic, 'FollowAction'),
165
+ },
166
+ comments,
167
+ }
168
+ }
169
+
170
+ async function fetchHtml(url, timeoutMs, proxy) {
171
+ const headers = {
172
+ 'User-Agent': SEO_UA,
173
+ Accept: 'text/html,application/xhtml+xml',
174
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
175
+ }
176
+ if (proxy) {
177
+ const { status, html, finalUrl } = await fetchThroughProxy(url, { headers, timeoutMs, proxy })
178
+ if (status < 200 || status >= 300) {
179
+ throw new ToolError(`抓取抖音页面失败(${url}):HTTP ${status}(经代理 ${proxy.host}:${proxy.port})`, {
180
+ type: 'FetchError',
181
+ status,
182
+ })
183
+ }
184
+ return { html, finalUrl }
185
+ }
186
+ let response
187
+ try {
188
+ response = await fetch(url, { headers, redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
189
+ } catch (error) {
190
+ const reason =
191
+ error?.name === 'TimeoutError' || error?.name === 'AbortError'
192
+ ? `请求超时(${timeoutMs}ms)`
193
+ : error?.message || '网络请求失败'
194
+ throw new ToolError(`抓取抖音页面失败(${url}):${reason}`, { type: 'FetchError' })
195
+ }
196
+ const html = await response.text().catch(() => '')
197
+ if (!response.ok) {
198
+ throw new ToolError(`抓取抖音页面失败(${url}):HTTP ${response.status}`, {
199
+ type: 'FetchError',
200
+ status: response.status,
201
+ })
202
+ }
203
+ return { html, finalUrl: response.url || url }
204
+ }
205
+
206
+ /**
207
+ * 主入口:按视频 ID / 链接 / 本地 HTML 返回 { video, creator, comments }。
208
+ * `proxy` 为 parseProxy() 的结果;传了就走代理(CONNECT 隧道),不传直连。
209
+ * 失败抛 ToolError(FetchError / ParseError)或 UsageError(参数问题)。
210
+ */
211
+ export async function seoVideoDetail({ id, url, htmlPath, timeoutMs = 30000, proxy = null }) {
212
+ if (htmlPath) {
213
+ try {
214
+ const html = fs.readFileSync(htmlPath, 'utf8')
215
+ const videoId =
216
+ html.match(/rel="canonical"[^>]*href="[^"]*\/video\/(\d+)"/)?.[1] ||
217
+ videoIdFrom(url) ||
218
+ (id ? String(id) : null)
219
+ return buildSnapshot({ videoObject: parseVideoObject(html), videoId, html })
220
+ } catch (error) {
221
+ if (error instanceof ToolError) throw error
222
+ throw new UsageError(`读取 --html 失败:${error.message}`)
223
+ }
224
+ }
225
+
226
+ const target = id
227
+ ? `${VIDEO_PAGE}${encodeURIComponent(String(id).trim())}`
228
+ : /^https?:\/\//i.test(String(url))
229
+ ? String(url).trim()
230
+ : `https://${String(url).trim()}`
231
+ const { html, finalUrl } = await fetchHtml(target, timeoutMs, proxy)
232
+ const videoId =
233
+ html.match(/rel="canonical"[^>]*href="[^"]*\/video\/(\d+)"/)?.[1] ||
234
+ videoIdFrom(finalUrl) ||
235
+ videoIdFrom(id) ||
236
+ videoIdFrom(url)
237
+ if (!videoId) {
238
+ throw new ToolError('无法确定视频 ID(页面没有 canonical,入参也解析不到)', { type: 'ParseError' })
239
+ }
240
+ return buildSnapshot({ videoObject: parseVideoObject(html), videoId, html })
241
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 非 TCM 后端类错误(例如本地 `tool` 命令抓取第三方页面失败)。
3
+ *
4
+ * 与 ApiError 区分开:ApiError 表示「服务端返回了错误」,ToolError 表示
5
+ * 「本地工具执行失败」,输出里 type 保留具体原因(FetchError / ParseError)。
6
+ */
7
+ export class ToolError extends Error {
8
+ constructor(message, { type = 'ToolError', status = null, data = null } = {}) {
9
+ super(message)
10
+ this.name = type
11
+ this.type = type
12
+ this.status = status
13
+ this.data = data
14
+ }
15
+ }