@insta-dev01/intclaw 1.0.10 → 1.1.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/LICENSE +1 -1
- package/README.en.md +424 -0
- package/README.md +365 -164
- package/index.ts +28 -0
- package/openclaw.plugin.json +12 -41
- package/package.json +69 -40
- package/src/channel.ts +557 -0
- package/src/config/accounts.ts +230 -0
- package/src/config/schema.ts +144 -0
- package/src/core/connection.ts +733 -0
- package/src/core/message-handler.ts +1268 -0
- package/src/core/provider.ts +106 -0
- package/src/core/state.ts +54 -0
- package/src/directory.ts +95 -0
- package/src/gateway-methods.ts +237 -0
- package/src/onboarding.ts +387 -0
- package/src/policy.ts +19 -0
- package/src/probe.ts +213 -0
- package/src/reply-dispatcher.ts +674 -0
- package/src/runtime.ts +7 -0
- package/src/sdk/helpers.ts +317 -0
- package/src/sdk/types.ts +515 -0
- package/src/secret-input.ts +19 -0
- package/src/services/media/audio.ts +54 -0
- package/src/services/media/chunk-upload.ts +293 -0
- package/src/services/media/common.ts +154 -0
- package/src/services/media/file.ts +70 -0
- package/src/services/media/image.ts +67 -0
- package/src/services/media/index.ts +10 -0
- package/src/services/media/video.ts +162 -0
- package/src/services/media.ts +1134 -0
- package/src/services/messaging/index.ts +16 -0
- package/src/services/messaging/send.ts +137 -0
- package/src/services/messaging.ts +800 -0
- package/src/targets.ts +45 -0
- package/src/types/index.ts +52 -0
- package/src/utils/agent.ts +63 -0
- package/src/utils/async.ts +51 -0
- package/src/utils/constants.ts +9 -0
- package/src/utils/http-client.ts +84 -0
- package/src/utils/index.ts +8 -0
- package/src/utils/logger.ts +78 -0
- package/src/utils/session.ts +118 -0
- package/src/utils/token.ts +94 -0
- package/src/utils/utils-legacy.ts +506 -0
- package/.env.example +0 -11
- package/skills/intclaw_matrix/SKILL.md +0 -20
- package/src/channel/intclaw_channel.js +0 -155
- package/src/index.js +0 -23
|
@@ -0,0 +1,1134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IntClaw媒体处理
|
|
3
|
+
* 支持图片、视频、音频、文件的上传和下载
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as fs from 'fs';
|
|
7
|
+
import * as path from 'path';
|
|
8
|
+
import type { IntclawConfig } from '../types/index.ts';
|
|
9
|
+
import { INTCLAW_OAPI, getOapiAccessToken } from '../utils/index.ts';
|
|
10
|
+
import { intclawHttp, intclawOapiHttp } from '../utils/http-client.ts';
|
|
11
|
+
import { INTCLAW_CONFIG } from '../../config.ts';
|
|
12
|
+
|
|
13
|
+
// ============ 常量 ============
|
|
14
|
+
|
|
15
|
+
/** 文本文件扩展名 */
|
|
16
|
+
export const TEXT_FILE_EXTENSIONS = new Set([
|
|
17
|
+
'.txt',
|
|
18
|
+
'.md',
|
|
19
|
+
'.json',
|
|
20
|
+
'.yaml',
|
|
21
|
+
'.yml',
|
|
22
|
+
'.xml',
|
|
23
|
+
'.html',
|
|
24
|
+
'.css',
|
|
25
|
+
'.js',
|
|
26
|
+
'.ts',
|
|
27
|
+
'.py',
|
|
28
|
+
'.java',
|
|
29
|
+
'.c',
|
|
30
|
+
'.cpp',
|
|
31
|
+
'.h',
|
|
32
|
+
'.sh',
|
|
33
|
+
'.bat',
|
|
34
|
+
'.csv',
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
/** 图片文件扩展名 */
|
|
38
|
+
export const IMAGE_EXTENSIONS = /\.(png|jpg|jpeg|gif|bmp|webp|tiff|svg)$/i;
|
|
39
|
+
|
|
40
|
+
/** 本地图片路径正则表达式(跨平台) */
|
|
41
|
+
export const LOCAL_IMAGE_RE =
|
|
42
|
+
/!\[([^\]]*)\]\(((?:file:\/\/\/|MEDIA:|attachment:\/\/\/)[^)]+|\/(?:tmp|var|private|Users|home|root)[^)]+|[A-Za-z]:[\\/][^)]+)\)/g;
|
|
43
|
+
|
|
44
|
+
/** 纯文本图片路径正则表达式 */
|
|
45
|
+
export const BARE_IMAGE_PATH_RE =
|
|
46
|
+
/`?((?:\/(?:tmp|var|private|Users|home|root)\/[^\s`'",)]+|[A-Za-z]:[\\/][^\s`'",)]+)\.(?:png|jpg|jpeg|gif|bmp|webp))`?/gi;
|
|
47
|
+
|
|
48
|
+
/** 视频标记正则表达式 */
|
|
49
|
+
export const VIDEO_MARKER_PATTERN = /\[INTCLAW_VIDEO\](.*?)\[\/INTCLAW_VIDEO\]/gs;
|
|
50
|
+
|
|
51
|
+
/** 音频标记正则表达式 */
|
|
52
|
+
export const AUDIO_MARKER_PATTERN = /\[INTCLAW_AUDIO\](.*?)\[\/INTCLAW_AUDIO\]/gs;
|
|
53
|
+
|
|
54
|
+
/** 文件标记正则表达式 */
|
|
55
|
+
export const FILE_MARKER_PATTERN = /\[INTCLAW_FILE\](.*?)\[\/INTCLAW_FILE\]/gs;
|
|
56
|
+
|
|
57
|
+
// ============ 工具函数 ============
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 去掉 file:// / MEDIA: / attachment:// 前缀,得到实际的绝对路径
|
|
61
|
+
*/
|
|
62
|
+
export function toLocalPath(raw: string): string {
|
|
63
|
+
let filePath = raw;
|
|
64
|
+
if (filePath.startsWith('file://')) filePath = filePath.replace('file://', '');
|
|
65
|
+
else if (filePath.startsWith('MEDIA:')) filePath = filePath.replace('MEDIA:', '');
|
|
66
|
+
else if (filePath.startsWith('attachment://')) filePath = filePath.replace('attachment://', '');
|
|
67
|
+
|
|
68
|
+
// 解码 URL 编码的路径(如中文字符 %E5%9B%BE → 图)
|
|
69
|
+
try {
|
|
70
|
+
filePath = decodeURIComponent(filePath);
|
|
71
|
+
} catch {
|
|
72
|
+
// 解码失败则保持原样
|
|
73
|
+
}
|
|
74
|
+
return filePath;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 通用媒体文件上传函数
|
|
79
|
+
*/
|
|
80
|
+
/** 上传结果接口 */
|
|
81
|
+
export interface UploadResult {
|
|
82
|
+
mediaId: string; // 原始 media_id(带 @)
|
|
83
|
+
cleanMediaId: string; // 去掉 @ 的 media_id
|
|
84
|
+
downloadUrl: string; // 下载链接
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function uploadMediaToIntClaw(
|
|
88
|
+
filePath: string,
|
|
89
|
+
mediaType: 'image' | 'file' | 'video' | 'voice',
|
|
90
|
+
oapiToken: string,
|
|
91
|
+
maxSize: number = 20 * 1024 * 1024,
|
|
92
|
+
log?: any,
|
|
93
|
+
): Promise<UploadResult | null> {
|
|
94
|
+
try {
|
|
95
|
+
const FormData = (await import('form-data')).default;
|
|
96
|
+
|
|
97
|
+
const absPath = toLocalPath(filePath);
|
|
98
|
+
log?.info?.(`开始上传,文件路径:${absPath}`);
|
|
99
|
+
|
|
100
|
+
if (!fs.existsSync(absPath)) {
|
|
101
|
+
log?.warn?.(`文件不存在:${absPath}`);
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 检查文件大小
|
|
106
|
+
const stats = fs.statSync(absPath);
|
|
107
|
+
const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2);
|
|
108
|
+
const fileSize = stats.size;
|
|
109
|
+
|
|
110
|
+
log?.info?.(`文件大小:${fileSizeMB}MB`);
|
|
111
|
+
|
|
112
|
+
// 检查文件大小是否超过限制
|
|
113
|
+
if (stats.size > maxSize) {
|
|
114
|
+
const maxSizeMB = (maxSize / (1024 * 1024)).toFixed(0);
|
|
115
|
+
log?.warn?.(
|
|
116
|
+
`文件过大:${absPath}, 大小:${fileSizeMB}MB, 超过限制 ${maxSizeMB}MB`,
|
|
117
|
+
);
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ✅ 根据媒体类型设置正确的 contentType
|
|
122
|
+
const getContentType = () => {
|
|
123
|
+
const ext = path.extname(absPath).toLowerCase();
|
|
124
|
+
if (mediaType === 'image') {
|
|
125
|
+
return ext === '.png' ? 'image/png' : 'image/jpeg';
|
|
126
|
+
} else if (mediaType === 'video') {
|
|
127
|
+
return ext === '.mp4' ? 'video/mp4' : 'video/quicktime';
|
|
128
|
+
} else if (mediaType === 'voice') {
|
|
129
|
+
return ext === '.mp3' ? 'audio/mpeg' : 'audio/amr';
|
|
130
|
+
} else {
|
|
131
|
+
return 'application/octet-stream';
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const form = new FormData();
|
|
136
|
+
form.append('media', fs.createReadStream(absPath), {
|
|
137
|
+
filename: path.basename(absPath),
|
|
138
|
+
contentType: getContentType(),
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
log?.info?.(`上传文件: ${absPath} (${fileSizeMB}MB)`);
|
|
142
|
+
const resp = await intclawOapiHttp.post(
|
|
143
|
+
`${INTCLAW_OAPI}/media/upload?access_token=${oapiToken}&type=${mediaType === 'video' ? 'file' : mediaType}`,
|
|
144
|
+
form,
|
|
145
|
+
{ headers: form.getHeaders(), timeout: 60_000 },
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
const mediaId = resp.data?.media_id;
|
|
149
|
+
if (mediaId) {
|
|
150
|
+
// ✅ 去掉 media_id 前面的 @ 符号(如果有的话)
|
|
151
|
+
const cleanMediaId = mediaId.startsWith('@') ? mediaId.substring(1) : mediaId;
|
|
152
|
+
// ✅ 将 media_id 转换为IntClaw下载链接
|
|
153
|
+
const downloadUrl = `${INTCLAW_CONFIG.DOWNLOAD_BASE_URL}/media/${cleanMediaId}`;
|
|
154
|
+
log?.info?.(`上传成功: media_id=${mediaId}, cleanMediaId=${cleanMediaId}, downloadUrl=${downloadUrl}`);
|
|
155
|
+
return {
|
|
156
|
+
mediaId,
|
|
157
|
+
cleanMediaId,
|
|
158
|
+
downloadUrl,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
log?.warn?.(`上传返回无 media_id: ${JSON.stringify(resp.data)}`);
|
|
162
|
+
return null;
|
|
163
|
+
} catch (err: any) {
|
|
164
|
+
log?.error?.(`上传失败: ${err.message}`);
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 扫描内容中的本地图片路径,上传到IntClaw并替换为 media_id
|
|
171
|
+
*/
|
|
172
|
+
export async function processLocalImages(
|
|
173
|
+
content: string,
|
|
174
|
+
oapiToken: string | null,
|
|
175
|
+
log?: any,
|
|
176
|
+
): Promise<string> {
|
|
177
|
+
if (!oapiToken) {
|
|
178
|
+
log?.warn?.(`无 oapiToken,跳过图片后处理`);
|
|
179
|
+
return content;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let result = content;
|
|
183
|
+
|
|
184
|
+
// 第一步:匹配 markdown 图片语法 
|
|
185
|
+
const mdMatches = [...content.matchAll(LOCAL_IMAGE_RE)];
|
|
186
|
+
if (mdMatches.length > 0) {
|
|
187
|
+
log?.info?.(`检测到 ${mdMatches.length} 个 markdown 图片,开始上传...`);
|
|
188
|
+
for (const match of mdMatches) {
|
|
189
|
+
const [fullMatch, alt, rawPath] = match;
|
|
190
|
+
// 清理转义字符(AI 可能会对含空格的路径添加 \ )
|
|
191
|
+
const cleanPath = rawPath.replace(/\\ /g, ' ');
|
|
192
|
+
const uploadResult = await uploadMediaToIntClaw(cleanPath, 'image', oapiToken, 20 * 1024 * 1024, log);
|
|
193
|
+
if (uploadResult) {
|
|
194
|
+
result = result.replace(fullMatch, ``);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// 第二步:匹配纯文本中的本地图片路径
|
|
200
|
+
const bareMatches = [...result.matchAll(BARE_IMAGE_PATH_RE)];
|
|
201
|
+
const newBareMatches = bareMatches.filter((m) => {
|
|
202
|
+
// 检查这个路径是否已经在  中
|
|
203
|
+
if (m.index === undefined) return false;
|
|
204
|
+
const idx = m.index;
|
|
205
|
+
const before = result.slice(Math.max(0, idx - 10), idx);
|
|
206
|
+
return !before.includes('](');
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
if (newBareMatches.length > 0) {
|
|
210
|
+
log?.info?.(`检测到 ${newBareMatches.length} 个纯文本图片路径,开始上传...`);
|
|
211
|
+
// 从后往前替换,避免 index 偏移
|
|
212
|
+
for (const match of newBareMatches.reverse()) {
|
|
213
|
+
const [fullMatch, rawPath] = match;
|
|
214
|
+
log?.info?.(`纯文本图片: "${fullMatch}" -> path="${rawPath}"`);
|
|
215
|
+
const uploadResult = await uploadMediaToIntClaw(rawPath, 'image', oapiToken, 20 * 1024 * 1024, log);
|
|
216
|
+
if (uploadResult) {
|
|
217
|
+
const replacement = ``;
|
|
218
|
+
result = result.slice(0, match.index!) + result.slice(match.index!).replace(fullMatch, replacement);
|
|
219
|
+
log?.info?.(`替换纯文本路径为图片: ${replacement}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return result;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ============ 视频处理 ============
|
|
228
|
+
|
|
229
|
+
/** 视频信息接口 */
|
|
230
|
+
export interface VideoInfo {
|
|
231
|
+
path: string;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* 提取视频元数据(时长、分辨率)
|
|
236
|
+
*/
|
|
237
|
+
export async function extractVideoMetadata(
|
|
238
|
+
filePath: string,
|
|
239
|
+
log?: any,
|
|
240
|
+
): Promise<{ duration: number; width: number; height: number } | null> {
|
|
241
|
+
try {
|
|
242
|
+
const ffmpeg = require('fluent-ffmpeg');
|
|
243
|
+
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
|
|
244
|
+
const ffprobePath = require('@ffprobe-installer/ffprobe').path;
|
|
245
|
+
ffmpeg.setFfmpegPath(ffmpegPath);
|
|
246
|
+
ffmpeg.setFfprobePath(ffprobePath);
|
|
247
|
+
|
|
248
|
+
return new Promise((resolve) => {
|
|
249
|
+
ffmpeg.ffprobe(filePath, (err: any, metadata: any) => {
|
|
250
|
+
if (err) {
|
|
251
|
+
log?.warn?.(`ffprobe 执行失败: ${err.message}`);
|
|
252
|
+
resolve(null);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
// ✅ IntClaw API 需要毫秒,ffprobe 返回的是秒,需要转换
|
|
257
|
+
const duration = metadata.format?.duration ? Math.round(parseFloat(metadata.format.duration) * 1000) : 0;
|
|
258
|
+
const videoStream = metadata.streams?.find((s: any) => s.codec_type === 'video');
|
|
259
|
+
const width = videoStream?.width || 0;
|
|
260
|
+
const height = videoStream?.height || 0;
|
|
261
|
+
resolve({ duration, width, height });
|
|
262
|
+
} catch (err) {
|
|
263
|
+
log?.warn?.(`解析 ffprobe 输出失败`);
|
|
264
|
+
resolve(null);
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
} catch (err: any) {
|
|
269
|
+
log?.warn?.(`提取视频元数据失败: ${err.message}`);
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* 生成视频封面图(第1秒截图)
|
|
276
|
+
*/
|
|
277
|
+
export async function extractVideoThumbnail(
|
|
278
|
+
videoPath: string,
|
|
279
|
+
outputPath: string,
|
|
280
|
+
log?: any,
|
|
281
|
+
): Promise<string | null> {
|
|
282
|
+
try {
|
|
283
|
+
const ffmpeg = require('fluent-ffmpeg');
|
|
284
|
+
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
|
|
285
|
+
const path = await import('path');
|
|
286
|
+
ffmpeg.setFfmpegPath(ffmpegPath);
|
|
287
|
+
|
|
288
|
+
return new Promise((resolve) => {
|
|
289
|
+
ffmpeg(videoPath)
|
|
290
|
+
.screenshots({
|
|
291
|
+
count: 1,
|
|
292
|
+
folder: path.dirname(outputPath),
|
|
293
|
+
filename: path.basename(outputPath),
|
|
294
|
+
timemarks: ['1'],
|
|
295
|
+
size: '?x360',
|
|
296
|
+
})
|
|
297
|
+
.on('end', () => {
|
|
298
|
+
log?.info?.(`封面生成成功: ${outputPath}`);
|
|
299
|
+
resolve(outputPath);
|
|
300
|
+
})
|
|
301
|
+
.on('error', (err: any) => {
|
|
302
|
+
log?.error?.(`封面生成失败: ${err.message}`);
|
|
303
|
+
resolve(null);
|
|
304
|
+
});
|
|
305
|
+
});
|
|
306
|
+
} catch (err: any) {
|
|
307
|
+
log?.error?.(`ffmpeg 失败: ${err.message}`);
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 提取视频标记并发送视频消息
|
|
314
|
+
*/
|
|
315
|
+
export async function processVideoMarkers(
|
|
316
|
+
content: string,
|
|
317
|
+
sessionWebhook: string,
|
|
318
|
+
config: IntclawConfig,
|
|
319
|
+
oapiToken: string | null,
|
|
320
|
+
log?: any,
|
|
321
|
+
useProactiveApi: boolean = false,
|
|
322
|
+
target?: any,
|
|
323
|
+
): Promise<string> {
|
|
324
|
+
const logPrefix = useProactiveApi ? 'Video[Proactive]' : 'Video';
|
|
325
|
+
|
|
326
|
+
if (!oapiToken) {
|
|
327
|
+
log?.warn?.(`${logPrefix} 无 oapiToken,跳过视频处理`);
|
|
328
|
+
return content;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const matches = [...content.matchAll(VIDEO_MARKER_PATTERN)];
|
|
332
|
+
const videoInfos: VideoInfo[] = [];
|
|
333
|
+
const invalidVideos: string[] = [];
|
|
334
|
+
|
|
335
|
+
// 导入需要的模块
|
|
336
|
+
const os = await import('os');
|
|
337
|
+
|
|
338
|
+
for (const match of matches) {
|
|
339
|
+
try {
|
|
340
|
+
const videoInfo = JSON.parse(match[1]) as VideoInfo;
|
|
341
|
+
if (videoInfo.path && fs.existsSync(videoInfo.path)) {
|
|
342
|
+
videoInfos.push(videoInfo);
|
|
343
|
+
log?.info?.(`${logPrefix} 提取到视频: ${videoInfo.path}`);
|
|
344
|
+
} else {
|
|
345
|
+
invalidVideos.push(videoInfo.path || '未知路径');
|
|
346
|
+
log?.warn?.(`${logPrefix} 视频文件不存在: ${videoInfo.path}`);
|
|
347
|
+
}
|
|
348
|
+
} catch (err: any) {
|
|
349
|
+
log?.warn?.(`${logPrefix} 解析标记失败: ${err.message}`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (videoInfos.length === 0 && invalidVideos.length === 0) {
|
|
354
|
+
log?.info?.(`${logPrefix} 未检测到视频标记`);
|
|
355
|
+
return content.replace(VIDEO_MARKER_PATTERN, '').trim();
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// 先移除所有视频标记
|
|
359
|
+
let cleanedContent = content.replace(VIDEO_MARKER_PATTERN, '').trim();
|
|
360
|
+
|
|
361
|
+
const statusMessages: string[] = [];
|
|
362
|
+
|
|
363
|
+
for (const invalidPath of invalidVideos) {
|
|
364
|
+
statusMessages.push(`⚠️ 视频文件不存在: ${path.basename(invalidPath)}`);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (videoInfos.length > 0) {
|
|
368
|
+
log?.info?.(`${logPrefix} 检测到 ${videoInfos.length} 个视频,开始处理...`);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
for (const videoInfo of videoInfos) {
|
|
372
|
+
const fileName = path.basename(videoInfo.path);
|
|
373
|
+
let thumbnailPath = '';
|
|
374
|
+
try {
|
|
375
|
+
// 1. 提取视频元数据
|
|
376
|
+
const metadata = await extractVideoMetadata(videoInfo.path, log);
|
|
377
|
+
if (!metadata) {
|
|
378
|
+
log?.warn?.(`${logPrefix} 无法提取元数据: ${videoInfo.path}`);
|
|
379
|
+
statusMessages.push(`⚠️ 视频处理失败: ${fileName}(无法读取视频信息)`);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// 2. 生成封面图
|
|
384
|
+
thumbnailPath = path.join(os.tmpdir(), `thumbnail_${Date.now()}_${Math.random().toString(36).substr(2, 9)}.jpg`);
|
|
385
|
+
log?.info?.(`${logPrefix} 准备生成封面: ${thumbnailPath}`);
|
|
386
|
+
const thumbnail = await extractVideoThumbnail(videoInfo.path, thumbnailPath, log);
|
|
387
|
+
if (!thumbnail) {
|
|
388
|
+
log?.warn?.(`${logPrefix} 无法生成封面: ${videoInfo.path}`);
|
|
389
|
+
statusMessages.push(`⚠️ 视频处理失败: ${fileName}(无法生成封面)`);
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// 检查生成的封面文件
|
|
394
|
+
if (fs.existsSync(thumbnailPath)) {
|
|
395
|
+
const stats = fs.statSync(thumbnailPath);
|
|
396
|
+
log?.info?.(`${logPrefix} 封面文件生成完成: ${thumbnailPath}, 大小: ${(stats.size / 1024).toFixed(2)}KB`);
|
|
397
|
+
if (stats.size < 1024) { // 小于1KB可能有问题
|
|
398
|
+
log?.warn?.(`${logPrefix} 封面文件过小,可能存在质量问题`);
|
|
399
|
+
}
|
|
400
|
+
} else {
|
|
401
|
+
log?.error?.(`${logPrefix} 封面文件未生成: ${thumbnailPath}`);
|
|
402
|
+
statusMessages.push(`⚠️ 视频处理失败: ${fileName}(封面文件未生成)`);
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// 3. 上传视频
|
|
407
|
+
const videoUploadResult = await uploadMediaToIntClaw(videoInfo.path, 'video', oapiToken, 20 * 1024 * 1024, log);
|
|
408
|
+
if (!videoUploadResult) {
|
|
409
|
+
log?.warn?.(`${logPrefix} 视频上传失败: ${videoInfo.path}`);
|
|
410
|
+
statusMessages.push(`⚠️ 视频上传失败: ${fileName}(文件可能超过 20MB 限制)`);
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
const videoMediaId = videoUploadResult.mediaId; // 使用原始 media_id(带 @)
|
|
414
|
+
|
|
415
|
+
// 4. 上传封面
|
|
416
|
+
const picUploadResult = await uploadMediaToIntClaw(thumbnailPath, 'image', oapiToken, 20 * 1024 * 1024, log);
|
|
417
|
+
if (!picUploadResult) {
|
|
418
|
+
log?.warn?.(`${logPrefix} 封面上传失败: ${thumbnailPath}`);
|
|
419
|
+
statusMessages.push(`⚠️ 视频封面上传失败: ${fileName}`);
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
const picMediaId = picUploadResult.mediaId; // 使用原始 media_id(带 @)
|
|
423
|
+
|
|
424
|
+
// 5. 发送视频消息
|
|
425
|
+
if (useProactiveApi && target) {
|
|
426
|
+
await sendVideoProactive(config, target, videoMediaId, picMediaId, metadata, log);
|
|
427
|
+
} else {
|
|
428
|
+
await sendVideoMessage(config, sessionWebhook, fileName, videoUploadResult.downloadUrl, log, metadata);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
statusMessages.push(`✅ 视频已发送: ${fileName}`);
|
|
432
|
+
log?.info?.(`${logPrefix} 视频处理完成: ${fileName}`);
|
|
433
|
+
} catch (err: any) {
|
|
434
|
+
log?.error?.(`${logPrefix} 处理视频失败: ${err.message}`);
|
|
435
|
+
statusMessages.push(`⚠️ 视频处理异常: ${fileName}(${err.message})`);
|
|
436
|
+
} finally {
|
|
437
|
+
// 清理临时封面文件
|
|
438
|
+
if (thumbnailPath && fs.existsSync(thumbnailPath)) {
|
|
439
|
+
try {
|
|
440
|
+
fs.unlinkSync(thumbnailPath);
|
|
441
|
+
log?.info?.(`${logPrefix} 临时封面已清理: ${thumbnailPath}`);
|
|
442
|
+
} catch (cleanupErr: any) {
|
|
443
|
+
log?.warn?.(`${logPrefix} 清理临时文件失败: ${cleanupErr?.message || cleanupErr}`);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
if (statusMessages.length > 0) {
|
|
450
|
+
const statusText = statusMessages.join('\n');
|
|
451
|
+
cleanedContent = cleanedContent
|
|
452
|
+
? `${cleanedContent}\n\n${statusText}`
|
|
453
|
+
: statusText;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
return cleanedContent;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// ============ 音频处理 ============
|
|
460
|
+
|
|
461
|
+
/** 音频信息接口 */
|
|
462
|
+
export interface AudioInfo {
|
|
463
|
+
path: string;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* 提取音频时长
|
|
468
|
+
*/
|
|
469
|
+
async function extractAudioDuration(filePath: string, log?: any): Promise<number | null> {
|
|
470
|
+
try {
|
|
471
|
+
// 使用 ffprobe 提取音频时长
|
|
472
|
+
const { exec } = await import('child_process');
|
|
473
|
+
return new Promise((resolve) => {
|
|
474
|
+
exec(
|
|
475
|
+
`ffprobe -v error -show_entries format=duration -of json "${filePath}"`,
|
|
476
|
+
(error: any, stdout: string) => {
|
|
477
|
+
if (error) {
|
|
478
|
+
log?.warn?.(`ffprobe 执行失败: ${error.message}`);
|
|
479
|
+
resolve(null);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
try {
|
|
483
|
+
const data = JSON.parse(stdout);
|
|
484
|
+
const duration = data.format?.duration ? Math.round(parseFloat(data.format.duration) * 1000) : 0;
|
|
485
|
+
resolve(duration);
|
|
486
|
+
} catch (err) {
|
|
487
|
+
log?.warn?.(`解析 ffprobe 输出失败`);
|
|
488
|
+
resolve(null);
|
|
489
|
+
}
|
|
490
|
+
},
|
|
491
|
+
);
|
|
492
|
+
});
|
|
493
|
+
} catch (err: any) {
|
|
494
|
+
log?.warn?.(`提取音频时长失败: ${err.message}`);
|
|
495
|
+
return null;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* 提取音频标记并发送音频消息
|
|
501
|
+
*/
|
|
502
|
+
export async function processAudioMarkers(
|
|
503
|
+
content: string,
|
|
504
|
+
sessionWebhook: string,
|
|
505
|
+
config: IntclawConfig,
|
|
506
|
+
oapiToken: string | null,
|
|
507
|
+
log?: any,
|
|
508
|
+
useProactiveApi: boolean = false,
|
|
509
|
+
target?: any,
|
|
510
|
+
): Promise<string> {
|
|
511
|
+
const logPrefix = useProactiveApi ? 'Audio[Proactive]' : 'Audio';
|
|
512
|
+
|
|
513
|
+
if (!oapiToken) {
|
|
514
|
+
log?.warn?.(`${logPrefix} 无 oapiToken,跳过音频处理`);
|
|
515
|
+
return content;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const matches = [...content.matchAll(AUDIO_MARKER_PATTERN)];
|
|
519
|
+
const audioInfos: AudioInfo[] = [];
|
|
520
|
+
const invalidAudios: string[] = [];
|
|
521
|
+
|
|
522
|
+
for (const match of matches) {
|
|
523
|
+
try {
|
|
524
|
+
const audioInfo = JSON.parse(match[1]) as AudioInfo;
|
|
525
|
+
if (audioInfo.path && fs.existsSync(audioInfo.path)) {
|
|
526
|
+
audioInfos.push(audioInfo);
|
|
527
|
+
log?.info?.(`${logPrefix} 提取到音频: ${audioInfo.path}`);
|
|
528
|
+
} else {
|
|
529
|
+
invalidAudios.push(audioInfo.path || '未知路径');
|
|
530
|
+
log?.warn?.(`${logPrefix} 音频文件不存在: ${audioInfo.path}`);
|
|
531
|
+
}
|
|
532
|
+
} catch (err: any) {
|
|
533
|
+
log?.warn?.(`${logPrefix} 解析标记失败: ${err.message}`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (audioInfos.length === 0 && invalidAudios.length === 0) {
|
|
538
|
+
log?.info?.(`${logPrefix} 未检测到音频标记`);
|
|
539
|
+
return content.replace(AUDIO_MARKER_PATTERN, '').trim();
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// 先移除所有音频标记
|
|
543
|
+
let cleanedContent = content.replace(AUDIO_MARKER_PATTERN, '').trim();
|
|
544
|
+
|
|
545
|
+
const statusMessages: string[] = [];
|
|
546
|
+
|
|
547
|
+
for (const invalidPath of invalidAudios) {
|
|
548
|
+
statusMessages.push(`⚠️ 音频文件不存在: ${path.basename(invalidPath)}`);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
if (audioInfos.length > 0) {
|
|
552
|
+
log?.info?.(`${logPrefix} 检测到 ${audioInfos.length} 个音频,开始处理...`);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
for (const audioInfo of audioInfos) {
|
|
556
|
+
const fileName = path.basename(audioInfo.path);
|
|
557
|
+
try {
|
|
558
|
+
const ext = path.extname(audioInfo.path).slice(1).toLowerCase();
|
|
559
|
+
|
|
560
|
+
// 上传音频到IntClaw
|
|
561
|
+
const uploadResult = await uploadMediaToIntClaw(audioInfo.path, 'voice', oapiToken, 20 * 1024 * 1024, log);
|
|
562
|
+
if (!uploadResult) {
|
|
563
|
+
statusMessages.push(`⚠️ 音频上传失败: ${fileName}(文件可能超过 20MB 限制)`);
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// 提取音频实际时长
|
|
568
|
+
const audioDurationMs = await extractAudioDuration(audioInfo.path, log);
|
|
569
|
+
|
|
570
|
+
// 发送音频消息
|
|
571
|
+
if (useProactiveApi && target) {
|
|
572
|
+
await sendAudioProactive(config, target, fileName, uploadResult.downloadUrl, log, audioDurationMs ?? undefined);
|
|
573
|
+
} else {
|
|
574
|
+
await sendAudioMessage(config, sessionWebhook, fileName, uploadResult.downloadUrl, log, audioDurationMs ?? undefined);
|
|
575
|
+
}
|
|
576
|
+
statusMessages.push(`✅ 音频已发送: ${fileName}`);
|
|
577
|
+
log?.info?.(`${logPrefix} 音频处理完成: ${fileName}`);
|
|
578
|
+
} catch (err: any) {
|
|
579
|
+
log?.error?.(`${logPrefix} 处理音频失败: ${err.message}`);
|
|
580
|
+
statusMessages.push(`⚠️ 音频处理异常: ${fileName}(${err.message})`);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
if (statusMessages.length > 0) {
|
|
585
|
+
const statusText = statusMessages.join('\n');
|
|
586
|
+
cleanedContent = cleanedContent
|
|
587
|
+
? `${cleanedContent}\n\n${statusText}`
|
|
588
|
+
: statusText;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
return cleanedContent;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// ============ 文件处理 ============
|
|
595
|
+
|
|
596
|
+
/** 文件信息接口 */
|
|
597
|
+
export interface FileInfo {
|
|
598
|
+
path: string;
|
|
599
|
+
fileName: string;
|
|
600
|
+
fileType: string;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* 提取文件标记并发送文件消息
|
|
605
|
+
*/
|
|
606
|
+
export async function processFileMarkers(
|
|
607
|
+
content: string,
|
|
608
|
+
sessionWebhook: string,
|
|
609
|
+
config: IntclawConfig,
|
|
610
|
+
oapiToken: string | null,
|
|
611
|
+
log?: any,
|
|
612
|
+
useProactiveApi: boolean = false,
|
|
613
|
+
target?: any,
|
|
614
|
+
): Promise<string> {
|
|
615
|
+
const logPrefix = useProactiveApi ? 'File[Proactive]' : 'File';
|
|
616
|
+
|
|
617
|
+
if (!oapiToken) {
|
|
618
|
+
log?.warn?.(`${logPrefix} 无 oapiToken,跳过文件处理`);
|
|
619
|
+
return content;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const matches = [...content.matchAll(FILE_MARKER_PATTERN)];
|
|
623
|
+
const fileInfos: FileInfo[] = [];
|
|
624
|
+
const invalidFiles: string[] = [];
|
|
625
|
+
|
|
626
|
+
for (const match of matches) {
|
|
627
|
+
try {
|
|
628
|
+
const fileInfo = JSON.parse(match[1]) as FileInfo;
|
|
629
|
+
if (fileInfo.path && fs.existsSync(fileInfo.path)) {
|
|
630
|
+
fileInfos.push(fileInfo);
|
|
631
|
+
log?.info?.(`${logPrefix} 提取到文件: ${fileInfo.path}`);
|
|
632
|
+
} else {
|
|
633
|
+
invalidFiles.push(fileInfo.path || '未知路径');
|
|
634
|
+
log?.warn?.(`${logPrefix} 文件不存在: ${fileInfo.path}`);
|
|
635
|
+
}
|
|
636
|
+
} catch (err: any) {
|
|
637
|
+
log?.warn?.(`${logPrefix} 解析标记失败: ${err.message}`);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
if (fileInfos.length === 0 && invalidFiles.length === 0) {
|
|
642
|
+
log?.info?.(`${logPrefix} 未检测到文件标记`);
|
|
643
|
+
return content.replace(FILE_MARKER_PATTERN, '').trim();
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// 先移除所有文件标记
|
|
647
|
+
let cleanedContent = content.replace(FILE_MARKER_PATTERN, '').trim();
|
|
648
|
+
|
|
649
|
+
const statusMessages: string[] = [];
|
|
650
|
+
|
|
651
|
+
for (const invalidPath of invalidFiles) {
|
|
652
|
+
statusMessages.push(`⚠️ 文件不存在: ${path.basename(invalidPath)}`);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
if (fileInfos.length > 0) {
|
|
656
|
+
log?.info?.(`${logPrefix} 检测到 ${fileInfos.length} 个文件,开始处理...`);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
for (const fileInfo of fileInfos) {
|
|
660
|
+
const fileName = fileInfo.fileName || path.basename(fileInfo.path);
|
|
661
|
+
try {
|
|
662
|
+
// 上传文件到IntClaw
|
|
663
|
+
const uploadResult = await uploadMediaToIntClaw(fileInfo.path, 'file', oapiToken, 20 * 1024 * 1024, log);
|
|
664
|
+
if (!uploadResult) {
|
|
665
|
+
statusMessages.push(`⚠️ 文件上传失败: ${fileName}(文件可能超过 20MB 限制)`);
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// 发送文件消息
|
|
670
|
+
if (useProactiveApi && target) {
|
|
671
|
+
await sendFileProactive(config, target, fileInfo, uploadResult.downloadUrl, log);
|
|
672
|
+
} else {
|
|
673
|
+
await sendFileMessage(config, sessionWebhook, fileInfo, uploadResult.downloadUrl, log);
|
|
674
|
+
}
|
|
675
|
+
statusMessages.push(`✅ 文件已发送: ${fileName}`);
|
|
676
|
+
log?.info?.(`${logPrefix} 文件处理完成: ${fileName}`);
|
|
677
|
+
} catch (err: any) {
|
|
678
|
+
log?.error?.(`${logPrefix} 处理文件失败: ${err.message}`);
|
|
679
|
+
statusMessages.push(`⚠️ 文件处理异常: ${fileName}(${err.message})`);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
if (statusMessages.length > 0) {
|
|
684
|
+
const statusText = statusMessages.join('\n');
|
|
685
|
+
cleanedContent = cleanedContent
|
|
686
|
+
? `${cleanedContent}\n\n${statusText}`
|
|
687
|
+
: statusText;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
return cleanedContent;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// ============ 视频消息发送 ============
|
|
694
|
+
|
|
695
|
+
/** 视频元数据接口 */
|
|
696
|
+
interface VideoMetadata {
|
|
697
|
+
duration: number;
|
|
698
|
+
width: number;
|
|
699
|
+
height: number;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* 发送视频消息(sessionWebhook 模式)
|
|
704
|
+
*/
|
|
705
|
+
async function sendVideoMessage(
|
|
706
|
+
config: IntclawConfig,
|
|
707
|
+
sessionWebhook: string,
|
|
708
|
+
fileName: string,
|
|
709
|
+
mediaId: string,
|
|
710
|
+
log?: any,
|
|
711
|
+
metadata?: { duration: number; width: number; height: number },
|
|
712
|
+
): Promise<void> {
|
|
713
|
+
try {
|
|
714
|
+
const token = await (await import('../utils/index.ts')).getAccessToken(config);
|
|
715
|
+
|
|
716
|
+
// IntClaw视频消息格式(sessionWebhook 模式)
|
|
717
|
+
const videoMessage = {
|
|
718
|
+
msgtype: 'video',
|
|
719
|
+
video: {
|
|
720
|
+
mediaId: mediaId,
|
|
721
|
+
duration: metadata?.duration.toString() || '60000',
|
|
722
|
+
type: 'mp4',
|
|
723
|
+
},
|
|
724
|
+
};
|
|
725
|
+
|
|
726
|
+
log?.info?.(`发送视频消息: ${fileName}`);
|
|
727
|
+
const resp = await intclawHttp.post(sessionWebhook, videoMessage, {
|
|
728
|
+
headers: {
|
|
729
|
+
'x-acs-intclaw-access-token': token,
|
|
730
|
+
'Content-Type': 'application/json',
|
|
731
|
+
},
|
|
732
|
+
timeout: 10_000,
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
if (resp.data?.success !== false) {
|
|
736
|
+
log?.info?.(`视频消息发送成功: ${fileName}`);
|
|
737
|
+
} else {
|
|
738
|
+
log?.error?.(`视频消息发送失败: ${JSON.stringify(resp.data)}`);
|
|
739
|
+
}
|
|
740
|
+
} catch (err: any) {
|
|
741
|
+
log?.error?.(`发送视频消息异常: ${fileName}, 错误: ${err.message}`);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* 发送视频消息(主动 API 模式)
|
|
747
|
+
*/
|
|
748
|
+
export async function sendVideoProactive(
|
|
749
|
+
config: IntclawConfig,
|
|
750
|
+
target: any,
|
|
751
|
+
videoMediaId: string,
|
|
752
|
+
picMediaId: string,
|
|
753
|
+
metadata?: { duration: number; width: number; height: number },
|
|
754
|
+
log?: any,
|
|
755
|
+
): Promise<void> {
|
|
756
|
+
try {
|
|
757
|
+
const token = await (await import('../utils/index.ts')).getAccessToken(config);
|
|
758
|
+
const { INTCLAW_API } = await import('../utils/index.ts');
|
|
759
|
+
|
|
760
|
+
// IntClaw普通消息 API 的视频消息格式
|
|
761
|
+
const msgParam = {
|
|
762
|
+
duration: metadata?.duration.toString() || '60000',
|
|
763
|
+
videoMediaId: videoMediaId,
|
|
764
|
+
videoType: 'mp4',
|
|
765
|
+
picMediaId: picMediaId || '', // 封面图 mediaId
|
|
766
|
+
};
|
|
767
|
+
|
|
768
|
+
const body: any = {
|
|
769
|
+
robotCode: config.clientId,
|
|
770
|
+
msgKey: 'sampleVideo',
|
|
771
|
+
msgParam: JSON.stringify(msgParam),
|
|
772
|
+
};
|
|
773
|
+
|
|
774
|
+
let endpoint: string;
|
|
775
|
+
if (target.type === 'group') {
|
|
776
|
+
body.openConversationId = target.openConversationId;
|
|
777
|
+
endpoint = `${INTCLAW_API}/v1.0/robot/groupMessages/send`;
|
|
778
|
+
} else {
|
|
779
|
+
body.userIds = [target.userId];
|
|
780
|
+
endpoint = `${INTCLAW_API}/v1.0/robot/oToMessages/batchSend`;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
log?.info?.(`Video[Proactive] 发送视频消息`);
|
|
784
|
+
log?.info?.(`Video[Proactive] 请求体: ${JSON.stringify(body, null, 2)}`);
|
|
785
|
+
log?.info?.(`Video[Proactive] endpoint: ${endpoint}`);
|
|
786
|
+
const resp = await intclawHttp.post(endpoint, body, {
|
|
787
|
+
headers: { 'x-acs-intclaw-access-token': token, 'Content-Type': 'application/json' },
|
|
788
|
+
timeout: 10_000,
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
log?.info?.(`Video[Proactive] IntClaw API 响应: ${JSON.stringify(resp.data, null, 2)}`);
|
|
792
|
+
|
|
793
|
+
if (resp.data?.processQueryKey) {
|
|
794
|
+
log?.info?.(`Video[Proactive] 视频消息发送成功`);
|
|
795
|
+
} else {
|
|
796
|
+
log?.error?.(`Video[Proactive] 视频消息发送失败: ${JSON.stringify(resp.data)}`);
|
|
797
|
+
throw new Error(`视频消息发送失败: ${JSON.stringify(resp.data)}`);
|
|
798
|
+
}
|
|
799
|
+
} catch (err: any) {
|
|
800
|
+
log?.error?.(`Video[Proactive] 发送视频消息失败, 错误: ${err.message}`);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// ============ 音频消息发送 ============
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* 发送音频消息(sessionWebhook 模式)
|
|
808
|
+
*/
|
|
809
|
+
async function sendAudioMessage(
|
|
810
|
+
config: IntclawConfig,
|
|
811
|
+
sessionWebhook: string,
|
|
812
|
+
fileName: string,
|
|
813
|
+
mediaId: string,
|
|
814
|
+
log?: any,
|
|
815
|
+
durationMs?: number,
|
|
816
|
+
): Promise<void> {
|
|
817
|
+
try {
|
|
818
|
+
const token = await (await import('../utils/index.ts')).getAccessToken(config);
|
|
819
|
+
|
|
820
|
+
// IntClaw语音消息格式
|
|
821
|
+
const actualDuration = (durationMs && durationMs > 0) ? durationMs.toString() : '60000';
|
|
822
|
+
const audioMessage = {
|
|
823
|
+
msgtype: 'voice',
|
|
824
|
+
voice: {
|
|
825
|
+
mediaId: mediaId,
|
|
826
|
+
duration: actualDuration,
|
|
827
|
+
},
|
|
828
|
+
};
|
|
829
|
+
|
|
830
|
+
log?.info?.(`发送语音消息: ${fileName}`);
|
|
831
|
+
const resp = await intclawHttp.post(sessionWebhook, audioMessage, {
|
|
832
|
+
headers: {
|
|
833
|
+
'x-acs-intclaw-access-token': token,
|
|
834
|
+
'Content-Type': 'application/json',
|
|
835
|
+
},
|
|
836
|
+
timeout: 10_000,
|
|
837
|
+
});
|
|
838
|
+
|
|
839
|
+
if (resp.data?.success !== false) {
|
|
840
|
+
log?.info?.(`语音消息发送成功: ${fileName}`);
|
|
841
|
+
} else {
|
|
842
|
+
log?.error?.(`语音消息发送失败: ${JSON.stringify(resp.data)}`);
|
|
843
|
+
}
|
|
844
|
+
} catch (err: any) {
|
|
845
|
+
log?.error?.(`发送语音消息异常: ${fileName}, 错误: ${err.message}`);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* 发送音频消息(主动 API 模式)
|
|
851
|
+
*/
|
|
852
|
+
export async function sendAudioProactive(
|
|
853
|
+
config: IntclawConfig,
|
|
854
|
+
target: any,
|
|
855
|
+
fileName: string,
|
|
856
|
+
mediaId: string,
|
|
857
|
+
log?: any,
|
|
858
|
+
durationMs?: number,
|
|
859
|
+
): Promise<void> {
|
|
860
|
+
try {
|
|
861
|
+
const token = await (await import('../utils/index.ts')).getAccessToken(config);
|
|
862
|
+
const { INTCLAW_API } = await import('../utils/index.ts');
|
|
863
|
+
|
|
864
|
+
// IntClaw普通消息 API 的音频消息格式
|
|
865
|
+
const actualDuration = (durationMs && durationMs > 0) ? durationMs.toString() : '60000';
|
|
866
|
+
const msgParam = {
|
|
867
|
+
mediaId: mediaId,
|
|
868
|
+
duration: actualDuration,
|
|
869
|
+
};
|
|
870
|
+
|
|
871
|
+
const body: any = {
|
|
872
|
+
robotCode: config.clientId,
|
|
873
|
+
msgKey: 'sampleAudio',
|
|
874
|
+
msgParam: JSON.stringify(msgParam),
|
|
875
|
+
};
|
|
876
|
+
|
|
877
|
+
let endpoint: string;
|
|
878
|
+
if (target.type === 'group') {
|
|
879
|
+
body.openConversationId = target.openConversationId;
|
|
880
|
+
endpoint = `${INTCLAW_API}/v1.0/robot/groupMessages/send`;
|
|
881
|
+
} else {
|
|
882
|
+
body.userIds = [target.userId];
|
|
883
|
+
endpoint = `${INTCLAW_API}/v1.0/robot/oToMessages/batchSend`;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
log?.info?.(`Audio[Proactive] 发送音频消息: ${fileName}`);
|
|
887
|
+
const resp = await intclawHttp.post(endpoint, body, {
|
|
888
|
+
headers: { 'x-acs-intclaw-access-token': token, 'Content-Type': 'application/json' },
|
|
889
|
+
timeout: 10_000,
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
if (resp.data?.processQueryKey) {
|
|
893
|
+
log?.info?.(`Audio[Proactive] 音频消息发送成功: ${fileName}`);
|
|
894
|
+
} else {
|
|
895
|
+
log?.warn?.(`Audio[Proactive] 音频消息发送响应异常: ${JSON.stringify(resp.data)}`);
|
|
896
|
+
}
|
|
897
|
+
} catch (err: any) {
|
|
898
|
+
log?.error?.(`Audio[Proactive] 发送音频消息失败: ${fileName}, 错误: ${err.message}`);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
// ============ 文件消息发送 ============
|
|
903
|
+
|
|
904
|
+
/**
|
|
905
|
+
* 发送文件消息(sessionWebhook 模式)
|
|
906
|
+
*/
|
|
907
|
+
async function sendFileMessage(
|
|
908
|
+
config: IntclawConfig,
|
|
909
|
+
sessionWebhook: string,
|
|
910
|
+
fileInfo: FileInfo,
|
|
911
|
+
mediaId: string,
|
|
912
|
+
log?: any,
|
|
913
|
+
): Promise<void> {
|
|
914
|
+
try {
|
|
915
|
+
const token = await (await import('../utils/index.ts')).getAccessToken(config);
|
|
916
|
+
|
|
917
|
+
const fileMessage = {
|
|
918
|
+
msgtype: 'file',
|
|
919
|
+
file: {
|
|
920
|
+
mediaId: mediaId,
|
|
921
|
+
fileName: fileInfo.fileName,
|
|
922
|
+
fileType: fileInfo.fileType,
|
|
923
|
+
},
|
|
924
|
+
};
|
|
925
|
+
|
|
926
|
+
log?.info?.(`发送文件消息: ${fileInfo.fileName}`);
|
|
927
|
+
const resp = await intclawHttp.post(sessionWebhook, fileMessage, {
|
|
928
|
+
headers: {
|
|
929
|
+
'x-acs-intclaw-access-token': token,
|
|
930
|
+
'Content-Type': 'application/json',
|
|
931
|
+
},
|
|
932
|
+
timeout: 10_000,
|
|
933
|
+
});
|
|
934
|
+
|
|
935
|
+
if (resp.data?.success !== false) {
|
|
936
|
+
log?.info?.(`文件消息发送成功: ${fileInfo.fileName}`);
|
|
937
|
+
} else {
|
|
938
|
+
log?.error?.(`文件消息发送失败: ${JSON.stringify(resp.data)}`);
|
|
939
|
+
}
|
|
940
|
+
} catch (err: any) {
|
|
941
|
+
log?.error?.(`发送文件消息异常: ${fileInfo.fileName}, 错误: ${err.message}`);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* 发送文件消息(主动 API 模式)
|
|
947
|
+
*/
|
|
948
|
+
export async function sendFileProactive(
|
|
949
|
+
config: IntclawConfig,
|
|
950
|
+
target: any,
|
|
951
|
+
fileInfo: FileInfo,
|
|
952
|
+
mediaId: string,
|
|
953
|
+
log?: any,
|
|
954
|
+
): Promise<void> {
|
|
955
|
+
try {
|
|
956
|
+
const token = await (await import('../utils/index.ts')).getAccessToken(config);
|
|
957
|
+
const { INTCLAW_API } = await import('../utils/index.ts');
|
|
958
|
+
|
|
959
|
+
// IntClaw普通消息 API 的文件消息格式
|
|
960
|
+
const msgParam = {
|
|
961
|
+
mediaId: mediaId,
|
|
962
|
+
fileName: fileInfo.fileName,
|
|
963
|
+
fileType: fileInfo.fileType,
|
|
964
|
+
};
|
|
965
|
+
|
|
966
|
+
const body: any = {
|
|
967
|
+
robotCode: config.clientId,
|
|
968
|
+
msgKey: 'sampleFile',
|
|
969
|
+
msgParam: JSON.stringify(msgParam),
|
|
970
|
+
};
|
|
971
|
+
|
|
972
|
+
let endpoint: string;
|
|
973
|
+
if (target.type === 'group') {
|
|
974
|
+
body.openConversationId = target.openConversationId;
|
|
975
|
+
endpoint = `${INTCLAW_API}/v1.0/robot/groupMessages/send`;
|
|
976
|
+
} else {
|
|
977
|
+
body.userIds = [target.userId];
|
|
978
|
+
endpoint = `${INTCLAW_API}/v1.0/robot/oToMessages/batchSend`;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
log?.info?.(`File[Proactive] 发送文件消息: ${fileInfo.fileName}`);
|
|
982
|
+
const resp = await intclawHttp.post(endpoint, body, {
|
|
983
|
+
headers: { 'x-acs-intclaw-access-token': token, 'Content-Type': 'application/json' },
|
|
984
|
+
timeout: 10_000,
|
|
985
|
+
});
|
|
986
|
+
|
|
987
|
+
if (resp.data?.processQueryKey) {
|
|
988
|
+
log?.info?.(`File[Proactive] 发送成功: processQueryKey=${resp.data.processQueryKey}`);
|
|
989
|
+
} else {
|
|
990
|
+
log?.warn?.(`File[Proactive] 发送失败: ${JSON.stringify(resp.data)}`);
|
|
991
|
+
}
|
|
992
|
+
} catch (err: any) {
|
|
993
|
+
log?.error?.(`File[Proactive] 发送文件消息失败: ${fileInfo.fileName}, 错误: ${err.message}`);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
// ============================================================================
|
|
998
|
+
// 裸露文件路径处理(绕过 OpenClaw SDK bug)
|
|
999
|
+
// ============================================================================
|
|
1000
|
+
|
|
1001
|
+
/**
|
|
1002
|
+
* 检测并处理响应中的裸露本地文件路径
|
|
1003
|
+
*
|
|
1004
|
+
* OpenClaw SDK 会自动检测响应中的裸露文件路径并调用 ctx.outbound.sendMedia,
|
|
1005
|
+
* 但是 SDK 传递了错误的 to 参数(accountId 而不是真实的用户 ID)。
|
|
1006
|
+
*
|
|
1007
|
+
* 为了绕过这个 bug,我们在 SDK 检测到之前就处理这些文件路径:
|
|
1008
|
+
* 1. 检测裸露的本地文件路径(如 /Users/xxx/video.mp4)
|
|
1009
|
+
* 2. 上传文件到IntClaw
|
|
1010
|
+
* 3. 发送媒体消息
|
|
1011
|
+
* 4. 从响应中移除文件路径
|
|
1012
|
+
*
|
|
1013
|
+
* 这样 SDK 就检测不到文件路径,也就不会调用 sendMedia 了。
|
|
1014
|
+
*/
|
|
1015
|
+
interface AICardTarget {
|
|
1016
|
+
type: 'user' | 'group';
|
|
1017
|
+
userId?: string;
|
|
1018
|
+
openConversationId?: string;
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
export async function processRawMediaPaths(
|
|
1022
|
+
content: string,
|
|
1023
|
+
config: IntclawConfig,
|
|
1024
|
+
oapiToken: string,
|
|
1025
|
+
log?: any,
|
|
1026
|
+
target?: AICardTarget,
|
|
1027
|
+
): Promise<string> {
|
|
1028
|
+
const logPrefix = 'RawMedia';
|
|
1029
|
+
|
|
1030
|
+
// 匹配裸露的本地文件路径(绝对路径)
|
|
1031
|
+
// 支持的格式:
|
|
1032
|
+
// - Unix: /path/to/file.ext
|
|
1033
|
+
// - Windows: C:\path\to\file.ext 或 C:/path/to/file.ext
|
|
1034
|
+
const rawPathPattern = /(?:^|\s)((?:[A-Za-z]:)?[\/\\](?:[^\/\\:\*\?"<>\|\s]+[\/\\])*[^\/\\:\*\?"<>\|\s]+\.(?:mp4|avi|mov|wmv|flv|mkv|webm|mp3|wav|flac|aac|ogg|m4a|wma|pdf|doc|docx|xls|xlsx|ppt|pptx|txt|zip|rar|7z|tar|gz))(?:\s|$)/gi;
|
|
1035
|
+
|
|
1036
|
+
const matches = Array.from(content.matchAll(rawPathPattern));
|
|
1037
|
+
|
|
1038
|
+
if (matches.length === 0) {
|
|
1039
|
+
return content;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
log?.info?.(`${logPrefix} 检测到 ${matches.length} 个裸露的本地文件路径`);
|
|
1043
|
+
|
|
1044
|
+
let processedContent = content;
|
|
1045
|
+
const statusMessages: string[] = [];
|
|
1046
|
+
|
|
1047
|
+
for (const match of matches) {
|
|
1048
|
+
const fullMatch = match[0];
|
|
1049
|
+
const filePath = match[1].trim();
|
|
1050
|
+
|
|
1051
|
+
try {
|
|
1052
|
+
log?.info?.(`${logPrefix} 开始处理文件: ${filePath}`);
|
|
1053
|
+
|
|
1054
|
+
// 判断文件类型
|
|
1055
|
+
const ext = filePath.toLowerCase().split('.').pop() || '';
|
|
1056
|
+
let mediaType: 'video' | 'voice' | 'file';
|
|
1057
|
+
|
|
1058
|
+
if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].includes(ext)) {
|
|
1059
|
+
mediaType = 'video';
|
|
1060
|
+
} else if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a', 'wma'].includes(ext)) {
|
|
1061
|
+
mediaType = 'voice'; // IntClaw API 中音频类型是 'voice'
|
|
1062
|
+
} else {
|
|
1063
|
+
mediaType = 'file';
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// 上传文件到IntClaw
|
|
1067
|
+
const uploadResult = await uploadMediaToIntClaw(
|
|
1068
|
+
filePath,
|
|
1069
|
+
mediaType,
|
|
1070
|
+
oapiToken,
|
|
1071
|
+
20 * 1024 * 1024,
|
|
1072
|
+
log
|
|
1073
|
+
);
|
|
1074
|
+
|
|
1075
|
+
if (!uploadResult) {
|
|
1076
|
+
log?.error?.(`${logPrefix} 文件上传失败: ${filePath}`);
|
|
1077
|
+
statusMessages.push(`⚠️ 文件上传失败: ${filePath}`);
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// 发送媒体消息
|
|
1082
|
+
const fileName = filePath.split(/[\/\\]/).pop() || 'unknown';
|
|
1083
|
+
|
|
1084
|
+
if (mediaType === 'video') {
|
|
1085
|
+
// 提取视频元数据
|
|
1086
|
+
const metadata = await extractVideoMetadata(filePath, log);
|
|
1087
|
+
|
|
1088
|
+
if (target) {
|
|
1089
|
+
// 视频消息需要原始 mediaId(带 @)
|
|
1090
|
+
await sendVideoProactive(config, target, uploadResult.mediaId, fileName, log, metadata);
|
|
1091
|
+
}
|
|
1092
|
+
statusMessages.push(`✅ 视频已发送: ${fileName}`);
|
|
1093
|
+
} else if (mediaType === 'voice') {
|
|
1094
|
+
// 提取音频时长
|
|
1095
|
+
const durationMs = await extractAudioDuration(filePath, log);
|
|
1096
|
+
|
|
1097
|
+
if (target) {
|
|
1098
|
+
// 音频消息使用下载链接
|
|
1099
|
+
await sendAudioProactive(config, target, fileName, uploadResult.downloadUrl, log, durationMs ?? undefined);
|
|
1100
|
+
}
|
|
1101
|
+
statusMessages.push(`✅ 音频已发送: ${fileName}`);
|
|
1102
|
+
} else {
|
|
1103
|
+
// 文件消息
|
|
1104
|
+
const fileInfo: FileInfo = {
|
|
1105
|
+
path: filePath,
|
|
1106
|
+
fileName: fileName,
|
|
1107
|
+
fileType: ext,
|
|
1108
|
+
};
|
|
1109
|
+
|
|
1110
|
+
if (target) {
|
|
1111
|
+
// 文件消息使用下载链接
|
|
1112
|
+
await sendFileProactive(config, target, fileInfo, uploadResult.downloadUrl, log);
|
|
1113
|
+
}
|
|
1114
|
+
statusMessages.push(`✅ 文件已发送: ${fileName}`);
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// 从响应中移除文件路径
|
|
1118
|
+
processedContent = processedContent.replace(fullMatch, fullMatch.replace(filePath, ''));
|
|
1119
|
+
|
|
1120
|
+
log?.info?.(`${logPrefix} 文件处理完成: ${fileName}`);
|
|
1121
|
+
} catch (err: any) {
|
|
1122
|
+
log?.error?.(`${logPrefix} 处理文件失败: ${filePath}, 错误: ${err.message}`);
|
|
1123
|
+
statusMessages.push(`⚠️ 处理失败: ${filePath}`);
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// 添加状态消息到响应中
|
|
1128
|
+
if (statusMessages.length > 0) {
|
|
1129
|
+
const statusText = '\n\n' + statusMessages.join('\n');
|
|
1130
|
+
processedContent = processedContent.trim() + statusText;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
return processedContent;
|
|
1134
|
+
}
|