From 8e0a94b801bf2782e67313e1d16e917c59ef2db1 Mon Sep 17 00:00:00 2001 From: robin <66371002+robinsws@users.noreply.github.com> Date: Wed, 22 Jul 2026 21:08:37 +0200 Subject: [PATCH] Refactor downloadApiYt to use local yt-dlp Refactor downloadApiYt to use local yt-dlp instead of an external API service. Added error handling and improved title sanitization. --- src/lib/yt-dlp.js | 61 ++++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/src/lib/yt-dlp.js b/src/lib/yt-dlp.js index 3741858..9da5ac6 100644 --- a/src/lib/yt-dlp.js +++ b/src/lib/yt-dlp.js @@ -128,40 +128,41 @@ export async function ytdown(url, type = "video") { } /** - * Download YouTube audio/video via API + * Download YouTube audio/video via local yt-dlp * @param {String} url * @param {Object} opts * @param {Boolean} opts.video - * @param {String} opts.videoQuality - * @param {String} opts.audioFormat + * @param {String} opts.title * @returns {Promise<{ buffer: Buffer, mimetype: string, fileName: string }>} */ export async function downloadApiYt(url, opts = {}) { - const { video = false, title = "youtube" } = opts; - - const result = await ytdown(url, video ? "video" : "audio"); - - if (!result?.download) { - throw new Error("Download link not found"); - } - - const { data } = await axios.get(result.download, { - responseType: "arraybuffer", - }); - - let buffer = Buffer.from(data); - - if (!video) { - buffer = await to_audio(buffer, "mp3"); - } - - const safeTitle = (title || result.info.title || "yt") - .replace(/[\\/:*?"<>|]/g, "") - .slice(0, 60); - - return { - buffer, - mimetype: video ? "video/mp4" : "audio/mpeg", - fileName: `${safeTitle}.${video ? "mp4" : "mp3"}`, - }; + const { video = false, title = "youtube" } = opts; + + try { + // Use local yt-dlp instead of external API service + const result = await downloadYt(url, { + video, + title: title || "youtube", + }); + + let buffer = result.buffer; + + // Convert to MP3 if audio was requested + if (!video) { + buffer = await to_audio(buffer, "mp3"); + } + + const safeTitle = (title || "yt") + .replace(/[\\/:*?"<>|]/g, "") + .slice(0, 60); + + return { + buffer, + mimetype: video ? "video/mp4" : "audio/mpeg", + fileName: `${safeTitle}.${video ? "mp4" : "mp3"}`, + }; + } catch (error) { + console.error("[downloadApiYt] Error:", error.message); + throw error; + } }