Spaces:
Sleeping
Sleeping
Download backend/server.js.backup from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 8.99 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/server.js.backup
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/server.js.backup
-
curl -L -o server.js.backup https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/server.js.backup
8.99 kB
| 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(` | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>edi.chat - UGA AI Assistant</title> | |
| <style> | |
| body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; } | |
| .header { text-align: center; color: #BA0C2F; } | |
| .status { background: #f0f0f0; padding: 15px; border-radius: 8px; margin: 20px 0; } | |
| .api-link { display: inline-block; margin: 10px; padding: 10px 20px; background: #BA0C2F; color: white; text-decoration: none; border-radius: 5px; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="header"> | |
| <h1>π edi.chat</h1> | |
| <h2>UGA AI Assistant</h2> | |
| </div> | |
| <div class="status"> | |
| <h3>β Backend Server Running</h3> | |
| <p>The edi.chat backend server is running successfully!</p> | |
| <p><strong>Environment:</strong> ${process.env.NODE_ENV || 'development'}</p> | |
| <p><strong>AI Configuration:</strong> ${process.env.USE_HUGGINGFACE === 'true' ? 'Hugging Face' : process.env.USE_LOCAL_AI === 'true' ? 'Local Ollama' : 'OpenAI'}</p> | |
| </div> | |
| <h3>π API Endpoints</h3> | |
| <a href="/health" class="api-link">Health Check</a> | |
| <a href="/api/health" class="api-link">API Health</a> | |
| <a href="/dashboard" class="api-link">Dashboard</a> | |
| <h3>π About edi.chat</h3> | |
| <p>An intelligent, agentic AI assistant specifically designed for the University of Georgia community.</p> | |
| <h4>π― Key Features:</h4> | |
| <ul> | |
| <li><strong>Agentic Capabilities:</strong> Actually performs tasks, not just provides information</li> | |
| <li><strong>Course Registration:</strong> Register for classes directly through the chat</li> | |
| <li><strong>UGA-Specific Intelligence:</strong> Deep understanding of UGA systems and procedures</li> | |
| <li><strong>Multiple AI Models:</strong> Support for OpenAI, Ollama, and Hugging Face</li> | |
| </ul> | |
| <p><em>Frontend loading... If this page persists, the React frontend may still be building.</em></p> | |
| </body> | |
| </html> | |
| `); | |
| } else { | |
| res.sendFile(indexPath); | |
| } | |
| }); | |
| }); | |
| server.listen(PORT, '0.0.0.0'); | |
| module.exports = app; |