@lynker-desktop/electron-sdk 0.0.9-alpha.51 → 0.0.9-alpha.53
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.d.ts +2 -98
- package/esm/main/index.d.ts.map +1 -1
- package/esm/main/index.js +4 -687
- package/esm/main/index.js.map +1 -1
- package/esm/main/resource-cache.d.ts +164 -0
- package/esm/main/resource-cache.d.ts.map +1 -0
- package/esm/main/resource-cache.js +612 -0
- package/esm/main/resource-cache.js.map +1 -0
- package/esm/main/video-downloader.d.ts +39 -0
- package/esm/main/video-downloader.d.ts.map +1 -0
- package/esm/main/video-downloader.js +505 -0
- package/esm/main/video-downloader.js.map +1 -0
- package/main/index.d.ts +2 -98
- package/main/index.d.ts.map +1 -1
- package/main/index.js +11 -699
- package/main/index.js.map +1 -1
- package/main/resource-cache.d.ts +164 -0
- package/main/resource-cache.d.ts.map +1 -0
- package/main/resource-cache.js +612 -0
- package/main/resource-cache.js.map +1 -0
- package/main/video-downloader.d.ts +39 -0
- package/main/video-downloader.d.ts.map +1 -0
- package/main/video-downloader.js +510 -0
- package/main/video-downloader.js.map +1 -0
- package/package.json +5 -5
package/esm/main/index.js
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { promisify } from 'node:util';
|
|
4
|
-
import http from 'node:http';
|
|
5
|
-
import https from 'node:https';
|
|
6
|
-
import { spawn } from 'node:child_process';
|
|
7
4
|
import electron, { app, webContents } from 'electron';
|
|
8
5
|
import md5 from 'md5';
|
|
9
6
|
import { v5 } from 'uuid';
|
|
@@ -15,6 +12,8 @@ import * as windowManager from '@lynker-desktop/electron-window-manager/main';
|
|
|
15
12
|
import { IPC_GET_APP_METRICS } from '../common/index.js';
|
|
16
13
|
import { initializeStore } from './store.js';
|
|
17
14
|
import { initializeClipboard } from './clipboard.js';
|
|
15
|
+
import { ResourceCache } from './resource-cache.js';
|
|
16
|
+
import { setFFmpegPath, downloadVideo, clearVideoCache, getVideoCacheStats, removeVideoCache } from './video-downloader.js';
|
|
18
17
|
|
|
19
18
|
if (!remote.isInitialized()) {
|
|
20
19
|
remote.initialize();
|
|
@@ -52,7 +51,7 @@ const initialize = (options) => {
|
|
|
52
51
|
initializeStore();
|
|
53
52
|
initializeClipboard();
|
|
54
53
|
if (options.ffmpegPath) {
|
|
55
|
-
|
|
54
|
+
setFFmpegPath(options.ffmpegPath);
|
|
56
55
|
}
|
|
57
56
|
const wm = windowManager.initialize(preload, loadingViewUrl, errorViewUrl, preloadWebContentsConfig, webviewDomainWhiteList || []);
|
|
58
57
|
if (protocol) {
|
|
@@ -278,231 +277,12 @@ const serve = (options) => {
|
|
|
278
277
|
}
|
|
279
278
|
});
|
|
280
279
|
};
|
|
281
|
-
/**
|
|
282
|
-
* 默认配置
|
|
283
|
-
*/
|
|
284
|
-
const DEFAULT_OPTIONS = {
|
|
285
|
-
cacheDir: '',
|
|
286
|
-
cacheTTL: 24 * 60 * 60 * 1000,
|
|
287
|
-
match: /\.(png|jpe?g|webp|gif|svg|woff2?|ttf|mp4|webm|ogg|css|js)(\?.*)?$/i,
|
|
288
|
-
allowedOrigins: null,
|
|
289
|
-
};
|
|
290
|
-
/**
|
|
291
|
-
* 资源缓存类:拦截并缓存静态资源,提升加载性能
|
|
292
|
-
*/
|
|
293
|
-
class ResourceCache {
|
|
294
|
-
/**
|
|
295
|
-
* 构造函数
|
|
296
|
-
* @param session Electron session
|
|
297
|
-
* @param options 缓存配置
|
|
298
|
-
*/
|
|
299
|
-
constructor(session, options) {
|
|
300
|
-
this.cacheHost = `${ResourceCache.scheme}://-`;
|
|
301
|
-
if (!session)
|
|
302
|
-
throw new Error('ResourceCache: session is required');
|
|
303
|
-
this.session = session;
|
|
304
|
-
// 合并配置,保证类型安全
|
|
305
|
-
this.options = {
|
|
306
|
-
...DEFAULT_OPTIONS,
|
|
307
|
-
...options,
|
|
308
|
-
cacheDir: options.cacheDir,
|
|
309
|
-
cacheTTL: options.cacheTTL ?? DEFAULT_OPTIONS.cacheTTL,
|
|
310
|
-
match: options.match ?? DEFAULT_OPTIONS.match,
|
|
311
|
-
allowedOrigins: options.allowedOrigins ?? DEFAULT_OPTIONS.allowedOrigins,
|
|
312
|
-
};
|
|
313
|
-
if (!this.options.cacheDir) {
|
|
314
|
-
throw new Error('ResourceCache: cacheDir is required');
|
|
315
|
-
}
|
|
316
|
-
// 确保缓存目录存在
|
|
317
|
-
if (!fs.existsSync(this.options.cacheDir)) {
|
|
318
|
-
fs.mkdirSync(this.options.cacheDir, { recursive: true });
|
|
319
|
-
}
|
|
320
|
-
this._registerInterceptor();
|
|
321
|
-
this._cleanOldCache();
|
|
322
|
-
}
|
|
323
|
-
/**
|
|
324
|
-
* 获取资源匹配函数
|
|
325
|
-
*/
|
|
326
|
-
_getMatchFunction() {
|
|
327
|
-
const matcher = this.options.match;
|
|
328
|
-
if (typeof matcher === 'function')
|
|
329
|
-
return matcher;
|
|
330
|
-
if (matcher instanceof RegExp)
|
|
331
|
-
return (url) => matcher.test(url);
|
|
332
|
-
return () => false;
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* 获取来源校验函数
|
|
336
|
-
*/
|
|
337
|
-
_getOriginAllowFunction() {
|
|
338
|
-
const origins = this.options.allowedOrigins;
|
|
339
|
-
if (!origins)
|
|
340
|
-
return () => true;
|
|
341
|
-
if (typeof origins === 'function')
|
|
342
|
-
return origins;
|
|
343
|
-
const prefixList = origins.map(o => o.toLowerCase());
|
|
344
|
-
return (url) => {
|
|
345
|
-
try {
|
|
346
|
-
const origin = new URL(url).origin.toLowerCase();
|
|
347
|
-
return prefixList.some(prefix => origin.startsWith(prefix));
|
|
348
|
-
}
|
|
349
|
-
catch {
|
|
350
|
-
return false;
|
|
351
|
-
}
|
|
352
|
-
};
|
|
353
|
-
}
|
|
354
|
-
/**
|
|
355
|
-
* 获取缓存文件路径
|
|
356
|
-
* @param url 资源URL
|
|
357
|
-
*/
|
|
358
|
-
getCachedPath(url) {
|
|
359
|
-
const md5Str = md5(url);
|
|
360
|
-
const urlObj = new URL(url);
|
|
361
|
-
// 取文件扩展名,若无则用 .res
|
|
362
|
-
const ext = path.extname(urlObj.pathname) || '.res';
|
|
363
|
-
return {
|
|
364
|
-
filePath: path.join(this.options.cacheDir, `${md5Str}${ext}`),
|
|
365
|
-
hostPath: `${this.cacheHost}/${md5Str}${ext}`,
|
|
366
|
-
};
|
|
367
|
-
}
|
|
368
|
-
/**
|
|
369
|
-
* 判断缓存是否有效
|
|
370
|
-
* @param filePath 缓存文件路径
|
|
371
|
-
*/
|
|
372
|
-
isCacheValid(filePath) {
|
|
373
|
-
if (!fs.existsSync(filePath))
|
|
374
|
-
return false;
|
|
375
|
-
const stat = fs.statSync(filePath);
|
|
376
|
-
return Date.now() - stat.mtimeMs < this.options.cacheTTL;
|
|
377
|
-
}
|
|
378
|
-
/**
|
|
379
|
-
* 下载资源到本地缓存
|
|
380
|
-
* @param url 资源URL
|
|
381
|
-
* @param filePath 本地缓存路径
|
|
382
|
-
*/
|
|
383
|
-
downloadResource(url, filePath) {
|
|
384
|
-
const tempFilePath = `${filePath}.cache`;
|
|
385
|
-
const lib = url.startsWith('https') ? https : http;
|
|
386
|
-
const file = fs.createWriteStream(tempFilePath);
|
|
387
|
-
let request;
|
|
388
|
-
const cleanupAndAbort = (errMsg, err) => {
|
|
389
|
-
if (err) {
|
|
390
|
-
console.log(errMsg, err);
|
|
391
|
-
}
|
|
392
|
-
else {
|
|
393
|
-
console.log(errMsg);
|
|
394
|
-
}
|
|
395
|
-
if (request) {
|
|
396
|
-
request.destroy();
|
|
397
|
-
}
|
|
398
|
-
file.close(() => {
|
|
399
|
-
// 使用 existsSync 避免在文件不存在时 unlink 抛出错误
|
|
400
|
-
if (fs.existsSync(tempFilePath)) {
|
|
401
|
-
fs.unlink(tempFilePath, () => { });
|
|
402
|
-
}
|
|
403
|
-
});
|
|
404
|
-
};
|
|
405
|
-
request = lib.get(url, (res) => {
|
|
406
|
-
if (res.statusCode !== 200) {
|
|
407
|
-
res.resume(); // 消费响应数据以释放内存
|
|
408
|
-
cleanupAndAbort(`下载失败,状态码: ${res.statusCode} for ${url}`);
|
|
409
|
-
return;
|
|
410
|
-
}
|
|
411
|
-
res.pipe(file);
|
|
412
|
-
});
|
|
413
|
-
file.on('finish', () => {
|
|
414
|
-
file.close((err) => {
|
|
415
|
-
if (err) {
|
|
416
|
-
return cleanupAndAbort(`关闭临时文件流失败: ${tempFilePath}`, err);
|
|
417
|
-
}
|
|
418
|
-
fs.rename(tempFilePath, filePath, (renameErr) => {
|
|
419
|
-
if (renameErr) {
|
|
420
|
-
cleanupAndAbort(`缓存文件重命名失败 from ${tempFilePath} to ${filePath}`, renameErr);
|
|
421
|
-
}
|
|
422
|
-
});
|
|
423
|
-
});
|
|
424
|
-
});
|
|
425
|
-
file.on('error', (err) => {
|
|
426
|
-
cleanupAndAbort(`写入临时文件失败: ${tempFilePath}`, err);
|
|
427
|
-
});
|
|
428
|
-
request.on('error', (err) => {
|
|
429
|
-
cleanupAndAbort(`下载资源请求失败: ${url}`, err);
|
|
430
|
-
});
|
|
431
|
-
}
|
|
432
|
-
/**
|
|
433
|
-
* 清理过期缓存文件
|
|
434
|
-
*/
|
|
435
|
-
_cleanOldCache() {
|
|
436
|
-
const files = fs.readdirSync(this.options.cacheDir);
|
|
437
|
-
const now = Date.now();
|
|
438
|
-
files.forEach(file => {
|
|
439
|
-
const fullPath = path.join(this.options.cacheDir, file);
|
|
440
|
-
try {
|
|
441
|
-
const stat = fs.statSync(fullPath);
|
|
442
|
-
if (now - stat.mtimeMs > this.options.cacheTTL) {
|
|
443
|
-
fs.unlinkSync(fullPath);
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
catch {
|
|
447
|
-
// 忽略单个文件异常
|
|
448
|
-
}
|
|
449
|
-
});
|
|
450
|
-
}
|
|
451
|
-
/**
|
|
452
|
-
* 注册 Electron 请求拦截器,实现资源缓存
|
|
453
|
-
*/
|
|
454
|
-
_registerInterceptor() {
|
|
455
|
-
const shouldCache = this._getMatchFunction();
|
|
456
|
-
const isAllowedOrigin = this._getOriginAllowFunction();
|
|
457
|
-
this.session.webRequest.onBeforeRequest({ urls: ['http://*/*', 'https://*/*'] }, (details, callback) => {
|
|
458
|
-
const url = details.url;
|
|
459
|
-
// 不匹配或来源不允许,直接放行
|
|
460
|
-
if (details.method !== 'GET' || !shouldCache(url) || !isAllowedOrigin(url))
|
|
461
|
-
return callback({});
|
|
462
|
-
const cachePath = this.getCachedPath(url);
|
|
463
|
-
// 命中缓存,直接重定向到本地文件
|
|
464
|
-
if (this.isCacheValid(cachePath.filePath)) {
|
|
465
|
-
console.log('命中缓存: ', url, cachePath);
|
|
466
|
-
return callback({ redirectURL: cachePath.hostPath });
|
|
467
|
-
}
|
|
468
|
-
console.log('未命中缓存: ', url);
|
|
469
|
-
// 未命中则异步下载,当前请求正常放行
|
|
470
|
-
this.downloadResource(url, cachePath.filePath);
|
|
471
|
-
return callback({});
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
ResourceCache.scheme = 'cachefile';
|
|
476
280
|
/**
|
|
477
281
|
* @electron/remote/main enable方法
|
|
478
282
|
* @param webContents
|
|
479
283
|
* @returns
|
|
480
284
|
*/
|
|
481
285
|
const enable = (webContents) => remote.enable(webContents);
|
|
482
|
-
/**
|
|
483
|
-
* 生成跨平台的文件URL
|
|
484
|
-
* @param filePath 文件路径
|
|
485
|
-
* @returns file:// URL
|
|
486
|
-
*/
|
|
487
|
-
function getFileUrl(filePath) {
|
|
488
|
-
if (!filePath) {
|
|
489
|
-
return '';
|
|
490
|
-
}
|
|
491
|
-
if (filePath.startsWith('file://')) {
|
|
492
|
-
return filePath;
|
|
493
|
-
}
|
|
494
|
-
// 在Windows上,需要添加驱动器字母前的斜杠
|
|
495
|
-
if (process.platform === 'win32') {
|
|
496
|
-
// 如果路径是绝对路径(如 C:\path\to\file),转换为 /C:/path/to/file
|
|
497
|
-
if (filePath.match(/^[A-Za-z]:/)) {
|
|
498
|
-
return `file:///${filePath}`;
|
|
499
|
-
}
|
|
500
|
-
// 如果已经是 /C:/path/to/file 格式,直接添加 file://
|
|
501
|
-
return `file://${filePath}`;
|
|
502
|
-
}
|
|
503
|
-
// macOS 和 Linux 使用 file:/// 前缀
|
|
504
|
-
return `file://${filePath}`;
|
|
505
|
-
}
|
|
506
286
|
/**
|
|
507
287
|
* 获取随机UUID
|
|
508
288
|
* @param key
|
|
@@ -526,469 +306,6 @@ function getRandomUUID(key = `${Date.now()}`) {
|
|
|
526
306
|
const uuid = v5(`${JSON.stringify(key)}_${Date.now()}_${randomValue}`, v5.URL);
|
|
527
307
|
return uuid;
|
|
528
308
|
}
|
|
529
|
-
/**
|
|
530
|
-
* 视频下载和转码类
|
|
531
|
-
*/
|
|
532
|
-
class VideoDownloader {
|
|
533
|
-
constructor() {
|
|
534
|
-
this.ffmpegPath = '';
|
|
535
|
-
this.defaultCacheTTL = 24 * 60 * 60 * 1000; // 24小时缓存有效期
|
|
536
|
-
}
|
|
537
|
-
static getInstance() {
|
|
538
|
-
if (!VideoDownloader.instance) {
|
|
539
|
-
VideoDownloader.instance = new VideoDownloader();
|
|
540
|
-
}
|
|
541
|
-
return VideoDownloader.instance;
|
|
542
|
-
}
|
|
543
|
-
setFFmpegPath(ffmpegPath) {
|
|
544
|
-
this.ffmpegPath = ffmpegPath;
|
|
545
|
-
}
|
|
546
|
-
/**
|
|
547
|
-
* 下载视频文件
|
|
548
|
-
*/
|
|
549
|
-
async downloadVideoFile(url, outputPath, onProgress) {
|
|
550
|
-
return new Promise((resolve, reject) => {
|
|
551
|
-
const lib = url.startsWith('https') ? https : http;
|
|
552
|
-
const file = fs.createWriteStream(outputPath);
|
|
553
|
-
let downloadedBytes = 0;
|
|
554
|
-
let totalBytes = 0;
|
|
555
|
-
let startTime = Date.now();
|
|
556
|
-
let lastTime = startTime;
|
|
557
|
-
let lastBytes = 0;
|
|
558
|
-
const cleanup = () => {
|
|
559
|
-
if (file) {
|
|
560
|
-
file.close();
|
|
561
|
-
fs.unlinkSync(outputPath);
|
|
562
|
-
}
|
|
563
|
-
};
|
|
564
|
-
const request = lib.get(url, (res) => {
|
|
565
|
-
if (res.statusCode !== 200) {
|
|
566
|
-
cleanup();
|
|
567
|
-
reject(new Error(`下载失败,状态码: ${res.statusCode}`));
|
|
568
|
-
return;
|
|
569
|
-
}
|
|
570
|
-
totalBytes = parseInt(res.headers['content-length'] || '0', 10);
|
|
571
|
-
res.on('data', (chunk) => {
|
|
572
|
-
downloadedBytes += chunk.length;
|
|
573
|
-
const now = Date.now();
|
|
574
|
-
if (onProgress && (now - lastTime > 100 || downloadedBytes === totalBytes)) {
|
|
575
|
-
const speed = ((downloadedBytes - lastBytes) * 1000) / (now - lastTime);
|
|
576
|
-
onProgress({
|
|
577
|
-
downloaded: downloadedBytes,
|
|
578
|
-
total: totalBytes,
|
|
579
|
-
percentage: totalBytes > 0 ? (downloadedBytes / totalBytes) * 100 : 0,
|
|
580
|
-
speed: speed || 0
|
|
581
|
-
});
|
|
582
|
-
lastTime = now;
|
|
583
|
-
lastBytes = downloadedBytes;
|
|
584
|
-
}
|
|
585
|
-
});
|
|
586
|
-
res.pipe(file);
|
|
587
|
-
file.on('finish', () => {
|
|
588
|
-
file.close();
|
|
589
|
-
resolve();
|
|
590
|
-
});
|
|
591
|
-
file.on('error', (err) => {
|
|
592
|
-
cleanup();
|
|
593
|
-
reject(err);
|
|
594
|
-
});
|
|
595
|
-
});
|
|
596
|
-
request.on('error', (err) => {
|
|
597
|
-
cleanup();
|
|
598
|
-
reject(err);
|
|
599
|
-
});
|
|
600
|
-
});
|
|
601
|
-
}
|
|
602
|
-
/**
|
|
603
|
-
* 使用FFmpeg转码视频
|
|
604
|
-
*/
|
|
605
|
-
async transcodeVideo(inputPath, outputPath, options, onProgress) {
|
|
606
|
-
return new Promise((resolve, reject) => {
|
|
607
|
-
const ffmpegPath = options.ffmpegPath || this.ffmpegPath;
|
|
608
|
-
if (!ffmpegPath) {
|
|
609
|
-
reject(new Error('FFmpeg路径未设置'));
|
|
610
|
-
return;
|
|
611
|
-
}
|
|
612
|
-
const format = options.format || 'mp4';
|
|
613
|
-
const quality = options.quality || 18;
|
|
614
|
-
const videoCodec = options.videoCodec || 'h264';
|
|
615
|
-
const audioCodec = options.audioCodec || 'aac';
|
|
616
|
-
// 根据格式选择合适的编码器
|
|
617
|
-
const getCodecForFormat = (format, videoCodec, audioCodec) => {
|
|
618
|
-
switch (format) {
|
|
619
|
-
case 'webm':
|
|
620
|
-
return {
|
|
621
|
-
videoCodec: videoCodec === 'h264' ? 'libvpx-vp9' : videoCodec,
|
|
622
|
-
audioCodec: audioCodec === 'aac' ? 'libopus' : audioCodec
|
|
623
|
-
};
|
|
624
|
-
case 'avi':
|
|
625
|
-
return {
|
|
626
|
-
videoCodec: videoCodec === 'h265' ? 'h264' : videoCodec, // AVI不支持H265
|
|
627
|
-
audioCodec: audioCodec === 'opus' ? 'mp3' : audioCodec
|
|
628
|
-
};
|
|
629
|
-
case 'mov':
|
|
630
|
-
return {
|
|
631
|
-
videoCodec: videoCodec === 'vp9' ? 'h264' : videoCodec, // MOV对VP9支持有限
|
|
632
|
-
audioCodec: audioCodec === 'opus' ? 'aac' : audioCodec
|
|
633
|
-
};
|
|
634
|
-
default: // mp4, mkv
|
|
635
|
-
return { videoCodec, audioCodec };
|
|
636
|
-
}
|
|
637
|
-
};
|
|
638
|
-
const { videoCodec: finalVideoCodec, audioCodec: finalAudioCodec } = getCodecForFormat(format, videoCodec, audioCodec);
|
|
639
|
-
// 构建FFmpeg命令
|
|
640
|
-
const args = [
|
|
641
|
-
'-i', inputPath,
|
|
642
|
-
'-c:v', finalVideoCodec,
|
|
643
|
-
'-c:a', finalAudioCodec,
|
|
644
|
-
'-crf', quality.toString(),
|
|
645
|
-
'-preset', 'medium',
|
|
646
|
-
'-f', format, // 指定输出格式
|
|
647
|
-
'-y', // 覆盖输出文件
|
|
648
|
-
outputPath
|
|
649
|
-
];
|
|
650
|
-
const ffmpegProcess = spawn(ffmpegPath, args);
|
|
651
|
-
let duration = 0;
|
|
652
|
-
let stderr = '';
|
|
653
|
-
ffmpegProcess.stderr.on('data', (data) => {
|
|
654
|
-
stderr += data.toString();
|
|
655
|
-
// 解析FFmpeg输出获取进度
|
|
656
|
-
if (onProgress) {
|
|
657
|
-
const durationMatch = stderr.match(/Duration: (\d{2}):(\d{2}):(\d{2})\.(\d{2})/);
|
|
658
|
-
if (durationMatch && duration === 0) {
|
|
659
|
-
const hours = parseInt(durationMatch[1] || '0', 10);
|
|
660
|
-
const minutes = parseInt(durationMatch[2] || '0', 10);
|
|
661
|
-
const seconds = parseInt(durationMatch[3] || '0', 10);
|
|
662
|
-
const centiseconds = parseInt(durationMatch[4] || '0', 10);
|
|
663
|
-
duration = hours * 3600 + minutes * 60 + seconds + centiseconds / 100;
|
|
664
|
-
}
|
|
665
|
-
const timeMatch = stderr.match(/time=(\d{2}):(\d{2}):(\d{2})\.(\d{2})/);
|
|
666
|
-
if (timeMatch && duration > 0) {
|
|
667
|
-
const hours = parseInt(timeMatch[1] || '0', 10);
|
|
668
|
-
const minutes = parseInt(timeMatch[2] || '0', 10);
|
|
669
|
-
const seconds = parseInt(timeMatch[3] || '0', 10);
|
|
670
|
-
const centiseconds = parseInt(timeMatch[4] || '0', 10);
|
|
671
|
-
const currentTime = hours * 3600 + minutes * 60 + seconds + centiseconds / 100;
|
|
672
|
-
const percentage = (currentTime / duration) * 100;
|
|
673
|
-
const speedMatch = stderr.match(/speed=([\d.]+)x/);
|
|
674
|
-
const speed = speedMatch ? parseFloat(speedMatch[1] || '1') : 1;
|
|
675
|
-
onProgress({
|
|
676
|
-
percentage: Math.min(percentage, 100),
|
|
677
|
-
time: currentTime,
|
|
678
|
-
speed: speed
|
|
679
|
-
});
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
});
|
|
683
|
-
ffmpegProcess.on('close', (code) => {
|
|
684
|
-
if (code === 0) {
|
|
685
|
-
resolve();
|
|
686
|
-
}
|
|
687
|
-
else {
|
|
688
|
-
reject(new Error(`FFmpeg转码失败,退出码: ${code}\n${stderr}`));
|
|
689
|
-
}
|
|
690
|
-
});
|
|
691
|
-
ffmpegProcess.on('error', (err) => {
|
|
692
|
-
reject(new Error(`FFmpeg执行失败: ${err.message}`));
|
|
693
|
-
});
|
|
694
|
-
});
|
|
695
|
-
}
|
|
696
|
-
/**
|
|
697
|
-
* 检查FFmpeg是否可用
|
|
698
|
-
*/
|
|
699
|
-
async checkFFmpegAvailable(ffmpegPath) {
|
|
700
|
-
return new Promise((resolve) => {
|
|
701
|
-
const command = ffmpegPath || this.ffmpegPath;
|
|
702
|
-
if (!command) {
|
|
703
|
-
resolve(false);
|
|
704
|
-
return;
|
|
705
|
-
}
|
|
706
|
-
const childProcess = spawn(command, ['-version']);
|
|
707
|
-
childProcess.on('error', (error) => {
|
|
708
|
-
console.log("checkFFmpegAvailable", error);
|
|
709
|
-
resolve(false);
|
|
710
|
-
});
|
|
711
|
-
childProcess.on('close', (code) => {
|
|
712
|
-
console.log("checkFFmpegAvailable", code);
|
|
713
|
-
resolve(code === 0);
|
|
714
|
-
});
|
|
715
|
-
});
|
|
716
|
-
}
|
|
717
|
-
/**
|
|
718
|
-
* 获取视频信息
|
|
719
|
-
*/
|
|
720
|
-
async getVideoInfo(inputPath, ffmpegPath) {
|
|
721
|
-
return new Promise((resolve, reject) => {
|
|
722
|
-
const ffmpegPath_cmd = ffmpegPath || this.ffmpegPath;
|
|
723
|
-
const args = ['-i', inputPath, '-f', 'null', '-'];
|
|
724
|
-
if (!ffmpegPath_cmd) {
|
|
725
|
-
resolve({ duration: 0, fileSize: 0 });
|
|
726
|
-
return;
|
|
727
|
-
}
|
|
728
|
-
const ffmpegProcess = spawn(ffmpegPath_cmd, args);
|
|
729
|
-
let stderr = '';
|
|
730
|
-
let duration = 0;
|
|
731
|
-
ffmpegProcess.stderr.on('data', (data) => {
|
|
732
|
-
stderr += data.toString();
|
|
733
|
-
const durationMatch = stderr.match(/Duration: (\d{2}):(\d{2}):(\d{2})\.(\d{2})/);
|
|
734
|
-
if (durationMatch) {
|
|
735
|
-
const hours = parseInt(durationMatch[1] || '0', 10);
|
|
736
|
-
const minutes = parseInt(durationMatch[2] || '0', 10);
|
|
737
|
-
const seconds = parseInt(durationMatch[3] || '0', 10);
|
|
738
|
-
const centiseconds = parseInt(durationMatch[4] || '0', 10);
|
|
739
|
-
duration = hours * 3600 + minutes * 60 + seconds + centiseconds / 100;
|
|
740
|
-
}
|
|
741
|
-
});
|
|
742
|
-
ffmpegProcess.on('close', () => {
|
|
743
|
-
const stats = fs.statSync(inputPath);
|
|
744
|
-
resolve({
|
|
745
|
-
duration,
|
|
746
|
-
fileSize: stats.size
|
|
747
|
-
});
|
|
748
|
-
});
|
|
749
|
-
ffmpegProcess.on('error', (err) => {
|
|
750
|
-
reject(err);
|
|
751
|
-
});
|
|
752
|
-
});
|
|
753
|
-
}
|
|
754
|
-
/**
|
|
755
|
-
* 生成缓存文件名(基于URL的MD5)
|
|
756
|
-
*/
|
|
757
|
-
generateCacheFileName(options) {
|
|
758
|
-
const format = options.format || 'mp4';
|
|
759
|
-
const urlMd5 = md5(options.url);
|
|
760
|
-
return `${urlMd5}.${format}`;
|
|
761
|
-
}
|
|
762
|
-
/**
|
|
763
|
-
* 检查缓存文件是否存在
|
|
764
|
-
*/
|
|
765
|
-
isCacheFileExists(cacheFilePath) {
|
|
766
|
-
console.log('检查缓存文件是否存在: ', cacheFilePath);
|
|
767
|
-
return fs.existsSync(cacheFilePath);
|
|
768
|
-
}
|
|
769
|
-
/**
|
|
770
|
-
* 清理过期缓存文件
|
|
771
|
-
*/
|
|
772
|
-
cleanExpiredCacheFiles(outputDir, cacheTTL = this.defaultCacheTTL) {
|
|
773
|
-
try {
|
|
774
|
-
const files = fs.readdirSync(outputDir);
|
|
775
|
-
const now = Date.now();
|
|
776
|
-
files.forEach(file => {
|
|
777
|
-
const filePath = path.join(outputDir, file);
|
|
778
|
-
try {
|
|
779
|
-
const stats = fs.statSync(filePath);
|
|
780
|
-
// 如果文件超过缓存时间,删除它
|
|
781
|
-
if (now - stats.mtimeMs > cacheTTL) {
|
|
782
|
-
fs.unlinkSync(filePath);
|
|
783
|
-
console.log(`🧹 删除过期缓存文件: ${file}`);
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
catch (error) {
|
|
787
|
-
// 忽略单个文件错误
|
|
788
|
-
}
|
|
789
|
-
});
|
|
790
|
-
}
|
|
791
|
-
catch (error) {
|
|
792
|
-
// 忽略目录读取错误
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
/**
|
|
796
|
-
* 下载并转码视频
|
|
797
|
-
*/
|
|
798
|
-
async downloadAndTranscode(options, callbacks) {
|
|
799
|
-
try {
|
|
800
|
-
const outputDir = options.outputDir || app.getPath('temp');
|
|
801
|
-
// 获取缓存配置
|
|
802
|
-
const cacheConfig = options.cache || { enabled: true, ttl: this.defaultCacheTTL };
|
|
803
|
-
const cacheEnabled = cacheConfig.enabled !== false;
|
|
804
|
-
const cacheTTL = cacheConfig.ttl || this.defaultCacheTTL;
|
|
805
|
-
// 确保输出目录存在
|
|
806
|
-
if (!fs.existsSync(outputDir)) {
|
|
807
|
-
fs.mkdirSync(outputDir, { recursive: true });
|
|
808
|
-
}
|
|
809
|
-
// 清理过期缓存文件
|
|
810
|
-
this.cleanExpiredCacheFiles(outputDir, cacheTTL);
|
|
811
|
-
// 生成缓存文件名
|
|
812
|
-
const cacheFileName = this.generateCacheFileName(options);
|
|
813
|
-
const cacheFilePath = path.join(outputDir, cacheFileName);
|
|
814
|
-
// 如果启用缓存,检查缓存文件是否存在
|
|
815
|
-
if (cacheEnabled && this.isCacheFileExists(cacheFilePath)) {
|
|
816
|
-
console.log('🎯 命中缓存,直接返回缓存文件');
|
|
817
|
-
// 获取文件信息
|
|
818
|
-
const stats = fs.statSync(cacheFilePath);
|
|
819
|
-
const result = {
|
|
820
|
-
success: true,
|
|
821
|
-
outputPath: getFileUrl(cacheFilePath),
|
|
822
|
-
fileSize: stats.size,
|
|
823
|
-
fromCache: true
|
|
824
|
-
};
|
|
825
|
-
callbacks?.onComplete?.({
|
|
826
|
-
success: true,
|
|
827
|
-
outputPath: result.outputPath
|
|
828
|
-
});
|
|
829
|
-
return result;
|
|
830
|
-
}
|
|
831
|
-
// 检查FFmpeg是否可用
|
|
832
|
-
const ffmpegAvailable = await this.checkFFmpegAvailable(options.ffmpegPath);
|
|
833
|
-
if (!ffmpegAvailable) {
|
|
834
|
-
throw new Error('FFmpeg不可用,请确保已安装FFmpeg或提供正确的路径');
|
|
835
|
-
}
|
|
836
|
-
// 生成临时文件名和最终输出路径
|
|
837
|
-
const fileName = options.outputName || md5(options.url);
|
|
838
|
-
const format = options.format || 'mp4';
|
|
839
|
-
const tempPath = path.join(outputDir, `${fileName}.temp`);
|
|
840
|
-
const finalOutputPath = path.join(outputDir, `${fileName}.${format}`);
|
|
841
|
-
const outputPath = cacheEnabled ? cacheFilePath : finalOutputPath;
|
|
842
|
-
console.log('📥 开始下载视频...');
|
|
843
|
-
// 下载视频
|
|
844
|
-
await this.downloadVideoFile(options.url, tempPath, callbacks?.onDownloadProgress);
|
|
845
|
-
console.log('🔄 开始转码视频...');
|
|
846
|
-
// 转码视频
|
|
847
|
-
await this.transcodeVideo(tempPath, outputPath, {
|
|
848
|
-
...options,
|
|
849
|
-
outputDir
|
|
850
|
-
}, callbacks?.onTranscodeProgress);
|
|
851
|
-
// 如果启用了缓存,将缓存文件复制到最终输出路径
|
|
852
|
-
if (cacheEnabled && outputPath !== finalOutputPath) {
|
|
853
|
-
fs.copyFileSync(outputPath, finalOutputPath);
|
|
854
|
-
console.log('📋 缓存文件已复制到最终输出路径');
|
|
855
|
-
}
|
|
856
|
-
// 获取视频信息
|
|
857
|
-
const videoInfo = await this.getVideoInfo(outputPath, options.ffmpegPath);
|
|
858
|
-
// 清理临时文件
|
|
859
|
-
if (!options.keepOriginal) {
|
|
860
|
-
fs.unlinkSync(tempPath);
|
|
861
|
-
}
|
|
862
|
-
console.log('💾 文件已保存到缓存');
|
|
863
|
-
const result = {
|
|
864
|
-
success: true,
|
|
865
|
-
outputPath: getFileUrl(cacheEnabled ? finalOutputPath : outputPath),
|
|
866
|
-
originalPath: options.keepOriginal ? getFileUrl(tempPath) : undefined,
|
|
867
|
-
duration: videoInfo.duration,
|
|
868
|
-
fileSize: videoInfo.fileSize,
|
|
869
|
-
fromCache: false
|
|
870
|
-
};
|
|
871
|
-
callbacks?.onComplete?.({
|
|
872
|
-
success: true,
|
|
873
|
-
outputPath: result.outputPath
|
|
874
|
-
});
|
|
875
|
-
return result;
|
|
876
|
-
}
|
|
877
|
-
catch (error) {
|
|
878
|
-
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
|
879
|
-
const result = {
|
|
880
|
-
success: false,
|
|
881
|
-
error: errorMessage
|
|
882
|
-
};
|
|
883
|
-
callbacks?.onComplete?.({
|
|
884
|
-
success: false,
|
|
885
|
-
error: errorMessage
|
|
886
|
-
});
|
|
887
|
-
return result;
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
/**
|
|
891
|
-
* 清除指定目录的所有缓存文件
|
|
892
|
-
*/
|
|
893
|
-
clearCache(outputDir) {
|
|
894
|
-
try {
|
|
895
|
-
const files = fs.readdirSync(outputDir);
|
|
896
|
-
files.forEach(file => {
|
|
897
|
-
const filePath = path.join(outputDir, file);
|
|
898
|
-
try {
|
|
899
|
-
fs.unlinkSync(filePath);
|
|
900
|
-
}
|
|
901
|
-
catch (error) {
|
|
902
|
-
// 忽略单个文件删除错误
|
|
903
|
-
}
|
|
904
|
-
});
|
|
905
|
-
console.log('🧹 缓存文件已清空');
|
|
906
|
-
}
|
|
907
|
-
catch (error) {
|
|
908
|
-
console.log('⚠️ 清理缓存时发生错误:', error instanceof Error ? error.message : '未知错误');
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
/**
|
|
912
|
-
* 获取缓存统计信息
|
|
913
|
-
*/
|
|
914
|
-
getCacheStats(outputDir) {
|
|
915
|
-
try {
|
|
916
|
-
const files = fs.readdirSync(outputDir);
|
|
917
|
-
const entries = files.map(file => {
|
|
918
|
-
const filePath = path.join(outputDir, file);
|
|
919
|
-
try {
|
|
920
|
-
const stats = fs.statSync(filePath);
|
|
921
|
-
return {
|
|
922
|
-
fileName: file,
|
|
923
|
-
filePath: filePath,
|
|
924
|
-
fileSize: stats.size,
|
|
925
|
-
mtime: stats.mtimeMs
|
|
926
|
-
};
|
|
927
|
-
}
|
|
928
|
-
catch {
|
|
929
|
-
return null;
|
|
930
|
-
}
|
|
931
|
-
}).filter((entry) => entry !== null);
|
|
932
|
-
return {
|
|
933
|
-
size: entries.length,
|
|
934
|
-
entries
|
|
935
|
-
};
|
|
936
|
-
}
|
|
937
|
-
catch (error) {
|
|
938
|
-
return { size: 0, entries: [] };
|
|
939
|
-
}
|
|
940
|
-
}
|
|
941
|
-
/**
|
|
942
|
-
* 删除指定URL的缓存文件
|
|
943
|
-
*/
|
|
944
|
-
removeCache(options) {
|
|
945
|
-
try {
|
|
946
|
-
const cacheFileName = this.generateCacheFileName(options);
|
|
947
|
-
const cacheFilePath = path.join(options.outputDir, cacheFileName);
|
|
948
|
-
if (fs.existsSync(cacheFilePath)) {
|
|
949
|
-
fs.unlinkSync(cacheFilePath);
|
|
950
|
-
console.log(`🗑️ 删除缓存文件: ${cacheFileName}`);
|
|
951
|
-
return true;
|
|
952
|
-
}
|
|
953
|
-
return false;
|
|
954
|
-
}
|
|
955
|
-
catch (error) {
|
|
956
|
-
console.log('⚠️ 删除缓存文件时发生错误:', error instanceof Error ? error.message : '未知错误');
|
|
957
|
-
return false;
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
/**
|
|
962
|
-
* 下载视频并转码
|
|
963
|
-
* @param options 下载和转码选项
|
|
964
|
-
* @param callbacks 进度回调
|
|
965
|
-
* @returns 转码结果
|
|
966
|
-
*/
|
|
967
|
-
const downloadVideo = async (options, callbacks) => {
|
|
968
|
-
const downloader = VideoDownloader.getInstance();
|
|
969
|
-
return downloader.downloadAndTranscode(options, callbacks);
|
|
970
|
-
};
|
|
971
|
-
/**
|
|
972
|
-
* 清除指定目录的所有缓存文件
|
|
973
|
-
*/
|
|
974
|
-
const clearVideoCache = (outputDir) => {
|
|
975
|
-
const downloader = VideoDownloader.getInstance();
|
|
976
|
-
downloader.clearCache(outputDir);
|
|
977
|
-
};
|
|
978
|
-
/**
|
|
979
|
-
* 获取缓存统计信息
|
|
980
|
-
*/
|
|
981
|
-
const getVideoCacheStats = (outputDir) => {
|
|
982
|
-
const downloader = VideoDownloader.getInstance();
|
|
983
|
-
return downloader.getCacheStats(outputDir);
|
|
984
|
-
};
|
|
985
|
-
/**
|
|
986
|
-
* 删除指定URL的缓存文件
|
|
987
|
-
*/
|
|
988
|
-
const removeVideoCache = (options) => {
|
|
989
|
-
const downloader = VideoDownloader.getInstance();
|
|
990
|
-
return downloader.removeCache(options);
|
|
991
|
-
};
|
|
992
309
|
/**
|
|
993
310
|
* 获取定制Session
|
|
994
311
|
*/
|
|
@@ -1014,5 +331,5 @@ const index = new Proxy({}, {
|
|
|
1014
331
|
}
|
|
1015
332
|
});
|
|
1016
333
|
|
|
1017
|
-
export { ResourceCache,
|
|
334
|
+
export { ResourceCache, index as default, enable, getCustomSession, getRandomUUID, getSDK, initialize, isInitialized, registerProtocol, serve };
|
|
1018
335
|
//# sourceMappingURL=index.js.map
|