Spaces:
Sleeping
Sleeping
Download backend/src/controllers/documentController.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/controllers/documentController.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/controllers/documentController.js
-
curl -L -o documentController.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/controllers/documentController.js
13.4 kB
| const { validationResult } = require('express-validator'); | |
| const mongoose = require('mongoose'); | |
| const Document = require('../models/Document'); | |
| const fileService = require('../services/fileService'); | |
| const dueDateExtractionService = require('../services/dueDateExtractionService'); | |
| const calendarExportService = require('../services/calendarExportService'); | |
| const logger = require('../utils/logger'); | |
| const path = require('path'); | |
| class DocumentController { | |
| async uploadDocument(req, res) { | |
| try { | |
| const errors = validationResult(req); | |
| if (!errors.isEmpty()) { | |
| return res.status(400).json({ | |
| success: false, | |
| errors: errors.array() | |
| }); | |
| } | |
| if (!req.file) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'No file uploaded' | |
| }); | |
| } | |
| const file = req.file; | |
| const userId = req.user.id; | |
| // Validate file | |
| const validation = fileService.validateFile(file); | |
| if (!validation.isValid) { | |
| // Clean up uploaded file | |
| await fileService.deleteFile(file.path); | |
| return res.status(400).json({ | |
| success: false, | |
| errors: validation.errors | |
| }); | |
| } | |
| // Extract text from file | |
| logger.info('Extracting text from uploaded file', { | |
| filename: file.filename, | |
| mimetype: file.mimetype, | |
| size: file.size | |
| }); | |
| const extractedData = await fileService.extractText(file.path, file.mimetype); | |
| // Create document record | |
| const documentData = { | |
| filename: file.filename, | |
| originalName: file.originalname, | |
| mimeType: file.mimetype, | |
| size: file.size, | |
| filePath: file.path, | |
| extractedText: extractedData.text, | |
| userId: userId, | |
| processingStatus: 'processing', | |
| type: req.body.type || 'other', | |
| courseCode: req.body.courseCode || '', | |
| courseName: req.body.courseName || '', | |
| semester: req.body.semester || '', | |
| year: req.body.year || new Date().getFullYear(), | |
| professor: req.body.professor || '' | |
| }; | |
| // Add metadata if available | |
| if (extractedData.pages) { | |
| documentData.metadata = { pages: extractedData.pages }; | |
| } | |
| const document = new Document(documentData); | |
| await document.save(); | |
| // Extract due dates in the background | |
| try { | |
| const courseInfo = { | |
| courseCode: documentData.courseCode, | |
| semester: documentData.semester, | |
| year: documentData.year | |
| }; | |
| const extractedDueDates = await dueDateExtractionService.extractDueDatesWithCourseContext( | |
| extractedData.text, | |
| courseInfo | |
| ); | |
| // Validate and add due dates to document | |
| const validatedDueDates = dueDateExtractionService.validateExtractedDates(extractedDueDates); | |
| if (validatedDueDates.length > 0) { | |
| document.dueDates = validatedDueDates; | |
| } | |
| document.processingStatus = 'completed'; | |
| await document.save(); | |
| logger.info('Due dates extracted and saved', { | |
| documentId: document._id, | |
| dueDatesCount: validatedDueDates.length | |
| }); | |
| } catch (extractionError) { | |
| logger.error('Due date extraction failed:', extractionError); | |
| document.processingStatus = 'completed'; | |
| document.processingErrors = [extractionError.message]; | |
| await document.save(); | |
| } | |
| logger.info('Document uploaded successfully', { | |
| documentId: document._id, | |
| userId: userId, | |
| filename: file.originalname | |
| }); | |
| // Return document without file path for security | |
| const responseDoc = document.toJSON(); | |
| delete responseDoc.filePath; | |
| res.status(201).json({ | |
| success: true, | |
| data: { | |
| document: responseDoc, | |
| extractedText: extractedData.text.substring(0, 500) + '...' // Preview | |
| }, | |
| message: 'Document uploaded and processed successfully' | |
| }); | |
| } catch (error) { | |
| logger.error('Document upload error:', error); | |
| // Clean up file if it exists | |
| if (req.file && req.file.path) { | |
| try { | |
| await fileService.deleteFile(req.file.path); | |
| } catch (cleanupError) { | |
| logger.error('Failed to cleanup file after error:', cleanupError); | |
| } | |
| } | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to upload and process document' | |
| }); | |
| } | |
| } | |
| async getDocuments(req, res) { | |
| try { | |
| const userId = req.user.id; | |
| const { type, courseCode, semester, year, page = 1, limit = 10 } = req.query; | |
| const options = {}; | |
| if (type) options.type = type; | |
| if (courseCode) options.courseCode = courseCode; | |
| if (semester && year) { | |
| options.semester = semester; | |
| options.year = parseInt(year); | |
| } | |
| const documents = await Document.findByUser(userId, options) | |
| .limit(limit * 1) | |
| .skip((page - 1) * limit) | |
| .exec(); | |
| const total = await Document.countDocuments({ userId, ...options }); | |
| res.json({ | |
| success: true, | |
| data: { | |
| documents, | |
| pagination: { | |
| page: parseInt(page), | |
| limit: parseInt(limit), | |
| total, | |
| pages: Math.ceil(total / limit) | |
| } | |
| } | |
| }); | |
| } catch (error) { | |
| logger.error('Get documents error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch documents' | |
| }); | |
| } | |
| } | |
| async getDocument(req, res) { | |
| try { | |
| const { id } = req.params; | |
| const userId = req.user.id; | |
| const document = await Document.findOne({ _id: id, userId }); | |
| if (!document) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'Document not found' | |
| }); | |
| } | |
| // Increment view count | |
| await document.incrementViewCount(); | |
| res.json({ | |
| success: true, | |
| data: { document } | |
| }); | |
| } catch (error) { | |
| logger.error('Get document error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch document' | |
| }); | |
| } | |
| } | |
| async updateDocument(req, res) { | |
| try { | |
| const { id } = req.params; | |
| const userId = req.user.id; | |
| const updates = req.body; | |
| // Only allow certain fields to be updated | |
| const allowedUpdates = ['type', 'courseCode', 'courseName', 'semester', 'year', 'professor', 'aiTags']; | |
| const filteredUpdates = {}; | |
| allowedUpdates.forEach(field => { | |
| if (updates[field] !== undefined) { | |
| filteredUpdates[field] = updates[field]; | |
| } | |
| }); | |
| const document = await Document.findOneAndUpdate( | |
| { _id: id, userId }, | |
| filteredUpdates, | |
| { new: true, runValidators: true } | |
| ); | |
| if (!document) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'Document not found' | |
| }); | |
| } | |
| logger.info('Document updated', { documentId: id, userId }); | |
| res.json({ | |
| success: true, | |
| data: { document }, | |
| message: 'Document updated successfully' | |
| }); | |
| } catch (error) { | |
| logger.error('Update document error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to update document' | |
| }); | |
| } | |
| } | |
| async deleteDocument(req, res) { | |
| try { | |
| const { id } = req.params; | |
| const userId = req.user.id; | |
| const document = await Document.findOne({ _id: id, userId }); | |
| if (!document) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'Document not found' | |
| }); | |
| } | |
| // Delete physical file | |
| if (document.filePath) { | |
| await fileService.deleteFile(document.filePath); | |
| } | |
| // Delete document record | |
| await Document.findByIdAndDelete(id); | |
| logger.info('Document deleted', { documentId: id, userId }); | |
| res.json({ | |
| success: true, | |
| message: 'Document deleted successfully' | |
| }); | |
| } catch (error) { | |
| logger.error('Delete document error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to delete document' | |
| }); | |
| } | |
| } | |
| async getUpcomingDueDates(req, res) { | |
| try { | |
| const userId = req.user.id; | |
| const { days = 30 } = req.query; | |
| const dueDates = await Document.findUpcomingDueDates(userId, parseInt(days)); | |
| res.json({ | |
| success: true, | |
| data: { dueDates } | |
| }); | |
| } catch (error) { | |
| logger.error('Get upcoming due dates error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch upcoming due dates' | |
| }); | |
| } | |
| } | |
| async addDueDate(req, res) { | |
| try { | |
| const { id } = req.params; | |
| const userId = req.user.id; | |
| const dueDateData = req.body; | |
| const document = await Document.findOne({ _id: id, userId }); | |
| if (!document) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'Document not found' | |
| }); | |
| } | |
| await document.addDueDate(dueDateData); | |
| logger.info('Due date added to document', { documentId: id, userId }); | |
| res.json({ | |
| success: true, | |
| data: { document }, | |
| message: 'Due date added successfully' | |
| }); | |
| } catch (error) { | |
| logger.error('Add due date error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to add due date' | |
| }); | |
| } | |
| } | |
| async searchDocuments(req, res) { | |
| try { | |
| const userId = req.user.id; | |
| const { q, page = 1, limit = 10 } = req.query; | |
| if (!q || q.trim().length < 3) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Search query must be at least 3 characters' | |
| }); | |
| } | |
| const documents = await Document.find({ | |
| userId, | |
| $text: { $search: q } | |
| }) | |
| .score({ score: { $meta: 'textScore' } }) | |
| .sort({ score: { $meta: 'textScore' } }) | |
| .limit(limit * 1) | |
| .skip((page - 1) * limit) | |
| .exec(); | |
| res.json({ | |
| success: true, | |
| data: { documents } | |
| }); | |
| } catch (error) { | |
| logger.error('Search documents error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to search documents' | |
| }); | |
| } | |
| } | |
| async getUploadStats(req, res) { | |
| try { | |
| const userId = req.user.id; | |
| // Validate ObjectId format | |
| if (!mongoose.Types.ObjectId.isValid(userId)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid user ID format' | |
| }); | |
| } | |
| const stats = await Document.aggregate([ | |
| { $match: { userId: new mongoose.Types.ObjectId(userId) } }, | |
| { | |
| $group: { | |
| _id: null, | |
| totalDocuments: { $sum: 1 }, | |
| totalSize: { $sum: '$size' }, | |
| documentTypes: { $addToSet: '$type' }, | |
| totalDueDates: { $sum: { $size: '$dueDates' } } | |
| } | |
| } | |
| ]); | |
| const fileStats = fileService.getUploadStats(); | |
| res.json({ | |
| success: true, | |
| data: { | |
| documents: stats[0] || { | |
| totalDocuments: 0, | |
| totalSize: 0, | |
| documentTypes: [], | |
| totalDueDates: 0 | |
| }, | |
| storage: fileStats | |
| } | |
| }); | |
| } catch (error) { | |
| logger.error('Get upload stats error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to fetch upload statistics' | |
| }); | |
| } | |
| } | |
| async exportCalendar(req, res) { | |
| try { | |
| const userId = req.user.id; | |
| const { | |
| course, | |
| type, | |
| startDate, | |
| endDate, | |
| minConfidence = 0.3, | |
| format = 'ics' | |
| } = req.query; | |
| // Get all due dates for the user | |
| const dueDates = await Document.findUpcomingDueDates(userId, 365); // Get all due dates for next year | |
| if (dueDates.length === 0) { | |
| return res.status(404).json({ | |
| success: false, | |
| error: 'No due dates found for calendar export' | |
| }); | |
| } | |
| // Apply filters | |
| const filters = { | |
| course, | |
| type, | |
| startDate, | |
| endDate, | |
| minConfidence: parseFloat(minConfidence) | |
| }; | |
| // Generate calendar file | |
| const calendarData = await calendarExportService.generateFilteredCalendar(dueDates, filters); | |
| // Set appropriate headers for calendar file | |
| const filename = `uga-academic-calendar-${new Date().toISOString().split('T')[0]}.ics`; | |
| res.setHeader('Content-Type', 'text/calendar; charset=utf-8'); | |
| res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); | |
| res.setHeader('Cache-Control', 'no-cache'); | |
| logger.info('Calendar exported', { | |
| userId, | |
| dueDatesCount: dueDates.length, | |
| filters | |
| }); | |
| res.send(calendarData); | |
| } catch (error) { | |
| logger.error('Calendar export error:', error); | |
| res.status(500).json({ | |
| success: false, | |
| error: 'Failed to export calendar' | |
| }); | |
| } | |
| } | |
| } | |
| module.exports = new DocumentController(); |