@vitex/tcm-cli 0.3.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
@@ -199,6 +199,7 @@ tcm logout
199
199
 
200
200
  - `tcm tool seo_video_detail --id <awemeId>` — 按视频 ID 取抖音 SEO 版视频页:视频(文案 / 封面 / 发布时间 / 时长 / 点赞 / 评论 / 收藏 / 分享)、达人(昵称 / secUid / 获赞 / 粉丝)、首屏 10 条评论
201
201
  - 也支持 `--url <链接或分享文案>`(短链会自动跟随跳转)与 `--html <本地文件>`(离线解析已保存的页面)
202
+ - `--proxy <user:pass@host:port>` 可让抓取走公司 HTTP 代理(如 `--proxy proxy:xxxx@10.175.4.62:8081`)
202
203
  - 点赞 / 收藏 / 分享来自页面展示文本(`5.4万` → `54000`),是**近似值**;评论数取 ld+json 的精确值
203
204
  - 只有首屏 10 条一级评论,没有视频直链 / 音乐 / 弹幕
204
205
 
@@ -209,6 +210,9 @@ tcm tool seo_video_detail --id 7701278853448142120 --compact
209
210
  # 按链接(分享文案也行)
210
211
  tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120
211
212
 
213
+ # 走 HTTP 代理(user:pass@host:port)
214
+ tcm tool seo_video_detail --id 7701278853448142120 --proxy "proxy:617a6e1e066d3d31@10.175.4.62:8081"
215
+
212
216
  # 离线重放(排查页面改版用)
213
217
  tcm tool seo_video_detail --html ./page.html --compact
214
218
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitex/tcm-cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "TCM 控制台命令行工具(面向 agent,JSON 输入输出)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,5 +1,6 @@
1
1
  import { UsageError } from '../args.js'
2
2
  import { DEFAULT_TIMEOUT_MS } from '../config.js'
3
+ import { parseProxy } from '../proxy.js'
3
4
  import { seoVideoDetail } from '../seo-video.js'
4
5
  import { string } from './common.js'
5
6
 
@@ -23,24 +24,27 @@ export default {
23
24
  id: string('视频 ID(awemeId,按字符串传,19 位数字)'),
24
25
  url: string('视频链接(也接受分享文案;短链会自动跟随跳转)'),
25
26
  html: string('解析本地已保存的 HTML(离线调试,忽略 --id / --url)'),
27
+ proxy: string('走 HTTP 代理,格式 proxy:password@host:port'),
26
28
  },
27
29
  examples: [
28
30
  'tcm tool seo_video_detail --id 7701278853448142120',
29
31
  'tcm tool seo_video_detail --url https://www.douyin.com/video/7701278853448142120',
30
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"',
31
34
  'tcm tool seo_video_detail --html ./page.html --compact',
32
35
  ],
33
36
  async run({ values, global }) {
34
37
  const id = values.id?.trim()
35
38
  const url = values.url?.trim()
36
39
  const htmlPath = values.html?.trim()
40
+ const proxy = parseProxy(values.proxy)
37
41
 
38
42
  if (!htmlPath) {
39
43
  if (!id && !url) throw new UsageError('需要 --id 或 --url(--html 用于解析本地文件)')
40
44
  if (id && url) throw new UsageError('--id 和 --url 只能传一个')
41
45
  }
42
46
 
43
- return seoVideoDetail({ id, url, htmlPath, timeoutMs: timeoutMs(global) })
47
+ return seoVideoDetail({ id, url, htmlPath, timeoutMs: timeoutMs(global), proxy })
44
48
  },
45
49
  },
46
50
  },
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
+ }
package/src/seo-video.js CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import fs from 'node:fs'
11
11
  import { UsageError } from './args.js'
12
+ import { fetchThroughProxy } from './proxy.js'
12
13
  import { ToolError } from './tool-error.js'
13
14
 
14
15
  export const SEO_UA = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
@@ -166,12 +167,22 @@ export function buildSnapshot({ videoObject, videoId, html }) {
166
167
  }
167
168
  }
168
169
 
169
- async function fetchHtml(url, timeoutMs) {
170
+ async function fetchHtml(url, timeoutMs, proxy) {
170
171
  const headers = {
171
172
  'User-Agent': SEO_UA,
172
173
  Accept: 'text/html,application/xhtml+xml',
173
174
  'Accept-Language': 'zh-CN,zh;q=0.9',
174
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
+ }
175
186
  let response
176
187
  try {
177
188
  response = await fetch(url, { headers, redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
@@ -194,9 +205,10 @@ async function fetchHtml(url, timeoutMs) {
194
205
 
195
206
  /**
196
207
  * 主入口:按视频 ID / 链接 / 本地 HTML 返回 { video, creator, comments }。
208
+ * `proxy` 为 parseProxy() 的结果;传了就走代理(CONNECT 隧道),不传直连。
197
209
  * 失败抛 ToolError(FetchError / ParseError)或 UsageError(参数问题)。
198
210
  */
199
- export async function seoVideoDetail({ id, url, htmlPath, timeoutMs = 30000 }) {
211
+ export async function seoVideoDetail({ id, url, htmlPath, timeoutMs = 30000, proxy = null }) {
200
212
  if (htmlPath) {
201
213
  try {
202
214
  const html = fs.readFileSync(htmlPath, 'utf8')
@@ -216,7 +228,7 @@ export async function seoVideoDetail({ id, url, htmlPath, timeoutMs = 30000 }) {
216
228
  : /^https?:\/\//i.test(String(url))
217
229
  ? String(url).trim()
218
230
  : `https://${String(url).trim()}`
219
- const { html, finalUrl } = await fetchHtml(target, timeoutMs)
231
+ const { html, finalUrl } = await fetchHtml(target, timeoutMs, proxy)
220
232
  const videoId =
221
233
  html.match(/rel="canonical"[^>]*href="[^"]*\/video\/(\d+)"/)?.[1] ||
222
234
  videoIdFrom(finalUrl) ||