const fs = require("node:fs"); const fsp = require("node:fs/promises"); const path = require("node:path"); const { paths } = require("../config/paths"); const { config } = require("../config/env"); const { updateJob, event } = require("./jobs"); const { downloadVideo } = require("../downloader/ytdlp"); const { validateFileSize } = require("../security/validation"); const { sha256File } = require("../security/checksum"); const { getCached, saveCache, cachePathFor } = require("../cache/cache"); const { probe, verifyMedia } = require("../ffmpeg/ffprobe"); const { buildPlan } = require("../ffmpeg/planner"); const { splitIfNeeded } = require("../ffmpeg/splitter"); const { compressVideo } = require("../ffmpeg/ffmpeg"); const { logger } = require("../monitoring/logger"); const { analyzeQuality } = require("../ffmpeg/quality.analyzer"); async function processJob(job, botApi, progress) { const startedAt = new Date().toISOString(); updateJob(job.id, { status: "downloading", stage: "starting", attempts: job.attempts + 1, startedAt }); event(job.id, "info", "Job started"); let inputPath = job.inputPath; if (job.type === "link") { progress(job, 5, "downloading", "Downloading video link"); inputPath = await downloadVideo(job.sourceUrl, job.id, (p) => { progress(job, Math.min(35, Math.round((p.percent || 0) * 0.3)), "downloading", `Downloading ${p.percent?.toFixed(1) || 0}%`); }); updateJob(job.id, { inputPath }); } progress(job, 38, "validating", "Checking file integrity"); validateFileSize(inputPath); await verifyMedia(inputPath); const inputHash = await sha256File(inputPath); updateJob(job.id, { checksum: inputHash }); const cached = getCached(inputHash, job.mode); if (cached) { progress(job, 85, "uploading", "Cached optimized video found"); await sendOutputs(botApi, job, cached.outputPaths); updateJob(job.id, { status: "completed", stage: "cache-hit", progress: 100, outputPaths: cached.outputPaths, finishedAt: new Date().toISOString() }); return; } progress(job, 42, "probing", "Reading video technical details"); const info = await probe(inputPath); if (info.duration > config.limits.maxVideoDurationMinutes * 60) { throw new Error(`Video is longer than the configured limit of ${config.limits.maxVideoDurationMinutes} minutes.`); } progress(job, 47, "planning", "Choosing best compression settings"); const plan = await buildPlan(info, job.mode); const workDir = path.join(paths.output, job.id); await fsp.mkdir(workDir, { recursive: true }); progress(job, 50, "splitting", "Splitting long video when needed"); const segments = await splitIfNeeded(inputPath, workDir, info, plan); const outputs = []; const width = String(segments.length).length; for (const segment of segments) { const name = `optimized_part_${String(segment.index).padStart(width, "0")}_of_${String(segments.length).padStart(width, "0")}.mp4`; const output = cachePathFor(inputHash, `${plan.mode}_${name}`); const segmentInfo = segment.path === inputPath ? info : await probe(segment.path); const compResult = compressVideo({ inputPath: segment.path, outputPath: output, presetId: plan.mode, codec: config.video.preferredEncoder || "h264", keepAudio: true, onProgress: (pObj) => { const ffPercent = pObj.percentage; const segmentBase = 55 + ((segment.index - 1) / segments.length) * 30; const segmentShare = ffPercent / 100 * (30 / segments.length); let statsSuffix = ``; if (pObj.speed) { statsSuffix = ` | ${ffPercent}% | FPS: ${pObj.currentFps} | Speed: ${pObj.speed}x | ETA: ${pObj.etaSeconds}s`; } progress(job, Math.round(segmentBase + segmentShare), "compressing", `Compressing part ${segment.index}/${segments.length}${statsSuffix}`); }, info: segmentInfo }); await compResult.promise; outputs.push(output); } const sizeBefore = fs.statSync(inputPath).size; const sizeAfter = outputs.reduce((sum, file) => sum + fs.statSync(file).size, 0); const qualityMetrics = outputs[0] ? await analyzeQuality(inputPath, outputs[0]).catch(() => null) : null; const firstSsim = qualityMetrics ? qualityMetrics.ssim : null; progress(job, 88, "uploading", "Uploading optimized video"); const fileId = await sendOutputs(botApi, job, outputs); saveCache({ inputHash, mode: job.mode, fileId, outputPaths: outputs, sizeBefore, sizeAfter, duration: info.duration || 0, platform: job.type === "link" ? "url" : "telegram", metadata: { info, plan, ssim: firstSsim } }); updateJob(job.id, { status: "completed", stage: "completed", progress: 100, outputPaths: outputs, finishedAt: new Date().toISOString(), metadata: { info, plan, ssim: firstSsim, sizeBefore, sizeAfter } }); event(job.id, "info", "Job completed", { outputs }); } async function sendOutputs(botApi, job, outputs) { let fileId = null; for (const file of outputs) { const res = await botApi.sendVideo(job.chatId, { source: file }, { caption: `🎥 Optimized video (${path.basename(file)})` }).catch(async (err) => { logger.debug(`sendVideo failed, falling back to sendDocument: ${err.message}`); return await botApi.sendDocument(job.chatId, { source: file }, { caption: `📄 Optimized video file (${path.basename(file)})` }); }); if (res && res.video) { fileId = res.video.file_id; } else if (res && res.document) { fileId = res.document.file_id; } } return fileId; } module.exports = { processJob };