const fs = require('fs'); const path = require('path'); const { InputFile } = require('grammy'); const { createLogger } = require('../monitoring/logger'); const { throttleStream } = require('./throttle'); const { saveUploadState, clearUploadState } = require('./resume'); const { measureUploadSpeed } = require('./speed.detector'); const log = createLogger('Uploader'); /** * Perform a dynamic file upload to Telegram with progress callbacks and speed throttling * @param {import('grammy').Bot} bot Bot instance * @param {number} chatId * @param {string} filePath * @param {object} options * @param {function} onProgress Callback for upload percentage updates * @returns {Promise} */ async function uploadVideoFile(bot, chatId, filePath, options = {}, onProgress = null) { const { title, duration, width, height, thumbnailPath, throttleSpeedMbps } = options; const fileName = options.fileName || path.basename(filePath); log.info(`Initializing video upload: ${filePath} to Chat ID: ${chatId}`); // 1. Measure internet upload speeds if throttling is enabled let speedMbps = throttleSpeedMbps; if (speedMbps === 'auto') { speedMbps = await measureUploadSpeed(); log.info(`Auto-detected network speed: ${speedMbps.toFixed(2)} Mbps`); } // 2. Prepare read stream (either throttled or raw stream) let fileStream = fs.createReadStream(filePath); if (speedMbps && speedMbps > 0) { log.info(`Enabling upload throttle: limit = ${speedMbps} Mbps`); fileStream = throttleStream(fileStream, speedMbps); } // 3. Keep track of transfer progress manually let bytesUploaded = 0; const totalBytes = fs.statSync(filePath).size; const startTime = Date.now(); fileStream.on('data', (chunk) => { bytesUploaded += chunk.length; const progress = Math.min(100, Math.floor((bytesUploaded / totalBytes) * 100)); if (onProgress) { onProgress({ progress, uploadedBytes: bytesUploaded, totalBytes, elapsedTimeMs: Date.now() - startTime }); } }); try { const fileHash = `${totalBytes}_${chatId}`; saveUploadState(fileHash, { bytesUploaded, totalBytes }); // Build the grammY InputFile from the stream const inputFile = new InputFile(fileStream, fileName); const sendOptions = { caption: options.caption || '', supports_streaming: true }; if (duration) sendOptions.duration = Math.round(duration); if (width) sendOptions.width = width; if (height) sendOptions.height = height; if (thumbnailPath && fs.existsSync(thumbnailPath)) { sendOptions.thumbnail = new InputFile(thumbnailPath); } log.info('Sending video file payload via Telegram Bot API...'); const message = await bot.api.sendVideo(chatId, inputFile, sendOptions); clearUploadState(fileHash); log.info('Video uploaded successfully.'); return message; } catch (err) { log.error('Failed to upload video to Telegram:', err); throw err; } } module.exports = { uploadVideoFile };