Spaces:
Sleeping
Sleeping
File size: 7,408 Bytes
0b355ec adf44f1 0b355ec adf44f1 0b355ec | 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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | 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(); |