UNPKG

@lzwme/m3u8-dl

Version:

Batch download of m3u8 files and convert to mp4

84 lines (83 loc) 3.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fileDownload = fileDownload; const node_path_1 = require("node:path"); const fe_utils_1 = require("@lzwme/fe-utils"); const console_log_colors_1 = require("console-log-colors"); const format_options_js_1 = require("./format-options.js"); const utils_js_1 = require("./utils.js"); async function fileDownload(u, opts) { utils_js_1.logger.debug('fileDownload', u, opts); const { url, options } = (0, format_options_js_1.formatOptions)(u, opts); const startTime = Date.now(); const stats = { url, startTime, progress: 0, tsSuccess: 0, tsFailed: 0, tsCount: 0, duration: 0, durationDownloaded: 0, downloadedSize: 0, avgSpeed: 0, avgSpeedDesc: '0B/s', speed: 0, speedDesc: '0B/s', remainingTime: 0, filename: options.filename, localVideo: (0, node_path_1.resolve)(options.saveDir, options.filename), }; utils_js_1.logger.debug('开始下载', (0, console_log_colors_1.gray)(url), (0, console_log_colors_1.cyan)(stats.localVideo)); if (options.onInited) options.onInited(stats, null, null); try { const r = await (0, fe_utils_1.download)({ url, filepath: stats.localVideo, paralelism: options.threadNum, force: options.force, requestOptions: { headers: { referer: new URL(url).origin, ...(0, utils_js_1.formatHeaders)(options.headers), }, rejectUnauthorized: false, }, onProgress: info => { stats.progress = +info.percent.toFixed(2); stats.size = info.size; stats.downloadedSize = info.downloaded; stats.speed = info.speed; stats.speedDesc = `${(0, fe_utils_1.formatByteSize)(stats.speed)}/s`; stats.remainingTime = Math.round((info.size - info.downloaded) / stats.speed); if (options.showProgress) { const processBar = info.percent === -1 ? '' : '='.repeat(Math.floor(stats.progress * 0.2)).padEnd(20, '-'); utils_js_1.logger.logInline([ `${stats.progress}% [${(0, console_log_colors_1.greenBright)(processBar)}] `, `${(0, console_log_colors_1.blueBright)((0, fe_utils_1.formatByteSize)(stats.downloadedSize))} ${(0, console_log_colors_1.yellowBright)((0, fe_utils_1.formatTimeCost)(startTime))} ${(0, console_log_colors_1.magentaBright)(stats.speedDesc)} `, stats.progress === 100 ? '\n' : stats.remainingTime ? `${(0, console_log_colors_1.cyan)((0, fe_utils_1.formatTimeCost)(Date.now() - stats.remainingTime))}` : '', ].join('')); } if (options.onProgress) { return options.onProgress(info.downloaded, info.size, null, stats); } }, }); stats.endTime = Date.now(); return { errmsg: r.filepath ? '下载完成' : '下载失败', ...r, stats, }; } catch (error) { utils_js_1.logger.error('下载失败', error.message, (0, console_log_colors_1.gray)(url)); stats.errmsg = error.message; return { isExist: false, errmsg: `下载失败: ${error.message}`, stats, }; } }