@lynker-desktop/electron-sdk 0.0.9-alpha.3 → 0.0.9-alpha.30

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