@lynker-desktop/electron-sdk 0.0.9-alpha.27 → 0.0.9-alpha.29

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