require('dotenv').config(); const express = require('express'); const cors = require('cors'); const helmet = require('helmet'); const morgan = require('morgan'); const rateLimit = require('express-rate-limit'); const { createServer } = require('http'); const { Server } = require('socket.io'); const { connectDB } = require('./src/utils/database'); const { connectRedis } = require('./src/utils/redis'); const logger = require('./src/utils/logger'); const schedulerService = require('./src/services/schedulerService'); // Import routes const authRoutes = require('./src/routes/auth'); const chatRoutes = require('./src/routes/chat'); const ugaRoutes = require('./src/routes/uga'); const userRoutes = require('./src/routes/user'); const facultyRoutes = require('./src/routes/faculty'); const dashboardRoutes = require('./src/routes/dashboard'); const documentRoutes = require('./src/routes/documents'); const diningRoutes = require('./src/routes/dining'); // CORS configuration for edi.chat domain and Hugging Face const allowedOrigins = [ 'https://edi.chat', 'https://www.edi.chat', 'http://localhost:3000', 'http://localhost:3001', 'https://edichat-edi-chat-test.hf.space', 'https://huggingface.co', process.env.FRONTEND_URL ].filter(Boolean); const app = express(); const server = createServer(app); const io = new Server(server, { cors: { origin: allowedOrigins, methods: ['GET', 'POST'], credentials: true } }); const PORT = process.env.PORT || 7860; // Connect to databases asynchronously (non-blocking) connectDB().catch(err => logger.error('Database connection failed:', err)); connectRedis().catch(err => logger.error('Redis connection failed:', err)); // Initialize scheduler try { schedulerService.init(); } catch (err) { logger.error('Scheduler init failed:', err); } // Security middleware app.use(helmet({ contentSecurityPolicy: process.env.NODE_ENV === 'production' ? undefined : false })); app.use(cors({ origin: function (origin, callback) { // Allow requests with no origin (like mobile apps, curl requests, or Hugging Face) if (!origin) return callback(null, true); if (allowedOrigins.indexOf(origin) !== -1) { callback(null, true); } else { // Log rejected origins for debugging logger.info(`CORS blocked origin: ${origin}`); callback(null, true); // Temporarily allow all origins for HF debugging } }, credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'] })); // Rate limiting - TEMPORARILY DISABLED FOR DEVELOPMENT // const limiter = rateLimit({ // windowMs: 15 * 60 * 1000, // 15 minutes // max: 100, // limit each IP to 100 requests per windowMs // message: 'Too many requests from this IP, please try again later.' // }); // app.use('/api', limiter); // Body parsing middleware app.use(express.json({ limit: '10mb' })); app.use(express.urlencoded({ extended: true })); // NO LOGGING - completely silent // Serve static files and frontend const path = require('path'); // Serve built frontend from public directory app.use(express.static(path.join(__dirname, 'public'))); // Serve dashboard HTML (temporary - no auth for testing) app.get('/dashboard', (req, res) => { res.sendFile(path.join(__dirname, 'dashboard.html')); }); // Serve demo page when main frontend is not available app.get('/demo', (req, res) => { res.sendFile(path.join(__dirname, 'demo.html')); }); // Routes app.use('/api/auth', authRoutes); app.use('/api/chat', chatRoutes); app.use('/api/uga', ugaRoutes); app.use('/api/user', userRoutes); app.use('/api/faculty', facultyRoutes); app.use('/api/dashboard', dashboardRoutes); app.use('/api/documents', documentRoutes); app.use('/api/dining', diningRoutes); // Health check endpoint app.get('/health', (req, res) => { res.status(200).json({ status: 'OK', timestamp: new Date().toISOString(), uptime: process.uptime(), environment: process.env.NODE_ENV || 'development', ai_config: { use_local_ai: process.env.USE_LOCAL_AI === 'true', use_huggingface: process.env.USE_HUGGINGFACE === 'true', local_ai_url: process.env.LOCAL_AI_URL || 'not configured', huggingface_model: process.env.HUGGINGFACE_MODEL || 'not configured' } }); }); app.get('/api/health', (req, res) => { res.status(200).json({ status: 'OK', timestamp: new Date().toISOString(), uptime: process.uptime(), environment: process.env.NODE_ENV || 'development' }); }); // Simple chat endpoint for demo/testing (no auth required) app.post('/api/simple-chat', async (req, res) => { try { const { message } = req.body; if (!message) { return res.status(400).json({ success: false, error: 'Message is required' }); } // Import AI service for direct use const aiService = require('./src/services/aiService'); // Generate response using local AI const response = await aiService.generateResponse(message, [], 'general'); res.json({ success: true, response: response, timestamp: new Date().toISOString(), message: message }); } catch (error) { logger.error('Simple chat error:', error); res.status(500).json({ success: false, error: 'Failed to generate response', details: error.message }); } }); // Socket.io connection handling io.on('connection', (socket) => { logger.info(`User connected: ${socket.id}`); socket.on('join-room', (userId) => { socket.join(`user-${userId}`); logger.info(`User ${userId} joined room`); }); socket.on('chat-message', (data) => { // Handle real-time chat messages socket.to(`user-${data.userId}`).emit('bot-response', data.response); }); socket.on('disconnect', () => { logger.info(`User disconnected: ${socket.id}`); }); }); // Error handling middleware app.use((err, req, res, next) => { logger.error(err.stack); res.status(500).json({ error: 'Something went wrong!', message: process.env.NODE_ENV === 'development' ? err.message : 'Internal server error' }); }); // Catch-all handler for SPA routes (must be after API routes) app.get('*', (req, res) => { const indexPath = path.join(__dirname, 'public', 'index.html'); // Check if index.html exists, otherwise serve a simple fallback require('fs').access(indexPath, require('fs').constants.F_OK, (err) => { if (err) { // Fallback HTML for when frontend build isn't available res.send(`
The edi.chat backend server is running successfully!
Environment: ${process.env.NODE_ENV || 'development'}
AI Configuration: ${process.env.USE_HUGGINGFACE === 'true' ? 'Hugging Face' : process.env.USE_LOCAL_AI === 'true' ? 'Local Ollama' : 'OpenAI'}
An intelligent, agentic AI assistant specifically designed for the University of Georgia community.
Frontend loading... If this page persists, the React frontend may still be building.
`); } else { res.sendFile(indexPath); } }); }); server.listen(PORT, '0.0.0.0'); module.exports = app;