From 0e1c80874bd9af6e3449317bf5f9ea73705e11c3 Mon Sep 17 00:00:00 2001 From: LuanRT Date: Sat, 2 Oct 2021 22:42:53 -0300 Subject: [PATCH] Fix - stream was being piped incorrectly --- lib/Innertube.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/lib/Innertube.js b/lib/Innertube.js index 05f2fd8e..ec187c0e 100644 --- a/lib/Innertube.js +++ b/lib/Innertube.js @@ -46,7 +46,7 @@ class Innertube { return this; } - async search(query, options = { period: 'any', order: 'relevance', duration: 'any' }) { + async search(query, options = { period: 'any', order: 'relevance', duration: 'any', quantity: 100 }) { if (!this.initialized) throw new Error('Missing Innertube data.'); const yt_response = await axios.post(Constants.urls.YT_BASE_URL + '/youtubei/v1/search?key=' + this.key, JSON.stringify({ context: this.context, params: Constants.filters(options.period + ',' + options.duration + ',' + options.order), query }), Constants.innertube_request_opts({ session: this })).catch((error) => error); @@ -110,7 +110,7 @@ class Innertube { let cancel; let cancelled = false; - const stream = new Stream.PassThrough(); + const stream = new Stream.PassThrough({ highWaterMark: 1024 * 512 }); this.requestVideoInfo(id, true).then(async (video_data) => { let formats = []; @@ -191,7 +191,6 @@ class Innertube { let downloaded_size = 0; response.data.on('data', (chunk) => { - stream.write(new Buffer.from(chunk)); downloaded_size += chunk.length; let size = (response.headers['content-length'] / 1024 / 1024).toFixed(2); let percentage = Math.floor((downloaded_size / response.headers['content-length']) * 100); @@ -205,7 +204,6 @@ class Innertube { stream.emit('error', { message: err.message, type: 'DOWNLOAD_ABORTED' }); } }); - response.data.on('end', () => setTimeout(() => stream.emit('end'), 100)); } else { const chunk_size = 1048576 * 10; // 10MB @@ -223,7 +221,6 @@ class Innertube { } response.data.on('data', (chunk) => { - stream.write(new Buffer.from(chunk)); downloaded_size += chunk.length; let size = (selected_format.contentLength / 1024 / 1024).toFixed(2); let percentage = Math.floor((downloaded_size / selected_format.contentLength) * 100); @@ -236,10 +233,9 @@ class Innertube { if (downloaded_size < selected_format.contentLength) { downloadChunk(); - } else { - setTimeout(() => stream.emit('end'), 100); // The delay ensures the last chunk is completely piped. - } + } }); + response.data.on('error', (err) => { if (cancelled) { stream.emit('error', { message: 'Download cancelled.', type: 'DOWNLOAD_CANCELLED' }); @@ -247,6 +243,8 @@ class Innertube { stream.emit('error', { message: err.message, type: 'DOWNLOAD_ABORTED' }); } }); + + response.data.pipe(stream); }; downloadChunk(); } @@ -256,6 +254,7 @@ class Innertube { cancelled = true; cancel(); }; + return stream; }