import * as fs from 'fs'; import * as path from 'path'; import * as https from 'https'; import * as http from 'http'; export class FileDownloader { private tempDir: string; constructor() { // Use a temp directory that's accessible across different environments this.tempDir = path.join(process.cwd(), 'temp-downloads'); this.ensureTempDirExists(); } private ensureTempDirExists(): void { if (!fs.existsSync(this.tempDir)) { fs.mkdirSync(this.tempDir, { recursive: true }); } } async downloadFile(url: string, filename: string): Promise { return new Promise((resolve, reject) => { const filePath = path.join(this.tempDir, filename); // Clean up existing file if it exists if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); } const file = fs.createWriteStream(filePath); const client = url.startsWith('https') ? https : http; const request = client.get(url, (response) => { if (response.statusCode === 200) { response.pipe(file); file.on('finish', () => { file.close(); resolve(filePath); }); } else { file.close(); fs.unlink(filePath, () => {}); reject(new Error(`Failed to download file: ${response.statusCode} ${response.statusMessage}`)); } }); request.on('error', (err) => { file.close(); fs.unlink(filePath, () => {}); reject(err); }); }); } async cleanupFile(filePath: string): Promise { return new Promise((resolve, reject) => { if (fs.existsSync(filePath)) { fs.unlink(filePath, (err) => { if (err) { reject(err); } else { resolve(); } }); } else { resolve(); } }); } getTempDir(): string { return this.tempDir; } }