text-dataset-tiny-code-script-py-format
/
ysnrfd_messenger
/BACKUP
/backend
/src
/controllers
/uploadController.js
| const fs = require('fs'); | |
| const path = require('path'); | |
| const { v4: uuidv4 } = require('uuid'); | |
| const { validateFile, getFileType } = require('../utils/fileValidation'); | |
| const { formatFileSize } = require('../utils/helpers'); | |
| exports.uploadFile = async (req, res) => { | |
| try { | |
| if (!req.file) { | |
| return res.status(400).json({ error: 'No file provided' }); | |
| } | |
| const file = req.file; | |
| // Validate file | |
| const fileCategory = validateFile(file); | |
| // Generate file metadata | |
| const fileData = { | |
| id: uuidv4(), | |
| originalName: file.originalname, | |
| fileName: file.filename, | |
| fileSize: file.size, | |
| mimeType: file.mimetype, | |
| url: `/uploads/${file.filename}`, | |
| uploaderId: req.user.userId, | |
| uploadedAt: new Date() | |
| }; | |
| // Generate thumbnail for images (simplified - in production use sharp/gm) | |
| if (fileCategory === 'image') { | |
| fileData.thumbnail = `/uploads/${file.filename}`; // Same file for demo | |
| } | |
| res.json({ | |
| message: 'File uploaded successfully', | |
| file: fileData | |
| }); | |
| } catch (error) { | |
| console.error('File upload error:', error); | |
| res.status(400).json({ error: error.message }); | |
| } | |
| }; | |
| exports.getFile = async (req, res) => { | |
| try { | |
| const { filename } = req.params; | |
| const filePath = path.join(__dirname, '../../uploads', filename); | |
| // Check if file exists | |
| if (!fs.existsSync(filePath)) { | |
| return res.status(404).json({ error: 'File not found' }); | |
| } | |
| // Set appropriate headers | |
| const ext = path.extname(filename).toLowerCase(); | |
| const mimeTypes = { | |
| '.jpg': 'image/jpeg', | |
| '.jpeg': 'image/jpeg', | |
| '.png': 'image/png', | |
| '.gif': 'image/gif', | |
| '.webp': 'image/webp', | |
| '.pdf': 'application/pdf', | |
| '.txt': 'text/plain', | |
| '.mp3': 'audio/mpeg', | |
| '.wav': 'audio/wav', | |
| '.ogg': 'audio/ogg' | |
| }; | |
| res.setHeader('Content-Type', mimeTypes[ext] || 'application/octet-stream'); | |
| res.setHeader('Content-Disposition', `inline; filename="${filename}"`); | |
| // Stream file | |
| const fileStream = fs.createReadStream(filePath); | |
| fileStream.pipe(res); | |
| } catch (error) { | |
| console.error('Get file error:', error); | |
| res.status(500).json({ error: 'Server error retrieving file' }); | |
| } | |
| }; | |
| exports.cleanupOrphanedFiles = async (req, res) => { | |
| try { | |
| // This would typically be a cron job | |
| const uploadsDir = path.join(__dirname, '../../uploads'); | |
| const files = fs.readdirSync(uploadsDir); | |
| const orphanedFiles = []; | |
| const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); | |
| for (const file of files) { | |
| const filePath = path.join(uploadsDir, file); | |
| const stats = fs.statSync(filePath); | |
| // Check if file is older than 1 week and not referenced in any message | |
| if (stats.mtime < oneWeekAgo) { | |
| const messageWithFile = await Message.findOne({ 'attachment.fileName': file }); | |
| if (!messageWithFile) { | |
| orphanedFiles.push(file); | |
| fs.unlinkSync(filePath); | |
| } | |
| } | |
| } | |
| res.json({ | |
| message: `Cleaned up ${orphanedFiles.length} orphaned files`, | |
| orphanedFiles | |
| }); | |
| } catch (error) { | |
| console.error('Cleanup error:', error); | |
| res.status(500).json({ error: 'Server error during cleanup' }); | |
| } | |
| }; |