Misc fixes on yt downloader

This commit is contained in:
Lucas Gabriel 2024-09-29 23:09:44 -03:00
parent 56041a56c1
commit 459a2857b3
No known key found for this signature in database
GPG Key ID: D9B075FC6DC93985
3 changed files with 103 additions and 69 deletions

View File

@ -15,9 +15,9 @@ function getYtDlpPath() {
const platform = os.platform(); const platform = os.platform();
if (platform === 'linux') { if (platform === 'linux') {
return 'yt-dlp'; return 'yt-dlp';
}l }
return ytDlpPaths[platform] || 'yt-dlp'; return ytDlpPaths[platform] || 'yt-dlp';
}; }
async function downloadFromYoutube(command, args) { async function downloadFromYoutube(command, args) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -29,7 +29,7 @@ async function downloadFromYoutube(command, args) {
} }
}); });
}); });
}; }
async function getApproxSize(command, videoUrl) { async function getApproxSize(command, videoUrl) {
const args = [videoUrl, '--compat-opt', 'manifest-filesize-approx', '-O', 'filesize_approx']; const args = [videoUrl, '--compat-opt', 'manifest-filesize-approx', '-O', 'filesize_approx'];
@ -50,11 +50,19 @@ async function getApproxSize(command, videoUrl) {
} }
}); });
}); });
}; }
function timeoutPromise(timeout) {
return new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Timeout: Check took too long'));
}, timeout);
});
}
module.exports = (bot) => { module.exports = (bot) => {
bot.command(['yt', 'ytdl'], spamwatchMiddleware, async (ctx) => { bot.command(['yt', 'ytdl'], spamwatchMiddleware, async (ctx) => {
const strings = getStrings(ctx.from.language_code); const Strings = getStrings(ctx.from.language_code);
const ytDlpPath = getYtDlpPath(); const ytDlpPath = getYtDlpPath();
const userId = ctx.from.id; const userId = ctx.from.id;
const videoUrl = ctx.message.text.split(' ').slice(1).join(' '); const videoUrl = ctx.message.text.split(' ').slice(1).join(' ');
@ -63,20 +71,28 @@ module.exports = (bot) => {
const cmdArgs = "--max-filesize 2G --no-playlist --merge-output-format mp4 -o"; const cmdArgs = "--max-filesize 2G --no-playlist --merge-output-format mp4 -o";
const dlpCommand = ytDlpPath; const dlpCommand = ytDlpPath;
const downloadingMessage = await ctx.reply(strings.ytDownloading, { const downloadingMessage = await ctx.reply(Strings.ytCheckingSize, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
reply_to_message_id: ctx.message.message_id, reply_to_message_id: ctx.message.message_id,
}); });
if (fs.existsSync(ytDlpPath)) {
try { try {
const approxSizeInMB = await getApproxSize(ytDlpPath, videoUrl); const approxSizeInMB = await Promise.race([
let videoFormat = ""; getApproxSize(ytDlpPath, videoUrl),
timeoutPromise(5000)
]);
if (approxSizeInMB >= 50) { let videoFormat = approxSizeInMB >= 50 ? `-f best` : "-f bestvideo+bestaudio";
videoFormat = `-f best`;
} else { await ctx.telegram.editMessageText(
videoFormat = "-f bestvideo+bestaudio"; ctx.chat.id,
} downloadingMessage.message_id,
null,
Strings.ytDownloading, {
parse_mode: 'Markdown',
reply_to_message_id: ctx.message.message_id,
});
const dlpArgs = [videoUrl, videoFormat, ...cmdArgs.split(' '), mp4File]; const dlpArgs = [videoUrl, videoFormat, ...cmdArgs.split(' '), mp4File];
await downloadFromYoutube(dlpCommand, dlpArgs); await downloadFromYoutube(dlpCommand, dlpArgs);
@ -85,13 +101,13 @@ module.exports = (bot) => {
ctx.chat.id, ctx.chat.id,
downloadingMessage.message_id, downloadingMessage.message_id,
null, null,
strings.ytUploading, { Strings.ytUploading, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
reply_to_message_id: ctx.message.message_id, reply_to_message_id: ctx.message.message_id,
}); });
if (fs.existsSync(mp4File)) { if (fs.existsSync(mp4File)) {
const message = strings.ytUploadDesc const message = Strings.ytUploadDesc
.replace("{userId}", userId) .replace("{userId}", userId)
.replace("{userName}", ctx.from.first_name); .replace("{userName}", ctx.from.first_name);
@ -102,18 +118,20 @@ module.exports = (bot) => {
parse_mode: 'Markdown', parse_mode: 'Markdown',
}); });
if (approxSizeInMB >= 50) {
await ctx.telegram.editMessageText( await ctx.telegram.editMessageText(
ctx.chat.id, ctx.chat.id,
downloadingMessage.message_id, downloadingMessage.message_id,
null, null,
strings.ytUploadLimit2, { Strings.ytUploadLimit2, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
reply_to_message_id: ctx.message.message_id, reply_to_message_id: ctx.message.message_id,
}); });
}
fs.unlinkSync(mp4File); fs.unlinkSync(mp4File);
} catch (error) { } catch (error) {
await ctx.reply(`\`${error}\``, { await ctx.reply(`\`${error.message}\``, {
parse_mode: 'Markdown', parse_mode: 'Markdown',
reply_to_message_id: ctx.message.message_id, reply_to_message_id: ctx.message.message_id,
}); });
@ -123,15 +141,17 @@ module.exports = (bot) => {
} }
} catch (error) { } catch (error) {
fs.unlinkSync(mp4File); fs.unlinkSync(mp4File);
let errStatus = ""; let errStatus;
if (error == "Error: 413: Request Entity Too Large") { if (error.message === "Error: 413: Request Entity Too Large") {
errStatus = Strings.ytUploadLimit; errStatus = Strings.ytUploadLimit;
} else { } else {
errStatus = error.error ? error.error.message : 'Unknown error'; errStatus = error.message === 'Timeout: Check took too long'
? 'The check for video size timed out.'
: error.error ? error.error.message : 'Unknown error';
} }
const message = strings.ytDownloadErr const message = Strings.ytDownloadErr
.replace("{err}", errStatus) .replace("{err}", errStatus)
.replace("{userName}", ctx.from.first_name); .replace("{userName}", ctx.from.first_name);
@ -140,5 +160,15 @@ module.exports = (bot) => {
reply_to_message_id: ctx.message.message_id, reply_to_message_id: ctx.message.message_id,
}); });
} }
} else {
await ctx.telegram.editMessageText(
ctx.chat.id,
downloadingMessage.message_id,
null,
Strings.ytFileErr, {
parse_mode: 'Markdown',
reply_to_message_id: ctx.message.message_id,
});
};
}); });
}; };

