Fix - stream was being piped incorrectly

This commit is contained in:
LuanRT
2021-10-02 22:42:53 -03:00
parent c73dde8602
commit 0e1c80874b

View File

@@ -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;
}