const fs = require('fs'); const path = require('path'); const pdfParse = require('pdf-parse'); const mammoth = require('mammoth'); const multer = require('multer'); const logger = require('../utils/logger'); class FileService { constructor() { this.allowedMimeTypes = [ 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx 'application/msword', // .doc 'text/plain', 'text/rtf' ]; this.maxFileSize = 10 * 1024 * 1024; // 10MB this.uploadPath = path.join(__dirname, '../../uploads'); // Ensure upload directory exists this.ensureUploadDir(); } ensureUploadDir() { try { if (!fs.existsSync(this.uploadPath)) { fs.mkdirSync(this.uploadPath, { recursive: true }); logger.info('Created upload directory', { path: this.uploadPath }); } } catch (error) { logger.warn('Cannot create upload directory, using temp directory', { originalPath: this.uploadPath, error: error.message }); // Fallback to OS temp directory this.uploadPath = path.join(require('os').tmpdir(), 'edichat-uploads'); try { if (!fs.existsSync(this.uploadPath)) { fs.mkdirSync(this.uploadPath, { recursive: true }); } logger.info('Using fallback upload directory', { path: this.uploadPath }); } catch (fallbackError) { logger.error('Cannot create any upload directory', { error: fallbackError.message }); // Disable file uploads if we can't create any directory this.uploadPath = null; } } } // Configure multer for file uploads getMulterConfig() { // If no upload directory is available, return disabled config if (!this.uploadPath) { return multer({ limits: { fileSize: 0 }, // Disable uploads fileFilter: (req, file, cb) => { cb(new Error('File uploads are disabled due to filesystem restrictions'), false); } }); } const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, this.uploadPath); }, filename: (req, file, cb) => { // Generate unique filename const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); const extension = path.extname(file.originalname); cb(null, `${file.fieldname}-${uniqueSuffix}${extension}`); } }); const fileFilter = (req, file, cb) => { if (this.allowedMimeTypes.includes(file.mimetype)) { cb(null, true); } else { cb(new Error(`File type ${file.mimetype} not allowed. Supported types: PDF, DOCX, DOC, TXT, RTF`), false); } }; return multer({ storage, limits: { fileSize: this.maxFileSize }, fileFilter }); } // Extract text from different file types async extractText(filePath, mimeType) { try { switch (mimeType) { case 'application/pdf': return await this.extractFromPDF(filePath); case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': case 'application/msword': return await this.extractFromWord(filePath); case 'text/plain': case 'text/rtf': return await this.extractFromText(filePath); default: throw new Error(`Unsupported file type: ${mimeType}`); } } catch (error) { logger.error('Text extraction failed', { filePath, mimeType, error: error.message }); throw error; } } async extractFromPDF(filePath) { try { const dataBuffer = fs.readFileSync(filePath); const data = await pdfParse(dataBuffer); return { text: data.text, pages: data.numpages, metadata: data.info || {} }; } catch (error) { throw new Error(`PDF extraction failed: ${error.message}`); } } async extractFromWord(filePath) { try { const result = await mammoth.extractRawText({ path: filePath }); return { text: result.value, pages: null, // Word docs don't have page concept metadata: {}, warnings: result.messages || [] }; } catch (error) { throw new Error(`Word document extraction failed: ${error.message}`); } } async extractFromText(filePath) { try { const text = fs.readFileSync(filePath, 'utf8'); return { text, pages: null, metadata: {} }; } catch (error) { throw new Error(`Text file extraction failed: ${error.message}`); } } // Clean up uploaded file async deleteFile(filePath) { try { if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); logger.info('File deleted', { filePath }); return true; } return false; } catch (error) { logger.error('File deletion failed', { filePath, error: error.message }); throw error; } } // Get file info getFileInfo(filePath) { try { const stats = fs.statSync(filePath); return { size: stats.size, created: stats.birthtime, modified: stats.mtime, exists: true }; } catch (error) { return { exists: false, error: error.message }; } } // Validate file before processing validateFile(file) { const errors = []; if (!file) { errors.push('No file provided'); return { isValid: false, errors }; } if (!this.allowedMimeTypes.includes(file.mimetype)) { errors.push(`File type ${file.mimetype} not supported`); } if (file.size > this.maxFileSize) { errors.push(`File size ${file.size} exceeds maximum ${this.maxFileSize} bytes`); } // Check for suspicious filenames const filename = file.originalname.toLowerCase(); const suspiciousExtensions = ['.exe', '.bat', '.cmd', '.scr', '.js', '.vbs']; if (suspiciousExtensions.some(ext => filename.endsWith(ext))) { errors.push('File type not allowed for security reasons'); } return { isValid: errors.length === 0, errors }; } // Generate safe filename generateSafeFilename(originalName) { const extension = path.extname(originalName); const baseName = path.basename(originalName, extension); // Remove special characters and spaces const safeName = baseName .replace(/[^a-zA-Z0-9\-_]/g, '_') .replace(/_{2,}/g, '_') .replace(/^_+|_+$/g, ''); const timestamp = Date.now(); return `${safeName}_${timestamp}${extension}`; } // Get upload statistics getUploadStats() { try { const files = fs.readdirSync(this.uploadPath); let totalSize = 0; files.forEach(file => { const filePath = path.join(this.uploadPath, file); const stats = fs.statSync(filePath); totalSize += stats.size; }); return { fileCount: files.length, totalSizeBytes: totalSize, totalSizeMB: Math.round(totalSize / (1024 * 1024) * 100) / 100, uploadPath: this.uploadPath }; } catch (error) { logger.error('Failed to get upload stats', { error: error.message }); return { fileCount: 0, totalSizeBytes: 0, totalSizeMB: 0, error: error.message }; } } } module.exports = new FileService();