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