Spaces:
Configuration error
Configuration error
Download src/bot/commands.js from UUUZCX/video-optimizer-bot: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/spaces/UUUZCX/video-optimizer-bot/resolve/main/src/bot/commands.js
- Command line
-
hf download hf://spaces/UUUZCX/video-optimizer-bot/src/bot/commands.js
-
curl -L -o commands.js https://huggingface.co/spaces/UUUZCX/video-optimizer-bot/resolve/main/src/bot/commands.js
15.3 kB
| const os = require("os"); | |
| const { getDb } = require("../config/db"); | |
| const { config } = require("../config/env"); | |
| const { isAdmin } = require("../security/auth"); | |
| const { getModesKeyboard, getCancelKeyboard, adminKeyboard } = require("./keyboards"); | |
| const { getMessages } = require("./messages"); | |
| const { createLogger } = require("../monitoring/logger"); | |
| const systeminfo = require("systeminformation"); | |
| const logger = createLogger("BotCommands"); | |
| function formatSize(bytes) { | |
| if (!bytes || isNaN(bytes) || bytes < 0) return '0 B'; | |
| const units = ['B', 'KB', 'MB', 'GB']; | |
| let i = 0; | |
| let val = parseFloat(bytes); | |
| while (val >= 1024 && i < units.length - 1) { | |
| val /= 1024; | |
| i++; | |
| } | |
| return `${val.toFixed(2)} ${units[i]}`; | |
| } | |
| function getActiveJobForUser(userId) { | |
| const db = getDb(); | |
| return db.prepare(` | |
| SELECT * FROM jobs | |
| WHERE user_id = ? AND status IN ('queued', 'downloading', 'analyzing', 'compressing', 'uploading') | |
| ORDER BY created_at DESC LIMIT 1 | |
| `).get(String(userId)); | |
| } | |
| function getQueuePosition(createdAt) { | |
| const db = getDb(); | |
| const row = db.prepare(` | |
| SELECT COUNT(*) as pos FROM jobs | |
| WHERE status = 'queued' AND created_at < ? | |
| `).get(createdAt); | |
| return (row?.pos || 0) + 1; | |
| } | |
| function registerCommands(bot, queueRef) { | |
| // /start command | |
| bot.command("start", async (ctx) => { | |
| const name = ctx.from?.first_name || "User"; | |
| const mode = ctx.state.user.mode || "auto"; | |
| const msgs = ctx.state.messages; | |
| const welcomeMsg = msgs.welcome | |
| .replace("{name}", name) | |
| .replace("{mode}", mode.toUpperCase()); | |
| await ctx.reply(welcomeMsg, { | |
| parse_mode: "Markdown", | |
| reply_markup: getModesKeyboard(mode, ctx.state.user.language) | |
| }); | |
| }); | |
| // /help command | |
| bot.command("help", async (ctx) => { | |
| await ctx.reply(ctx.state.messages.help, { parse_mode: "Markdown" }); | |
| }); | |
| // /modes command | |
| bot.command("modes", async (ctx) => { | |
| const mode = ctx.state.user.mode || "auto"; | |
| await ctx.reply(ctx.state.messages.modes_title, { | |
| parse_mode: "Markdown", | |
| reply_markup: getModesKeyboard(mode, ctx.state.user.language) | |
| }); | |
| }); | |
| // /status command | |
| bot.command("status", async (ctx) => { | |
| const userId = ctx.from?.id; | |
| const msgs = ctx.state.messages; | |
| const activeJob = getActiveJobForUser(userId); | |
| if (!activeJob) { | |
| return ctx.reply(msgs.no_active_task, { parse_mode: "Markdown" }); | |
| } | |
| const modeUpper = activeJob.mode.toUpperCase(); | |
| let statusText = ""; | |
| if (activeJob.status === "queued") { | |
| const pos = getQueuePosition(activeJob.created_at); | |
| statusText = msgs.queued.replace("{position}", pos).replace("{mode}", modeUpper); | |
| } else if (activeJob.status === "downloading") { | |
| statusText = msgs.downloading; | |
| } else if (activeJob.status === "compressing") { | |
| statusText = msgs.compressing | |
| .replace("{mode}", modeUpper) | |
| .replace("{progress}", String(Math.round(activeJob.progress || 0))); | |
| } else if (activeJob.status === "uploading") { | |
| statusText = msgs.uploading; | |
| } else { | |
| statusText = `⚙️ *Status:* ${activeJob.status.toUpperCase()}\n📊 *Progress:* ${Math.round(activeJob.progress)}%`; | |
| } | |
| await ctx.reply(statusText, { | |
| parse_mode: "Markdown", | |
| reply_markup: getCancelKeyboard(activeJob.id, ctx.state.user.language) | |
| }); | |
| }); | |
| // /queue command | |
| bot.command("queue", async (ctx) => { | |
| const userId = ctx.from?.id; | |
| const isAr = ctx.state.user.language === "ar"; | |
| const db = getDb(); | |
| const activeJobs = db.prepare(` | |
| SELECT id, user_id, status, progress, mode, created_at FROM jobs | |
| WHERE status IN ('queued', 'downloading', 'analyzing', 'compressing', 'uploading') | |
| ORDER BY created_at ASC | |
| `).all(); | |
| if (activeJobs.length === 0) { | |
| return ctx.reply( | |
| isAr | |
| ? "📭 لا توجد أي عمليات ضغط في الطابور حالياً. البوت جاهز تماماً!" | |
| : "📭 No compression jobs in the queue. The bot is fully idle!" | |
| ); | |
| } | |
| let queueMsg = isAr ? "📊 *طابور العمليات الحالي:*\n\n" : "📊 *Current Job Queue:*\n\n"; | |
| activeJobs.forEach((job, index) => { | |
| const isMine = String(job.user_id) === String(userId); | |
| const prefix = isMine ? "⭐️ " : "▪️ "; | |
| const statusIcon = job.status === "queued" ? "⏳" : job.status === "compressing" ? "⚡" : "📥"; | |
| queueMsg += `${prefix}*#${index + 1}* ${statusIcon} [${job.status.toUpperCase()}] \n`; | |
| queueMsg += ` • ${isAr ? "الوضع:" : "Profile:"} \`${job.mode.toUpperCase()}\``; | |
| if (job.status === "compressing") { | |
| queueMsg += ` | ${isAr ? "التقدم:" : "Progress:"} \`${Math.round(job.progress)}%\``; | |
| } | |
| queueMsg += "\n\n"; | |
| }); | |
| await ctx.reply(queueMsg, { parse_mode: "Markdown" }); | |
| }); | |
| // /cancel command | |
| bot.command("cancel", async (ctx) => { | |
| const userId = ctx.from?.id; | |
| const msgs = ctx.state.messages; | |
| const activeJob = getActiveJobForUser(userId); | |
| if (!activeJob) { | |
| return ctx.reply(msgs.no_active_task, { parse_mode: "Markdown" }); | |
| } | |
| const db = getDb(); | |
| const now = new Date().toISOString(); | |
| db.prepare(` | |
| UPDATE jobs | |
| SET status = 'failed', error = 'Cancelled by user', updated_at = ?, finished_at = ? | |
| WHERE id = ? | |
| `).run(now, now, activeJob.id); | |
| logger.info(`Job ${activeJob.id} cancelled by user ${userId}`); | |
| await ctx.reply(msgs.cancelled, { parse_mode: "Markdown" }); | |
| }); | |
| // /stats command | |
| bot.command("stats", async (ctx) => { | |
| const userId = ctx.from?.id; | |
| const isAr = ctx.state.user.language === "ar"; | |
| const db = getDb(); | |
| // User statistics | |
| const userJobs = db.prepare(` | |
| SELECT | |
| COUNT(*) as total, | |
| SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as success, | |
| SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed | |
| FROM jobs WHERE user_id = ? | |
| `).get(String(userId)); | |
| // Space saved | |
| const userSavedRow = db.prepare(` | |
| SELECT SUM(size_before - size_after) as saved | |
| FROM cache | |
| WHERE input_hash IN (SELECT checksum FROM jobs WHERE user_id = ? AND status = 'completed') | |
| `).get(String(userId)); | |
| const total = userJobs?.total || 0; | |
| const success = userJobs?.success || 0; | |
| const failed = userJobs?.failed || 0; | |
| const savedBytes = userSavedRow?.saved || 0; | |
| let statsMsg = isAr | |
| ? `📊 *إحصائيات الاستخدام الخاصة بك:*\n\n` | |
| : `📊 *Your Usage Statistics:*\n\n`; | |
| statsMsg += isAr | |
| ? `• *إجمالي العمليات المرسلة:* ${total}\n` | |
| : `• *Total Jobs Submitted:* ${total}\n`; | |
| statsMsg += isAr | |
| ? `• *العمليات الناجحة:* ${success} ✅\n` | |
| : `• *Successful Conversions:* ${success} ✅\n`; | |
| statsMsg += isAr | |
| ? `• *العمليات الفاشلة:* ${failed} ❌\n` | |
| : `• *Failed Conversions:* ${failed} ❌\n`; | |
| statsMsg += isAr | |
| ? `• *إجمالي مساحة التخزين الموفرة:* \`${formatSize(savedBytes)}\` 💾\n\n` | |
| : `• *Total Internet Data Saved:* \`${formatSize(savedBytes)}\` 💾\n\n`; | |
| statsMsg += isAr | |
| ? `🚀 شكراً لاستخدامك خدمتنا لتحسين الفيديوهات!` | |
| : `🚀 Thank you for choosing our video compression bot!`; | |
| await ctx.reply(statsMsg, { parse_mode: "Markdown" }); | |
| }); | |
| // /admin control command | |
| bot.command("admin", async (ctx) => { | |
| if (!isAdmin(ctx.from?.id)) { | |
| return ctx.reply(ctx.state.messages.unauthorized); | |
| } | |
| await ctx.reply(ctx.state.messages.admin_panel, { | |
| parse_mode: "Markdown", | |
| reply_markup: adminKeyboard(ctx.state.user.language) | |
| }); | |
| }); | |
| // /sysinfo admin command | |
| bot.command("sysinfo", async (ctx) => { | |
| if (!isAdmin(ctx.from?.id)) return; | |
| await ctx.reply("⏳ Collecting system metrics..."); | |
| try { | |
| const cpu = await systeminfo.cpu(); | |
| const mem = await systeminfo.mem(); | |
| const currentLoad = await systeminfo.currentLoad(); | |
| const fsSize = await systeminfo.fsSize(); | |
| const cpuBrand = `${cpu.manufacturer} ${cpu.brand}`; | |
| const cpuUsage = `${currentLoad.currentLoad.toFixed(1)}%`; | |
| const ramTotal = formatSize(mem.total); | |
| const ramUsed = formatSize(mem.active); | |
| const ramPercent = ((mem.active / mem.total) * 100).toFixed(1); | |
| let diskInfo = "N/A"; | |
| if (fsSize && fsSize.length > 0) { | |
| const rootFs = fsSize[0]; | |
| diskInfo = `${formatSize(rootFs.used)} / ${formatSize(rootFs.size)} (${rootFs.use.toFixed(1)}%)`; | |
| } | |
| const rawUptime = os.uptime(); | |
| const hours = Math.floor(rawUptime / 3600); | |
| const minutes = Math.floor((rawUptime % 3600) / 60); | |
| const uptimeStr = `${hours}h ${minutes}m`; | |
| const sysInfoText = ctx.state.messages.sysinfo | |
| .replace("{os}", `${os.type()} ${os.arch()}`) | |
| .replace("{cpu}", `${cpuBrand} (${cpuUsage} Usage)`) | |
| .replace("{ram}", `${ramUsed} / ${ramTotal} (${ramPercent}%)`) | |
| .replace("{disk}", diskInfo) | |
| .replace("{uptime}", uptimeStr) | |
| .replace("{nodeVersion}", process.version) | |
| .replace("{ffmpegVersion}", "Detected locally"); | |
| await ctx.reply(sysInfoText, { parse_mode: "Markdown" }); | |
| } catch (e) { | |
| await ctx.reply(`❌ Failed to fetch system info: ${e.message}`); | |
| } | |
| }); | |
| // Inline callback query router for Mode setting | |
| bot.callbackQuery(/^setmode:(.+)$/, async (ctx) => { | |
| const requestedMode = ctx.match[1]; | |
| const userId = ctx.from.id; | |
| const db = getDb(); | |
| db.prepare("UPDATE users SET mode = ? WHERE id = ?").run(requestedMode, userId); | |
| await ctx.answerCallbackQuery(); | |
| const isAr = ctx.state.user.language === "ar"; | |
| await ctx.editMessageText( | |
| ctx.state.messages.mode_changed.replace("{mode}", requestedMode.toUpperCase()), | |
| { | |
| parse_mode: "Markdown", | |
| reply_markup: getModesKeyboard(requestedMode, ctx.state.user.language) | |
| } | |
| ); | |
| }); | |
| // Inline callback query router for Language switching | |
| bot.callbackQuery(/^setlang:(.+)$/, async (ctx) => { | |
| const requestedLang = ctx.match[1]; | |
| const userId = ctx.from.id; | |
| const db = getDb(); | |
| db.prepare("UPDATE users SET language = ? WHERE id = ?").run(requestedLang, userId); | |
| await ctx.answerCallbackQuery(); | |
| // Reload messages and user data | |
| ctx.state.user.language = requestedLang; | |
| ctx.state.messages = getMessages(requestedLang); | |
| const mode = ctx.state.user.mode || "auto"; | |
| const name = ctx.from?.first_name || "User"; | |
| const welcomeMsg = ctx.state.messages.welcome | |
| .replace("{name}", name) | |
| .replace("{mode}", mode.toUpperCase()); | |
| await ctx.editMessageText(welcomeMsg, { | |
| parse_mode: "Markdown", | |
| reply_markup: getModesKeyboard(mode, requestedLang) | |
| }); | |
| }); | |
| // Inline callback query router for cancelling | |
| bot.callbackQuery(/^cancel:(.+)$/, async (ctx) => { | |
| const jobId = ctx.match[1]; | |
| const db = getDb(); | |
| const msgs = ctx.state.messages; | |
| const job = db.prepare("SELECT * FROM jobs WHERE id = ?").get(jobId); | |
| if (!job) { | |
| await ctx.answerCallbackQuery({ text: "Job not found!", show_alert: true }); | |
| return; | |
| } | |
| const now = new Date().toISOString(); | |
| db.prepare(` | |
| UPDATE jobs | |
| SET status = 'failed', error = 'Cancelled by user', updated_at = ?, finished_at = ? | |
| WHERE id = ? | |
| `).run(now, now, jobId); | |
| await ctx.answerCallbackQuery({ text: msgs.cancelled.replace(/\*|\_/g, "") }); | |
| await ctx.editMessageText(msgs.cancelled, { parse_mode: "Markdown" }); | |
| }); | |
| // Inline callback query router for Admin functions | |
| bot.callbackQuery(/^admin:(.+)$/, async (ctx) => { | |
| if (!isAdmin(ctx.from.id)) { | |
| await ctx.answerCallbackQuery({ text: "Unauthorized admin request!", show_alert: true }); | |
| return; | |
| } | |
| const action = ctx.match[1]; | |
| const db = getDb(); | |
| const isAr = ctx.state.user.language === "ar"; | |
| if (action === "pause") { | |
| queueRef.pause(); | |
| await ctx.answerCallbackQuery({ text: isAr ? "⏸️ تم إيقاف الطابور مؤقتاً" : "⏸️ Queue Paused" }); | |
| } else if (action === "resume") { | |
| queueRef.resume(); | |
| await ctx.answerCallbackQuery({ text: isAr ? "▶️ تم استئناف تشغيل الطابور" : "▶️ Queue Resumed" }); | |
| } else if (action === "clean-temp") { | |
| const { runCleanup } = require("../cache/cleanup"); | |
| runCleanup().catch(() => {}); | |
| await ctx.answerCallbackQuery({ text: isAr ? "🗑️ جاري مسح الملفات المؤقتة والكاش" : "🗑️ Triggered Cleanups" }); | |
| } else if (action === "health") { | |
| const { checkBinary } = require("../utils/process.utils"); | |
| const hasFfmpeg = await checkBinary("ffmpeg"); | |
| const hasFfprobe = await checkBinary("ffprobe"); | |
| const hasYtdlp = await checkBinary("yt-dlp"); | |
| const healthStr = [ | |
| "⚙️ *System Health Status:*", | |
| `• FFmpeg: ${hasFfmpeg ? "✅ Active" : "❌ Dead"}`, | |
| `• FFprobe: ${hasFfprobe ? "✅ Active" : "❌ Dead"}`, | |
| `• yt-dlp: ${hasYtdlp ? "✅ Active" : "❌ Dead"}` | |
| ].join("\n"); | |
| await ctx.answerCallbackQuery(); | |
| await ctx.reply(healthStr, { parse_mode: "Markdown" }); | |
| return; | |
| } else if (action === "queue") { | |
| const activeJobs = db.prepare(` | |
| SELECT id, status, progress FROM jobs | |
| WHERE status IN ('queued', 'downloading', 'analyzing', 'compressing', 'uploading') | |
| ORDER BY created_at ASC | |
| `).all(); | |
| let queueMsg = isAr ? "📊 *قائمة العمليات الجارية:*\n\n" : "📊 *Current Operations Active:*\n\n"; | |
| if (activeJobs.length === 0) { | |
| queueMsg += isAr ? "📭 الطابور فارغ حالياً." : "📭 No active items."; | |
| } else { | |
| activeJobs.forEach((j, index) => { | |
| queueMsg += `*#${index + 1}* ${j.id.slice(0, 8)} | ${j.status.toUpperCase()} (${Math.round(j.progress)}%)\n`; | |
| }); | |
| } | |
| await ctx.answerCallbackQuery(); | |
| await ctx.reply(queueMsg, { parse_mode: "Markdown" }); | |
| return; | |
| } else if (action === "status") { | |
| // Gather active metrics | |
| const activeCount = db.prepare("SELECT COUNT(*) as c FROM jobs WHERE status IN ('downloading', 'analyzing', 'compressing', 'uploading')").get().c; | |
| const queuedCount = db.prepare("SELECT COUNT(*) as c FROM jobs WHERE status = 'queued'").get().c; | |
| const statusStr = [ | |
| "📊 *System Queue Status:*", | |
| `• Active Processing: *${activeCount}*`, | |
| `• Queued in Waiting: *${queuedCount}*` | |
| ].join("\n"); | |
| await ctx.answerCallbackQuery(); | |
| await ctx.reply(statusStr, { parse_mode: "Markdown" }); | |
| return; | |
| } | |
| await ctx.editMessageText( | |
| ctx.state.messages.admin_panel + `\n\n⚡ *Completed Action:* ${action.toUpperCase()}`, | |
| { | |
| parse_mode: "Markdown", | |
| reply_markup: adminKeyboard(ctx.state.user.language) | |
| } | |
| ); | |
| }); | |
| } | |
| module.exports = { registerCommands }; | |