@vitex/tcm-cli 0.2.0 → 0.3.0

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,26 @@ 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
+ - 点赞 / 收藏 / 分享来自页面展示文本(`5.4万` → `54000`),是**近似值**;评论数取 ld+json 的精确值
203
+ - 只有首屏 10 条一级评论,没有视频直链 / 音乐 / 弹幕
204
+
205
+ ```bash
206
+ # 按 ID
207
+ tcm tool seo_video_detail --id 7701278853448142120 --compact
208
+
209
+ # 按链接(分享文案也行)
210
+ tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120
211
+
212
+ # 离线重放(排查页面改版用)
213
+ tcm tool seo_video_detail --html ./page.html --compact
214
+ ```
215
+
185
216
  每个命令都支持 `--help` 查看完整参数,例如:
186
217
 
187
218
  ```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.0",
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,47 @@
1
+ import { UsageError } from '../args.js'
2
+ import { DEFAULT_TIMEOUT_MS } from '../config.js'
3
+ import { seoVideoDetail } from '../seo-video.js'
4
+ import { string } from './common.js'
5
+
6
+ function timeoutMs(global) {
7
+ const raw = global?.timeout
8
+ if (raw === undefined) return DEFAULT_TIMEOUT_MS
9
+ const value = Number(raw)
10
+ if (!Number.isFinite(value) || value <= 0) {
11
+ throw new UsageError('--timeout 需要是正整数(毫秒)')
12
+ }
13
+ return value
14
+ }
15
+
16
+ export default {
17
+ summary: '本地取数工具(抓第三方公开页面,不写 TCM)',
18
+ commands: {
19
+ seo_video_detail: {
20
+ summary: '按视频 ID 取抖音视频详情:视频 / 达人 / 首屏评论',
21
+ auth: false,
22
+ params: {
23
+ id: string('视频 ID(awemeId,按字符串传,19 位数字)'),
24
+ url: string('视频链接(也接受分享文案;短链会自动跟随跳转)'),
25
+ html: string('解析本地已保存的 HTML(离线调试,忽略 --id / --url)'),
26
+ },
27
+ examples: [
28
+ 'tcm tool seo_video_detail --id 7701278853448142120',
29
+ 'tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120',
30
+ 'tcm tool seo_video_detail --url "7.43 复制打开抖音… https://v.douyin.com/xxxx/" --compact',
31
+ 'tcm tool seo_video_detail --html ./page.html --compact',
32
+ ],
33
+ async run({ values, global }) {
34
+ const id = values.id?.trim()
35
+ const url = values.url?.trim()
36
+ const htmlPath = values.html?.trim()
37
+
38
+ if (!htmlPath) {
39
+ if (!id && !url) throw new UsageError('需要 --id 或 --url(--html 用于解析本地文件)')
40
+ if (id && url) throw new UsageError('--id 和 --url 只能传一个')
41
+ }
42
+
43
+ return seoVideoDetail({ id, url, htmlPath, timeoutMs: timeoutMs(global) })
44
+ },
45
+ },
46
+ },
47
+ }
@@ -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 }
@@ -0,0 +1,229 @@
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 { ToolError } from './tool-error.js'
13
+
14
+ export const SEO_UA = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
15
+ const VIDEO_PAGE = 'https://www.douyin.com/video/'
16
+ const BASE_URL = 'https://www.douyin.com'
17
+
18
+ /** 从视频链接 / 分享文案里抠出 awemeId。 */
19
+ export function videoIdFrom(text) {
20
+ if (!text) return null
21
+ const value = String(text)
22
+ const match = value.match(/\/(?:video|share\/video|note)\/(\d{10,25})/) || value.match(/^\s*(\d{10,25})\s*$/)
23
+ return match ? match[1] : null
24
+ }
25
+
26
+ /** 抖音缩写数字 -> 整数:'5.4万' -> 54000、'4587' -> 4587、'1.2亿' -> 120000000。 */
27
+ export function abbrevToInt(text) {
28
+ if (text === null || text === undefined) return null
29
+ const match = String(text).replace(/,/g, '').trim().match(/^([\d.]+)\s*([万亿wWkK]?)$/)
30
+ if (!match) return null
31
+ const unit = { 万: 10000, w: 10000, W: 10000, 亿: 100000000, k: 1000, K: 1000, '': 1 }[match[2]]
32
+ return Math.round(Number(match[1]) * unit)
33
+ }
34
+
35
+ /** ISO 8601 时长 -> 秒:'PT0H1M8S' -> 68。 */
36
+ export function isoDurationSeconds(value) {
37
+ const match = String(value || '').match(/^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?$/)
38
+ if (!match) return null
39
+ const [h, m, s] = match.slice(1).map((part) => (part ? Number(part) : 0))
40
+ return Math.floor(h * 3600 + m * 60 + s)
41
+ }
42
+
43
+ /** 修掉抖音在带时区的时间后面多写的 Z:'2026-10-27T17:35:19+08:00Z' -> '…+08:00'。 */
44
+ export function normalizeIsoTime(value) {
45
+ if (!value) return null
46
+ const text = String(value)
47
+ return /[+-]\d{2}:\d{2}Z$/.test(text) ? text.slice(0, -1) : text
48
+ }
49
+
50
+ export function absoluteUrl(url, base = BASE_URL) {
51
+ if (!url) return null
52
+ const text = String(url)
53
+ if (/^https?:\/\//i.test(text)) return text
54
+ return text.startsWith('/') ? `${base}${text}` : text
55
+ }
56
+
57
+ export function secUidFrom(url) {
58
+ const match = String(url || '').match(/\/user\/(MS4wLjABAAAA[\w-]+)/)
59
+ return match ? match[1] : null
60
+ }
61
+
62
+ /** interactionStatistic 里的动作类型可能是字符串、{ '@type' } 对象或 { value },统一成字符串。 */
63
+ function interactionName(item) {
64
+ const type = item?.interactionType
65
+ if (!type) return ''
66
+ if (typeof type === 'string') return type
67
+ return String(type['@type'] ?? type.value ?? JSON.stringify(type))
68
+ }
69
+
70
+ /** interactionStatistic 里按 LikeAction / FollowAction 取数,兼容单个对象与数组。 */
71
+ function counterOf(statistic, action) {
72
+ const items = Array.isArray(statistic) ? statistic : statistic ? [statistic] : []
73
+ for (const item of items) {
74
+ if (interactionName(item).includes(action)) {
75
+ return item?.userInteractionCount ?? null
76
+ }
77
+ }
78
+ return null
79
+ }
80
+
81
+ /** 取出 ld+json 里的 VideoObject(页面里可能有多段 ld+json)。 */
82
+ export function parseVideoObject(html) {
83
+ const text = String(html || '')
84
+ const blocks = text.matchAll(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)
85
+ for (const block of blocks) {
86
+ let parsed
87
+ try {
88
+ parsed = JSON.parse(block[1])
89
+ } catch {
90
+ continue
91
+ }
92
+ if (parsed && typeof parsed === 'object' && parsed['@type'] === 'VideoObject') return parsed
93
+ }
94
+ const message = /VideoObject/.test(text)
95
+ ? '页面里的 ld+json VideoObject 不是合法 JSON(抖音可能改版)'
96
+ : '页面里没有 ld+json VideoObject:可能不是搜索引擎 UA 返回的页面、视频不存在/已删除,或抖音改版'
97
+ throw new ToolError(message, { type: 'ParseError' })
98
+ }
99
+
100
+ /**
101
+ * 首屏统计块里的四个数——ld+json 里没有。
102
+ * 结构固定:前三格是 `<span class="hIpNkUXt">`(赞 / 评 / 藏),
103
+ * 分享格是 `data-e2e="video-share-icon-container"` 里的 `<span class="sB3y0d3B">`。
104
+ */
105
+ export function domStats(html) {
106
+ const block = String(html || '').match(/<div class="pWR86eZK">([\s\S]*?)<div class="o9W_EAcI">/)
107
+ if (!block) return {}
108
+ const seg = block[1]
109
+ const shorts = [...seg.matchAll(/<span class="hIpNkUXt">([^<]+)<\/span>/g)].map((m) => m[1])
110
+ const share = [...seg.matchAll(/<span class="sB3y0d3B">([^<]+)<\/span>/g)].map((m) => m[1])
111
+ const stats = {}
112
+ const keys = ['like_count', 'comment_count', 'collect_count']
113
+ keys.forEach((key, index) => {
114
+ if (shorts[index] !== undefined) stats[key] = abbrevToInt(shorts[index])
115
+ })
116
+ if (share[0] !== undefined) stats.share_count = abbrevToInt(share[0])
117
+ return stats
118
+ }
119
+
120
+ /** 把 VideoObject + DOM 统计转成对外输出结构。 */
121
+ export function buildSnapshot({ videoObject, videoId, html }) {
122
+ const vo = videoObject || {}
123
+ const creator = vo.creator || {}
124
+ const stats = domStats(html)
125
+
126
+ // description 只从 name 解析:去掉站名尾巴「- 抖音」和 #话题
127
+ const name = String(vo.name || '')
128
+ const head = name.replace(/\s+-\s+抖音$/, '').trim()
129
+ const description = head.replace(/#[^\s#]+/g, ' ').replace(/\s{2,}/g, ' ').trim() || head || null
130
+
131
+ const comments = (Array.isArray(vo.comment) ? vo.comment : []).map((comment) => {
132
+ const user = comment?.creator || {}
133
+ return {
134
+ text: comment?.text ?? null,
135
+ user: {
136
+ name: user.name ?? null,
137
+ sec_uid: secUidFrom(user.url),
138
+ profile_url: absoluteUrl(user.url),
139
+ },
140
+ like_count: counterOf(comment?.interactionStatistic, 'LikeAction'),
141
+ }
142
+ })
143
+
144
+ return {
145
+ video: {
146
+ id: videoId,
147
+ description,
148
+ cover_urls: Array.isArray(vo.thumbnailUrl) ? vo.thumbnailUrl : [],
149
+ publish_time: normalizeIsoTime(vo.uploadDate),
150
+ duration_seconds: isoDurationSeconds(vo.duration),
151
+ // 点赞/收藏/分享只能从 DOM 展示文本解析(万/亿 缩写 -> 整数,近似值);
152
+ // 评论数优先用 ld+json 的精确值,缺失时回退 DOM
153
+ like_count: stats.like_count ?? null,
154
+ comment_count: vo.commentCount ?? stats.comment_count ?? null,
155
+ collect_count: stats.collect_count ?? null,
156
+ share_count: stats.share_count ?? null,
157
+ },
158
+ creator: {
159
+ name: creator.name ?? null,
160
+ sec_uid: secUidFrom(creator.url),
161
+ profile_url: absoluteUrl(creator.url),
162
+ like_count: counterOf(creator.interactionStatistic, 'LikeAction'),
163
+ follower_count: counterOf(creator.interactionStatistic, 'FollowAction'),
164
+ },
165
+ comments,
166
+ }
167
+ }
168
+
169
+ async function fetchHtml(url, timeoutMs) {
170
+ const headers = {
171
+ 'User-Agent': SEO_UA,
172
+ Accept: 'text/html,application/xhtml+xml',
173
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
174
+ }
175
+ let response
176
+ try {
177
+ response = await fetch(url, { headers, redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
178
+ } catch (error) {
179
+ const reason =
180
+ error?.name === 'TimeoutError' || error?.name === 'AbortError'
181
+ ? `请求超时(${timeoutMs}ms)`
182
+ : error?.message || '网络请求失败'
183
+ throw new ToolError(`抓取抖音页面失败(${url}):${reason}`, { type: 'FetchError' })
184
+ }
185
+ const html = await response.text().catch(() => '')
186
+ if (!response.ok) {
187
+ throw new ToolError(`抓取抖音页面失败(${url}):HTTP ${response.status}`, {
188
+ type: 'FetchError',
189
+ status: response.status,
190
+ })
191
+ }
192
+ return { html, finalUrl: response.url || url }
193
+ }
194
+
195
+ /**
196
+ * 主入口:按视频 ID / 链接 / 本地 HTML 返回 { video, creator, comments }。
197
+ * 失败抛 ToolError(FetchError / ParseError)或 UsageError(参数问题)。
198
+ */
199
+ export async function seoVideoDetail({ id, url, htmlPath, timeoutMs = 30000 }) {
200
+ if (htmlPath) {
201
+ try {
202
+ const html = fs.readFileSync(htmlPath, 'utf8')
203
+ const videoId =
204
+ html.match(/rel="canonical"[^>]*href="[^"]*\/video\/(\d+)"/)?.[1] ||
205
+ videoIdFrom(url) ||
206
+ (id ? String(id) : null)
207
+ return buildSnapshot({ videoObject: parseVideoObject(html), videoId, html })
208
+ } catch (error) {
209
+ if (error instanceof ToolError) throw error
210
+ throw new UsageError(`读取 --html 失败:${error.message}`)
211
+ }
212
+ }
213
+
214
+ const target = id
215
+ ? `${VIDEO_PAGE}${encodeURIComponent(String(id).trim())}`
216
+ : /^https?:\/\//i.test(String(url))
217
+ ? String(url).trim()
218
+ : `https://${String(url).trim()}`
219
+ const { html, finalUrl } = await fetchHtml(target, timeoutMs)
220
+ const videoId =
221
+ html.match(/rel="canonical"[^>]*href="[^"]*\/video\/(\d+)"/)?.[1] ||
222
+ videoIdFrom(finalUrl) ||
223
+ videoIdFrom(id) ||
224
+ videoIdFrom(url)
225
+ if (!videoId) {
226
+ throw new ToolError('无法确定视频 ID(页面没有 canonical,入参也解析不到)', { type: 'ParseError' })
227
+ }
228
+ return buildSnapshot({ videoObject: parseVideoObject(html), videoId, html })
229
+ }
@@ -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
+ }