const fs = require('fs').promises; const fsSync = require('fs'); const pth = require('path'); const { closeButton } = require('../utility/close'); const dataDir = pth.join(__dirname, '../../../data/'); const PAGE_SIZE = 5; /** * Raccoglie ricorsivamente tutti i file nella cartella data/ */ async function listDataFiles() { const results = []; async function scan(dir, prefix) { const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = pth.join(dir, entry.name); if (entry.isDirectory()) { await scan(fullPath, prefix ? `${prefix}/${entry.name}` : entry.name); } else { const stat = await fs.stat(fullPath); results.push({ name: prefix ? `${prefix}/${entry.name}` : entry.name, path: fullPath, size: stat.size, modified: stat.mtime, lines: null // calcolato on-demand }); } } } try { await scan(dataDir, ''); } catch (e) { console.error('[BACKUP] Errore scan:', e.message); } return results.sort((a, b) => b.modified - a.modified); } function formatSize(bytes) { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(2)} MB`; } function buildPage(files, page, userMessageId) { const totalPages = Math.ceil(files.length / PAGE_SIZE); const start = page * PAGE_SIZE; const pageFiles = files.slice(start, start + PAGE_SIZE); const keyboard = pageFiles.map(f => { const date = new Date(f.modified).toLocaleDateString('it-IT', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }); const label = `${f.name} (${formatSize(f.size)}, ${date})`; // Encode file name as base64-safe identifier (index in full list) const fileIdx = files.indexOf(f); return [{ text: label, callback_data: `bkfile:${fileIdx}:${userMessageId}` }]; }); // Navigation row const navRow = []; if (page > 0) { navRow.push({ text: '<< Prec', callback_data: `bkpage:${page - 1}:${userMessageId}` }); } navRow.push({ text: `${page + 1}/${totalPages}`, callback_data: `bknoop:0` }); if (page < totalPages - 1) { navRow.push({ text: 'Succ >>', callback_data: `bkpage:${page + 1}:${userMessageId}` }); } keyboard.push(navRow); // Close button keyboard.push([{ text: '<- Chiudi', callback_data: `close:${userMessageId}` }]); return keyboard; } module.exports = { command: 'backup', handler: async (bot, msg) => { const chatId = msg.chat.id; const files = await listDataFiles(); if (files.length === 0) { bot.sendMessage(chatId, 'Nessun file nella cartella data.', { reply_to_message_id: msg.message_id, reply_markup: closeButton(msg.message_id) }); return; } const text = `*Backup & Logs*\n\n${files.length} file disponibili nella cartella data.\n_Seleziona un file per info e download._`; const keyboard = buildPage(files, 0, msg.message_id); bot.sendMessage(chatId, text, { parse_mode: 'Markdown', reply_to_message_id: msg.message_id, reply_markup: { inline_keyboard: keyboard } }); }, // Export utilities for callbacks listDataFiles, formatSize, buildPage, PAGE_SIZE };