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