@lynker-desktop/electron-sdk 0.0.9-alpha.4 → 0.0.9-alpha.41
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 +160 -1
- package/common/index.d.ts +96 -0
- package/common/index.d.ts.map +1 -1
- package/common/index.js.map +1 -1
- package/esm/common/index.d.ts +96 -0
- package/esm/common/index.d.ts.map +1 -1
- package/esm/common/index.js.map +1 -1
- package/esm/main/index.d.ts +49 -2
- package/esm/main/index.d.ts.map +1 -1
- package/esm/main/index.js +529 -6
- package/esm/main/index.js.map +1 -1
- package/esm/preload/index.js +17 -1
- package/esm/preload/index.js.map +1 -1
- package/esm/renderer/index.d.ts +8 -0
- package/esm/renderer/index.d.ts.map +1 -1
- package/esm/renderer/index.js +25 -0
- package/esm/renderer/index.js.map +1 -1
- package/main/index.d.ts +49 -2
- package/main/index.d.ts.map +1 -1
- package/main/index.js +533 -5
- package/main/index.js.map +1 -1
- package/package.json +5 -5
- package/preload/index.js +17 -1
- package/preload/index.js.map +1 -1
- package/renderer/index.d.ts +8 -0
- package/renderer/index.d.ts.map +1 -1
- package/renderer/index.js +25 -0
- package/renderer/index.js.map +1 -1
package/main/index.js
CHANGED
|
@@ -5,6 +5,7 @@ const path = require('node:path');
|
|
|
5
5
|
const node_util = require('node:util');
|
|
6
6
|
const http = require('node:http');
|
|
7
7
|
const https = require('node:https');
|
|
8
|
+
const node_child_process = require('node:child_process');
|
|
8
9
|
const electron = require('electron');
|
|
9
10
|
const md5 = require('md5');
|
|
10
11
|
const uuid = require('uuid');
|
|
@@ -56,7 +57,7 @@ function findWebContentsByPid(pid) {
|
|
|
56
57
|
* @returns
|
|
57
58
|
*/
|
|
58
59
|
const initialize = (options) => {
|
|
59
|
-
let { protocol, preload, loadingViewUrl, serveOptions = [], errorViewUrl,
|
|
60
|
+
let { protocol, preload, loadingViewUrl, serveOptions = [], errorViewUrl, preloadWebContentsConfig, webviewDomainWhiteList, resourceCacheOptions } = options;
|
|
60
61
|
if (exports.isInitialized) {
|
|
61
62
|
// @ts-ignore
|
|
62
63
|
return global['__GLBOAL_ELECTRON_SDK__'];
|
|
@@ -64,7 +65,10 @@ const initialize = (options) => {
|
|
|
64
65
|
exports.isInitialized = true;
|
|
65
66
|
ipc__namespace.initialize();
|
|
66
67
|
logs__namespace.initialize();
|
|
67
|
-
|
|
68
|
+
if (options.ffmpegPath) {
|
|
69
|
+
VideoDownloader.getInstance().setFFmpegPath(options.ffmpegPath);
|
|
70
|
+
}
|
|
71
|
+
const wm = windowManager__namespace.initialize(preload, loadingViewUrl, errorViewUrl, preloadWebContentsConfig, webviewDomainWhiteList || []);
|
|
68
72
|
if (protocol) {
|
|
69
73
|
registerProtocol(protocol);
|
|
70
74
|
}
|
|
@@ -92,6 +96,10 @@ const initialize = (options) => {
|
|
|
92
96
|
SDK.ipc = ipc__namespace.mainIPC;
|
|
93
97
|
SDK.windowManager = wm;
|
|
94
98
|
SDK.getPreload = () => preload;
|
|
99
|
+
SDK.downloadVideo = downloadVideo;
|
|
100
|
+
SDK.clearVideoCache = clearVideoCache;
|
|
101
|
+
SDK.getVideoCacheStats = getVideoCacheStats;
|
|
102
|
+
SDK.removeVideoCache = removeVideoCache;
|
|
95
103
|
ipc__namespace.mainIPC.handleRenderer(index$1.IPC_GET_APP_METRICS, async () => {
|
|
96
104
|
const metrics = electron.app.getAppMetrics().map(i => {
|
|
97
105
|
const webContents = findWebContentsByPid(i.pid || 0);
|
|
@@ -104,6 +112,30 @@ const initialize = (options) => {
|
|
|
104
112
|
});
|
|
105
113
|
return JSON.stringify(metrics);
|
|
106
114
|
});
|
|
115
|
+
ipc__namespace.mainIPC.handleRenderer(`__sdk_transcode_video__`, async (options) => {
|
|
116
|
+
const md5Options = md5(JSON.stringify(options.url));
|
|
117
|
+
downloadVideo(options, {
|
|
118
|
+
onDownloadProgress: (progress) => {
|
|
119
|
+
ipc__namespace.mainIPC.invokeAllRenderer(`__sdk_transcode_video_callback_${md5Options}__`, {
|
|
120
|
+
type: 'downloadProgress',
|
|
121
|
+
data: progress
|
|
122
|
+
});
|
|
123
|
+
},
|
|
124
|
+
onTranscodeProgress: (progress) => {
|
|
125
|
+
ipc__namespace.mainIPC.invokeAllRenderer(`__sdk_transcode_video_callback_${md5Options}__`, {
|
|
126
|
+
type: 'transcodeProgress',
|
|
127
|
+
data: progress
|
|
128
|
+
});
|
|
129
|
+
},
|
|
130
|
+
onComplete: (result) => {
|
|
131
|
+
ipc__namespace.mainIPC.invokeAllRenderer(`__sdk_transcode_video_callback_${md5Options}__`, {
|
|
132
|
+
type: 'complete',
|
|
133
|
+
data: result
|
|
134
|
+
});
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
return true;
|
|
138
|
+
});
|
|
107
139
|
// @ts-ignore
|
|
108
140
|
global['__GLBOAL_ELECTRON_SDK__'] = SDK;
|
|
109
141
|
return SDK;
|
|
@@ -461,6 +493,30 @@ ResourceCache.scheme = 'cachefile';
|
|
|
461
493
|
* @returns
|
|
462
494
|
*/
|
|
463
495
|
const enable = (webContents) => remote__namespace.enable(webContents);
|
|
496
|
+
/**
|
|
497
|
+
* 生成跨平台的文件URL
|
|
498
|
+
* @param filePath 文件路径
|
|
499
|
+
* @returns file:// URL
|
|
500
|
+
*/
|
|
501
|
+
function getFileUrl(filePath) {
|
|
502
|
+
if (!filePath) {
|
|
503
|
+
return '';
|
|
504
|
+
}
|
|
505
|
+
if (filePath.startsWith('file://')) {
|
|
506
|
+
return filePath;
|
|
507
|
+
}
|
|
508
|
+
// 在Windows上,需要添加驱动器字母前的斜杠
|
|
509
|
+
if (process.platform === 'win32') {
|
|
510
|
+
// 如果路径是绝对路径(如 C:\path\to\file),转换为 /C:/path/to/file
|
|
511
|
+
if (filePath.match(/^[A-Za-z]:/)) {
|
|
512
|
+
return `file:///${filePath}`;
|
|
513
|
+
}
|
|
514
|
+
// 如果已经是 /C:/path/to/file 格式,直接添加 file://
|
|
515
|
+
return `file://${filePath}`;
|
|
516
|
+
}
|
|
517
|
+
// macOS 和 Linux 使用 file:/// 前缀
|
|
518
|
+
return `file://${filePath}`;
|
|
519
|
+
}
|
|
464
520
|
/**
|
|
465
521
|
* 获取随机UUID
|
|
466
522
|
* @param key
|
|
@@ -484,6 +540,469 @@ function getRandomUUID(key = `${Date.now()}`) {
|
|
|
484
540
|
const uuid$1 = uuid.v5(`${JSON.stringify(key)}_${Date.now()}_${randomValue}`, uuid.v5.URL);
|
|
485
541
|
return uuid$1;
|
|
486
542
|
}
|
|
543
|
+
/**
|
|
544
|
+
* 视频下载和转码类
|
|
545
|
+
*/
|
|
546
|
+
class VideoDownloader {
|
|
547
|
+
constructor() {
|
|
548
|
+
this.ffmpegPath = '';
|
|
549
|
+
this.defaultCacheTTL = 24 * 60 * 60 * 1000; // 24小时缓存有效期
|
|
550
|
+
}
|
|
551
|
+
static getInstance() {
|
|
552
|
+
if (!VideoDownloader.instance) {
|
|
553
|
+
VideoDownloader.instance = new VideoDownloader();
|
|
554
|
+
}
|
|
555
|
+
return VideoDownloader.instance;
|
|
556
|
+
}
|
|
557
|
+
setFFmpegPath(ffmpegPath) {
|
|
558
|
+
this.ffmpegPath = ffmpegPath;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* 下载视频文件
|
|
562
|
+
*/
|
|
563
|
+
async downloadVideoFile(url, outputPath, onProgress) {
|
|
564
|
+
return new Promise((resolve, reject) => {
|
|
565
|
+
const lib = url.startsWith('https') ? https : http;
|
|
566
|
+
const file = fs.createWriteStream(outputPath);
|
|
567
|
+
let downloadedBytes = 0;
|
|
568
|
+
let totalBytes = 0;
|
|
569
|
+
let startTime = Date.now();
|
|
570
|
+
let lastTime = startTime;
|
|
571
|
+
let lastBytes = 0;
|
|
572
|
+
const cleanup = () => {
|
|
573
|
+
if (file) {
|
|
574
|
+
file.close();
|
|
575
|
+
fs.unlinkSync(outputPath);
|
|
576
|
+
}
|
|
577
|
+
};
|
|
578
|
+
const request = lib.get(url, (res) => {
|
|
579
|
+
if (res.statusCode !== 200) {
|
|
580
|
+
cleanup();
|
|
581
|
+
reject(new Error(`下载失败,状态码: ${res.statusCode}`));
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
totalBytes = parseInt(res.headers['content-length'] || '0', 10);
|
|
585
|
+
res.on('data', (chunk) => {
|
|
586
|
+
downloadedBytes += chunk.length;
|
|
587
|
+
const now = Date.now();
|
|
588
|
+
if (onProgress && (now - lastTime > 100 || downloadedBytes === totalBytes)) {
|
|
589
|
+
const speed = ((downloadedBytes - lastBytes) * 1000) / (now - lastTime);
|
|
590
|
+
onProgress({
|
|
591
|
+
downloaded: downloadedBytes,
|
|
592
|
+
total: totalBytes,
|
|
593
|
+
percentage: totalBytes > 0 ? (downloadedBytes / totalBytes) * 100 : 0,
|
|
594
|
+
speed: speed || 0
|
|
595
|
+
});
|
|
596
|
+
lastTime = now;
|
|
597
|
+
lastBytes = downloadedBytes;
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
res.pipe(file);
|
|
601
|
+
file.on('finish', () => {
|
|
602
|
+
file.close();
|
|
603
|
+
resolve();
|
|
604
|
+
});
|
|
605
|
+
file.on('error', (err) => {
|
|
606
|
+
cleanup();
|
|
607
|
+
reject(err);
|
|
608
|
+
});
|
|
609
|
+
});
|
|
610
|
+
request.on('error', (err) => {
|
|
611
|
+
cleanup();
|
|
612
|
+
reject(err);
|
|
613
|
+
});
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* 使用FFmpeg转码视频
|
|
618
|
+
*/
|
|
619
|
+
async transcodeVideo(inputPath, outputPath, options, onProgress) {
|
|
620
|
+
return new Promise((resolve, reject) => {
|
|
621
|
+
const ffmpegPath = options.ffmpegPath || this.ffmpegPath;
|
|
622
|
+
if (!ffmpegPath) {
|
|
623
|
+
reject(new Error('FFmpeg路径未设置'));
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
const format = options.format || 'mp4';
|
|
627
|
+
const quality = options.quality || 18;
|
|
628
|
+
const videoCodec = options.videoCodec || 'h264';
|
|
629
|
+
const audioCodec = options.audioCodec || 'aac';
|
|
630
|
+
// 根据格式选择合适的编码器
|
|
631
|
+
const getCodecForFormat = (format, videoCodec, audioCodec) => {
|
|
632
|
+
switch (format) {
|
|
633
|
+
case 'webm':
|
|
634
|
+
return {
|
|
635
|
+
videoCodec: videoCodec === 'h264' ? 'libvpx-vp9' : videoCodec,
|
|
636
|
+
audioCodec: audioCodec === 'aac' ? 'libopus' : audioCodec
|
|
637
|
+
};
|
|
638
|
+
case 'avi':
|
|
639
|
+
return {
|
|
640
|
+
videoCodec: videoCodec === 'h265' ? 'h264' : videoCodec, // AVI不支持H265
|
|
641
|
+
audioCodec: audioCodec === 'opus' ? 'mp3' : audioCodec
|
|
642
|
+
};
|
|
643
|
+
case 'mov':
|
|
644
|
+
return {
|
|
645
|
+
videoCodec: videoCodec === 'vp9' ? 'h264' : videoCodec, // MOV对VP9支持有限
|
|
646
|
+
audioCodec: audioCodec === 'opus' ? 'aac' : audioCodec
|
|
647
|
+
};
|
|
648
|
+
default: // mp4, mkv
|
|
649
|
+
return { videoCodec, audioCodec };
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
const { videoCodec: finalVideoCodec, audioCodec: finalAudioCodec } = getCodecForFormat(format, videoCodec, audioCodec);
|
|
653
|
+
// 构建FFmpeg命令
|
|
654
|
+
const args = [
|
|
655
|
+
'-i', inputPath,
|
|
656
|
+
'-c:v', finalVideoCodec,
|
|
657
|
+
'-c:a', finalAudioCodec,
|
|
658
|
+
'-crf', quality.toString(),
|
|
659
|
+
'-preset', 'medium',
|
|
660
|
+
'-f', format, // 指定输出格式
|
|
661
|
+
'-y', // 覆盖输出文件
|
|
662
|
+
outputPath
|
|
663
|
+
];
|
|
664
|
+
const ffmpegProcess = node_child_process.spawn(ffmpegPath, args);
|
|
665
|
+
let duration = 0;
|
|
666
|
+
let stderr = '';
|
|
667
|
+
ffmpegProcess.stderr.on('data', (data) => {
|
|
668
|
+
stderr += data.toString();
|
|
669
|
+
// 解析FFmpeg输出获取进度
|
|
670
|
+
if (onProgress) {
|
|
671
|
+
const durationMatch = stderr.match(/Duration: (\d{2}):(\d{2}):(\d{2})\.(\d{2})/);
|
|
672
|
+
if (durationMatch && duration === 0) {
|
|
673
|
+
const hours = parseInt(durationMatch[1] || '0', 10);
|
|
674
|
+
const minutes = parseInt(durationMatch[2] || '0', 10);
|
|
675
|
+
const seconds = parseInt(durationMatch[3] || '0', 10);
|
|
676
|
+
const centiseconds = parseInt(durationMatch[4] || '0', 10);
|
|
677
|
+
duration = hours * 3600 + minutes * 60 + seconds + centiseconds / 100;
|
|
678
|
+
}
|
|
679
|
+
const timeMatch = stderr.match(/time=(\d{2}):(\d{2}):(\d{2})\.(\d{2})/);
|
|
680
|
+
if (timeMatch && duration > 0) {
|
|
681
|
+
const hours = parseInt(timeMatch[1] || '0', 10);
|
|
682
|
+
const minutes = parseInt(timeMatch[2] || '0', 10);
|
|
683
|
+
const seconds = parseInt(timeMatch[3] || '0', 10);
|
|
684
|
+
const centiseconds = parseInt(timeMatch[4] || '0', 10);
|
|
685
|
+
const currentTime = hours * 3600 + minutes * 60 + seconds + centiseconds / 100;
|
|
686
|
+
const percentage = (currentTime / duration) * 100;
|
|
687
|
+
const speedMatch = stderr.match(/speed=([\d.]+)x/);
|
|
688
|
+
const speed = speedMatch ? parseFloat(speedMatch[1] || '1') : 1;
|
|
689
|
+
onProgress({
|
|
690
|
+
percentage: Math.min(percentage, 100),
|
|
691
|
+
time: currentTime,
|
|
692
|
+
speed: speed
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
ffmpegProcess.on('close', (code) => {
|
|
698
|
+
if (code === 0) {
|
|
699
|
+
resolve();
|
|
700
|
+
}
|
|
701
|
+
else {
|
|
702
|
+
reject(new Error(`FFmpeg转码失败,退出码: ${code}\n${stderr}`));
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
ffmpegProcess.on('error', (err) => {
|
|
706
|
+
reject(new Error(`FFmpeg执行失败: ${err.message}`));
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* 检查FFmpeg是否可用
|
|
712
|
+
*/
|
|
713
|
+
async checkFFmpegAvailable(ffmpegPath) {
|
|
714
|
+
return new Promise((resolve) => {
|
|
715
|
+
const command = ffmpegPath || this.ffmpegPath;
|
|
716
|
+
if (!command) {
|
|
717
|
+
resolve(false);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
const childProcess = node_child_process.spawn(command, ['-version']);
|
|
721
|
+
childProcess.on('error', (error) => {
|
|
722
|
+
console.log("checkFFmpegAvailable", error);
|
|
723
|
+
resolve(false);
|
|
724
|
+
});
|
|
725
|
+
childProcess.on('close', (code) => {
|
|
726
|
+
console.log("checkFFmpegAvailable", code);
|
|
727
|
+
resolve(code === 0);
|
|
728
|
+
});
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* 获取视频信息
|
|
733
|
+
*/
|
|
734
|
+
async getVideoInfo(inputPath, ffmpegPath) {
|
|
735
|
+
return new Promise((resolve, reject) => {
|
|
736
|
+
const ffmpegPath_cmd = ffmpegPath || this.ffmpegPath;
|
|
737
|
+
const args = ['-i', inputPath, '-f', 'null', '-'];
|
|
738
|
+
if (!ffmpegPath_cmd) {
|
|
739
|
+
resolve({ duration: 0, fileSize: 0 });
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
const ffmpegProcess = node_child_process.spawn(ffmpegPath_cmd, args);
|
|
743
|
+
let stderr = '';
|
|
744
|
+
let duration = 0;
|
|
745
|
+
ffmpegProcess.stderr.on('data', (data) => {
|
|
746
|
+
stderr += data.toString();
|
|
747
|
+
const durationMatch = stderr.match(/Duration: (\d{2}):(\d{2}):(\d{2})\.(\d{2})/);
|
|
748
|
+
if (durationMatch) {
|
|
749
|
+
const hours = parseInt(durationMatch[1] || '0', 10);
|
|
750
|
+
const minutes = parseInt(durationMatch[2] || '0', 10);
|
|
751
|
+
const seconds = parseInt(durationMatch[3] || '0', 10);
|
|
752
|
+
const centiseconds = parseInt(durationMatch[4] || '0', 10);
|
|
753
|
+
duration = hours * 3600 + minutes * 60 + seconds + centiseconds / 100;
|
|
754
|
+
}
|
|
755
|
+
});
|
|
756
|
+
ffmpegProcess.on('close', () => {
|
|
757
|
+
const stats = fs.statSync(inputPath);
|
|
758
|
+
resolve({
|
|
759
|
+
duration,
|
|
760
|
+
fileSize: stats.size
|
|
761
|
+
});
|
|
762
|
+
});
|
|
763
|
+
ffmpegProcess.on('error', (err) => {
|
|
764
|
+
reject(err);
|
|
765
|
+
});
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* 生成缓存文件名(基于URL的MD5)
|
|
770
|
+
*/
|
|
771
|
+
generateCacheFileName(options) {
|
|
772
|
+
const format = options.format || 'mp4';
|
|
773
|
+
const urlMd5 = md5(options.url);
|
|
774
|
+
return `${urlMd5}.${format}`;
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* 检查缓存文件是否存在
|
|
778
|
+
*/
|
|
779
|
+
isCacheFileExists(cacheFilePath) {
|
|
780
|
+
console.log('检查缓存文件是否存在: ', cacheFilePath);
|
|
781
|
+
return fs.existsSync(cacheFilePath);
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* 清理过期缓存文件
|
|
785
|
+
*/
|
|
786
|
+
cleanExpiredCacheFiles(outputDir, cacheTTL = this.defaultCacheTTL) {
|
|
787
|
+
try {
|
|
788
|
+
const files = fs.readdirSync(outputDir);
|
|
789
|
+
const now = Date.now();
|
|
790
|
+
files.forEach(file => {
|
|
791
|
+
const filePath = path.join(outputDir, file);
|
|
792
|
+
try {
|
|
793
|
+
const stats = fs.statSync(filePath);
|
|
794
|
+
// 如果文件超过缓存时间,删除它
|
|
795
|
+
if (now - stats.mtimeMs > cacheTTL) {
|
|
796
|
+
fs.unlinkSync(filePath);
|
|
797
|
+
console.log(`🧹 删除过期缓存文件: ${file}`);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
catch (error) {
|
|
801
|
+
// 忽略单个文件错误
|
|
802
|
+
}
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
catch (error) {
|
|
806
|
+
// 忽略目录读取错误
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* 下载并转码视频
|
|
811
|
+
*/
|
|
812
|
+
async downloadAndTranscode(options, callbacks) {
|
|
813
|
+
try {
|
|
814
|
+
const outputDir = options.outputDir || electron.app.getPath('temp');
|
|
815
|
+
// 获取缓存配置
|
|
816
|
+
const cacheConfig = options.cache || { enabled: true, ttl: this.defaultCacheTTL };
|
|
817
|
+
const cacheEnabled = cacheConfig.enabled !== false;
|
|
818
|
+
const cacheTTL = cacheConfig.ttl || this.defaultCacheTTL;
|
|
819
|
+
// 确保输出目录存在
|
|
820
|
+
if (!fs.existsSync(outputDir)) {
|
|
821
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
822
|
+
}
|
|
823
|
+
// 清理过期缓存文件
|
|
824
|
+
this.cleanExpiredCacheFiles(outputDir, cacheTTL);
|
|
825
|
+
// 生成缓存文件名
|
|
826
|
+
const cacheFileName = this.generateCacheFileName(options);
|
|
827
|
+
const cacheFilePath = path.join(outputDir, cacheFileName);
|
|
828
|
+
// 如果启用缓存,检查缓存文件是否存在
|
|
829
|
+
if (cacheEnabled && this.isCacheFileExists(cacheFilePath)) {
|
|
830
|
+
console.log('🎯 命中缓存,直接返回缓存文件');
|
|
831
|
+
// 获取文件信息
|
|
832
|
+
const stats = fs.statSync(cacheFilePath);
|
|
833
|
+
const result = {
|
|
834
|
+
success: true,
|
|
835
|
+
outputPath: getFileUrl(cacheFilePath),
|
|
836
|
+
fileSize: stats.size,
|
|
837
|
+
fromCache: true
|
|
838
|
+
};
|
|
839
|
+
callbacks?.onComplete?.({
|
|
840
|
+
success: true,
|
|
841
|
+
outputPath: result.outputPath
|
|
842
|
+
});
|
|
843
|
+
return result;
|
|
844
|
+
}
|
|
845
|
+
// 检查FFmpeg是否可用
|
|
846
|
+
const ffmpegAvailable = await this.checkFFmpegAvailable(options.ffmpegPath);
|
|
847
|
+
if (!ffmpegAvailable) {
|
|
848
|
+
throw new Error('FFmpeg不可用,请确保已安装FFmpeg或提供正确的路径');
|
|
849
|
+
}
|
|
850
|
+
// 生成临时文件名和最终输出路径
|
|
851
|
+
const fileName = options.outputName || md5(options.url);
|
|
852
|
+
const format = options.format || 'mp4';
|
|
853
|
+
const tempPath = path.join(outputDir, `${fileName}.temp`);
|
|
854
|
+
const finalOutputPath = path.join(outputDir, `${fileName}.${format}`);
|
|
855
|
+
const outputPath = cacheEnabled ? cacheFilePath : finalOutputPath;
|
|
856
|
+
console.log('📥 开始下载视频...');
|
|
857
|
+
// 下载视频
|
|
858
|
+
await this.downloadVideoFile(options.url, tempPath, callbacks?.onDownloadProgress);
|
|
859
|
+
console.log('🔄 开始转码视频...');
|
|
860
|
+
// 转码视频
|
|
861
|
+
await this.transcodeVideo(tempPath, outputPath, {
|
|
862
|
+
...options,
|
|
863
|
+
outputDir
|
|
864
|
+
}, callbacks?.onTranscodeProgress);
|
|
865
|
+
// 如果启用了缓存,将缓存文件复制到最终输出路径
|
|
866
|
+
if (cacheEnabled && outputPath !== finalOutputPath) {
|
|
867
|
+
fs.copyFileSync(outputPath, finalOutputPath);
|
|
868
|
+
console.log('📋 缓存文件已复制到最终输出路径');
|
|
869
|
+
}
|
|
870
|
+
// 获取视频信息
|
|
871
|
+
const videoInfo = await this.getVideoInfo(outputPath, options.ffmpegPath);
|
|
872
|
+
// 清理临时文件
|
|
873
|
+
if (!options.keepOriginal) {
|
|
874
|
+
fs.unlinkSync(tempPath);
|
|
875
|
+
}
|
|
876
|
+
console.log('💾 文件已保存到缓存');
|
|
877
|
+
const result = {
|
|
878
|
+
success: true,
|
|
879
|
+
outputPath: getFileUrl(cacheEnabled ? finalOutputPath : outputPath),
|
|
880
|
+
originalPath: options.keepOriginal ? getFileUrl(tempPath) : undefined,
|
|
881
|
+
duration: videoInfo.duration,
|
|
882
|
+
fileSize: videoInfo.fileSize,
|
|
883
|
+
fromCache: false
|
|
884
|
+
};
|
|
885
|
+
callbacks?.onComplete?.({
|
|
886
|
+
success: true,
|
|
887
|
+
outputPath: result.outputPath
|
|
888
|
+
});
|
|
889
|
+
return result;
|
|
890
|
+
}
|
|
891
|
+
catch (error) {
|
|
892
|
+
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
|
893
|
+
const result = {
|
|
894
|
+
success: false,
|
|
895
|
+
error: errorMessage
|
|
896
|
+
};
|
|
897
|
+
callbacks?.onComplete?.({
|
|
898
|
+
success: false,
|
|
899
|
+
error: errorMessage
|
|
900
|
+
});
|
|
901
|
+
return result;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* 清除指定目录的所有缓存文件
|
|
906
|
+
*/
|
|
907
|
+
clearCache(outputDir) {
|
|
908
|
+
try {
|
|
909
|
+
const files = fs.readdirSync(outputDir);
|
|
910
|
+
files.forEach(file => {
|
|
911
|
+
const filePath = path.join(outputDir, file);
|
|
912
|
+
try {
|
|
913
|
+
fs.unlinkSync(filePath);
|
|
914
|
+
}
|
|
915
|
+
catch (error) {
|
|
916
|
+
// 忽略单个文件删除错误
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
console.log('🧹 缓存文件已清空');
|
|
920
|
+
}
|
|
921
|
+
catch (error) {
|
|
922
|
+
console.log('⚠️ 清理缓存时发生错误:', error instanceof Error ? error.message : '未知错误');
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* 获取缓存统计信息
|
|
927
|
+
*/
|
|
928
|
+
getCacheStats(outputDir) {
|
|
929
|
+
try {
|
|
930
|
+
const files = fs.readdirSync(outputDir);
|
|
931
|
+
const entries = files.map(file => {
|
|
932
|
+
const filePath = path.join(outputDir, file);
|
|
933
|
+
try {
|
|
934
|
+
const stats = fs.statSync(filePath);
|
|
935
|
+
return {
|
|
936
|
+
fileName: file,
|
|
937
|
+
filePath: filePath,
|
|
938
|
+
fileSize: stats.size,
|
|
939
|
+
mtime: stats.mtimeMs
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
catch {
|
|
943
|
+
return null;
|
|
944
|
+
}
|
|
945
|
+
}).filter((entry) => entry !== null);
|
|
946
|
+
return {
|
|
947
|
+
size: entries.length,
|
|
948
|
+
entries
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
catch (error) {
|
|
952
|
+
return { size: 0, entries: [] };
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* 删除指定URL的缓存文件
|
|
957
|
+
*/
|
|
958
|
+
removeCache(options) {
|
|
959
|
+
try {
|
|
960
|
+
const cacheFileName = this.generateCacheFileName(options);
|
|
961
|
+
const cacheFilePath = path.join(options.outputDir, cacheFileName);
|
|
962
|
+
if (fs.existsSync(cacheFilePath)) {
|
|
963
|
+
fs.unlinkSync(cacheFilePath);
|
|
964
|
+
console.log(`🗑️ 删除缓存文件: ${cacheFileName}`);
|
|
965
|
+
return true;
|
|
966
|
+
}
|
|
967
|
+
return false;
|
|
968
|
+
}
|
|
969
|
+
catch (error) {
|
|
970
|
+
console.log('⚠️ 删除缓存文件时发生错误:', error instanceof Error ? error.message : '未知错误');
|
|
971
|
+
return false;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* 下载视频并转码
|
|
977
|
+
* @param options 下载和转码选项
|
|
978
|
+
* @param callbacks 进度回调
|
|
979
|
+
* @returns 转码结果
|
|
980
|
+
*/
|
|
981
|
+
const downloadVideo = async (options, callbacks) => {
|
|
982
|
+
const downloader = VideoDownloader.getInstance();
|
|
983
|
+
return downloader.downloadAndTranscode(options, callbacks);
|
|
984
|
+
};
|
|
985
|
+
/**
|
|
986
|
+
* 清除指定目录的所有缓存文件
|
|
987
|
+
*/
|
|
988
|
+
const clearVideoCache = (outputDir) => {
|
|
989
|
+
const downloader = VideoDownloader.getInstance();
|
|
990
|
+
downloader.clearCache(outputDir);
|
|
991
|
+
};
|
|
992
|
+
/**
|
|
993
|
+
* 获取缓存统计信息
|
|
994
|
+
*/
|
|
995
|
+
const getVideoCacheStats = (outputDir) => {
|
|
996
|
+
const downloader = VideoDownloader.getInstance();
|
|
997
|
+
return downloader.getCacheStats(outputDir);
|
|
998
|
+
};
|
|
999
|
+
/**
|
|
1000
|
+
* 删除指定URL的缓存文件
|
|
1001
|
+
*/
|
|
1002
|
+
const removeVideoCache = (options) => {
|
|
1003
|
+
const downloader = VideoDownloader.getInstance();
|
|
1004
|
+
return downloader.removeCache(options);
|
|
1005
|
+
};
|
|
487
1006
|
/**
|
|
488
1007
|
* 获取定制Session
|
|
489
1008
|
*/
|
|
@@ -493,25 +1012,34 @@ const getCustomSession = windowManager__namespace.getCustomSession;
|
|
|
493
1012
|
* @returns
|
|
494
1013
|
*/
|
|
495
1014
|
const index = new Proxy({}, {
|
|
496
|
-
get() {
|
|
1015
|
+
get(_target, prop) {
|
|
497
1016
|
if (!exports.isInitialized) {
|
|
498
1017
|
throw new Error('请在ready前先调用initialize');
|
|
499
1018
|
}
|
|
1019
|
+
if (!prop) {
|
|
1020
|
+
// @ts-ignore
|
|
1021
|
+
return global['__GLBOAL_ELECTRON_SDK__'];
|
|
1022
|
+
}
|
|
500
1023
|
// @ts-ignore
|
|
501
|
-
return global['__GLBOAL_ELECTRON_SDK__'];
|
|
1024
|
+
return global['__GLBOAL_ELECTRON_SDK__'][prop];
|
|
502
1025
|
},
|
|
503
1026
|
set() {
|
|
504
|
-
return
|
|
1027
|
+
return false;
|
|
505
1028
|
}
|
|
506
1029
|
});
|
|
507
1030
|
|
|
508
1031
|
exports.ResourceCache = ResourceCache;
|
|
1032
|
+
exports.clearVideoCache = clearVideoCache;
|
|
509
1033
|
exports.default = index;
|
|
1034
|
+
exports.downloadVideo = downloadVideo;
|
|
510
1035
|
exports.enable = enable;
|
|
511
1036
|
exports.getCustomSession = getCustomSession;
|
|
1037
|
+
exports.getFileUrl = getFileUrl;
|
|
512
1038
|
exports.getRandomUUID = getRandomUUID;
|
|
513
1039
|
exports.getSDK = getSDK;
|
|
1040
|
+
exports.getVideoCacheStats = getVideoCacheStats;
|
|
514
1041
|
exports.initialize = initialize;
|
|
515
1042
|
exports.registerProtocol = registerProtocol;
|
|
1043
|
+
exports.removeVideoCache = removeVideoCache;
|
|
516
1044
|
exports.serve = serve;
|
|
517
1045
|
//# sourceMappingURL=index.js.map
|