const fs = require('fs'); const fsPromises = require('fs').promises; const readline = require('readline'); const { listDataFiles, formatSize, buildPage } = require('../commands/backuplogs'); /** * Conta le righe di un file in modo efficiente (stream) */ function countLines(filePath) { return new Promise((resolve) => { let count = 0; const stream = fs.createReadStream(filePath); const rl = readline.createInterface({ input: stream, crlfDelay: Infinity }); rl.on('line', () => count++); rl.on('close', () => resolve(count)); rl.on('error', () => resolve(-1)); }); } module.exports = { prefix: 'bkfile:', handler: async (bot, query) => { const chatId = query.message.chat.id; const botMessageId = query.message.message_id; const parts = query.data.split(':'); const fileIdx = parseInt(parts[1]); const userMessageId = parts[2]; const files = await listDataFiles(); const file = files[fileIdx]; if (!file || !fs.existsSync(file.path)) { bot.answerCallbackQuery(query.id, { text: 'File non trovato', show_alert: true }); return; } // Conta righe let lineCount = '—'; try { const ext = file.name.split('.').pop().toLowerCase(); if (['csv', 'txt', 'log', 'json'].includes(ext)) { lineCount = await countLines(file.path); } } catch (e) {} const modified = new Date(file.modified).toLocaleDateString('it-IT', { day: '2-digit', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' }); const text = `*File:* \`${file.name}\`\n\n` + `*Dimensione:* ${formatSize(file.size)}\n` + `*Ultima modifica:* ${modified}\n` + `*Righe:* ${lineCount}\n`; const keyboard = [ [{ text: 'Scarica file', callback_data: `bkdl:${fileIdx}:${userMessageId}` }], [{ text: '<- Torna alla lista', callback_data: `bkback:0:${userMessageId}` }] ]; try { await bot.editMessageText(text, { chat_id: chatId, message_id: botMessageId, parse_mode: 'Markdown', reply_markup: { inline_keyboard: keyboard } }); } catch (e) {} bot.answerCallbackQuery(query.id); } };