@lynker-desktop/electron-sdk 0.0.9-alpha.5 → 0.0.9-alpha.51

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