View File

@ -61,6 +61,8 @@
"maInvalidModule": "Please provide a valid module ID from The Mod Archive.\nExample: `/modarchive 81574`", "maInvalidModule": "Please provide a valid module ID from The Mod Archive.\nExample: `/modarchive 81574`",
"maDownloadError": "Error downloading the file. Check the module ID and try again.", "maDownloadError": "Error downloading the file. Check the module ID and try again.",
"ytDownloading": "*Downloading video...*", "ytDownloading": "*Downloading video...*",
"ytFileErr": "*It seems that the yt-dlp executable does not exist on our server...\n\nIn that case, the problem is on our end! Please wait until we have noticed and solved the problem.*",
"ytCheckingSize": "*Checking if the video exceeds the 50MB limit...*",
"ytUploading": "*Uploading video...*", "ytUploading": "*Uploading video...*",
"ytUploadDesc": "*[{userName}](tg://user?id={userId}), there is your downloaded video.*", "ytUploadDesc": "*[{userName}](tg://user?id={userId}), there is your downloaded video.*",
"ytDownloadErr": "*Error during YT video download:*\n\n`{err}`", "ytDownloadErr": "*Error during YT video download:*\n\n`{err}`",

View File

@ -61,6 +61,8 @@
"maInvalidModule": "Por favor, forneça um ID de módulo válido do The Mod Archive.\nExemplo: `/modarchive 81574`", "maInvalidModule": "Por favor, forneça um ID de módulo válido do The Mod Archive.\nExemplo: `/modarchive 81574`",
"maDownloadError": "Erro ao baixar o arquivo. Verifique o ID do módulo e tente novamente.", "maDownloadError": "Erro ao baixar o arquivo. Verifique o ID do módulo e tente novamente.",
"ytDownloading": "*Baixando vídeo...*", "ytDownloading": "*Baixando vídeo...*",
"ytCheckingSize": "Verificando se o vídeo excede o limite de 50 MB...",
"ytFileErr": "*Parece que o executável do yt-dlp não existe no nosso servidor...\n\nNesse caso, o problema está no nosso lado! Aguarde até que tenhamos notado e resolvido o problema.*",
"ytUploading": "*Enviando video...*", "ytUploading": "*Enviando video...*",
"ytUploadDesc": "*[{userName}](tg://user?id={userId}), aqui está o seu vídeo baixado.*", "ytUploadDesc": "*[{userName}](tg://user?id={userId}), aqui está o seu vídeo baixado.*",
"ytDownloadErr": "*Erro durante o download do vídeo do YT:*\n\n`{err}`", "ytDownloadErr": "*Erro durante o download do vídeo do YT:*\n\n`{err}`",