File size: 1,265 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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");

async function downloadTelegramFile(ctx, fileId, jobId, originalName = "telegram-video.mp4", onProgress = () => {}) {
  const file = await ctx.api.getFile(fileId);
  const url = `https://api.telegram.org/file/bot${config.telegram.token}/${file.file_path}`;
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Telegram file download failed: ${response.status}`);
  await fsp.mkdir(paths.downloads, { recursive: true });
  const ext = path.extname(originalName) || path.extname(file.file_path) || ".mp4";
  const output = path.join(paths.downloads, `${jobId}${ext}`);
  const total = Number(response.headers.get("content-length") || file.file_size || 0);
  let done = 0;
  const writer = fs.createWriteStream(output);
  for await (const chunk of response.body) {
    done += chunk.length;
    writer.write(chunk);
    if (total) onProgress(Math.round(done / total * 100));
  }
  await new Promise((resolve, reject) => {
    writer.end(resolve);
    writer.on("error", reject);
  });
  return output;
}

module.exports = { downloadTelegramFile };