-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
234 lines (193 loc) · 7.85 KB
/
Copy pathapp.js
File metadata and controls
234 lines (193 loc) · 7.85 KB
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
/**
* ============================================================================
* MICROCOASTER WEBAPP - MAIN APPLICATION SERVER
* ============================================================================
* Express.js application with Socket.io for real-time IoT module management
*
* @version 1.0.0
* @description Web interface for MicroCoaster IoT modules control and monitoring
* @features Real-time updates, User authentication, Admin panel, Module control
* ============================================================================
*/
require('dotenv').config();
// ============================================================================
// DEPENDENCIES & IMPORTS
// ============================================================================
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const path = require('path');
const cors = require('cors');
const AppLogger = require('./utils/logger');
// TEMPORARY FIX: Expose Logger globally to prevent Express error
global.Logger = AppLogger;
const databaseManager = require('./bdd/DatabaseManager');
const RealTimeAPI = require('./api');
const websocketHandler = require('./websocket/handlers');
const ESP32WebSocketServer = require('./websocket/esp-server');
const SocketWSBridge = require('./websocket/socket-ws-bridge');
const { router: authRoutes } = require('./routes/auth');
const adminRoutes = require('./routes/admin');
const moduleRoutes = require('./routes/modules');
const dashboardRoutes = require('./routes/dashboard');
const timelinesRoutes = require('./routes/timelines');
const documentationsRoutes = require('./routes/documentations');
const languageRoutes = require('./routes/language');
// Language middleware
const { languageMiddleware } = require('./middleware/language');
// ============================================================================
// APPLICATION SETUP
// ============================================================================
const app = express();
const server = createServer(app);
const io = new Server(server, {
cors: {
origin: process.env.WS_CORS_ORIGIN || '*',
methods: ['GET', 'POST'],
},
path: '/socket.io/', // Path explicite pour Socket.IO (par défaut mais explicité)
pingTimeout: 60000,
pingInterval: 25000,
connectTimeout: 45000,
// Utiliser SEULEMENT polling pour une séparation complète
transports: ['polling'],
allowEIO3: true, // Compatibilité avec différentes versions
});
// ============================================================================
// MIDDLEWARE CONFIGURATION
// ============================================================================
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data:; " +
"connect-src 'self' ws: wss:; " +
"font-src 'self';"
);
next();
});
app.use(cors());
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const sessionMiddleware = session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.COOKIE_SECURE === 'true',
maxAge: parseInt(process.env.COOKIE_MAX_AGE) || 24 * 60 * 60 * 1000,
},
});
app.use(sessionMiddleware);
// Language middleware - must be after session for cookie access
app.use(languageMiddleware);
io.use((socket, next) => {
sessionMiddleware(socket.request, socket.request.res || {}, next);
});
// ============================================================================
// STATIC FILES & ROUTES
// ============================================================================
app.use('/assets', express.static(path.join(__dirname, 'public/assets')));
app.use('/css', express.static(path.join(__dirname, 'public/css')));
app.use('/js', express.static(path.join(__dirname, 'public/js')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', authRoutes);
app.use('/admin', adminRoutes);
app.use('/dashboard', dashboardRoutes);
app.use('/modules', moduleRoutes);
app.use('/timelines', timelinesRoutes);
app.use('/documentations', documentationsRoutes);
app.use('/api/language', languageRoutes);
app.use((req, res) => {
res.status(404).send('Page not found');
});
// ============================================================================
// WEBSOCKET SETUP & REAL-TIME API INITIALIZATION
// ============================================================================
io.app = app;
let realTimeAPI = null;
async function initializeRealTimeAPI() {
try {
await databaseManager.initialize();
await databaseManager.initializeDatabase();
realTimeAPI = new RealTimeAPI(io, databaseManager);
realTimeAPI.initialize();
app.locals.realTimeAPI = realTimeAPI;
AppLogger.app.info('🔄 Real-time Events API initialized early');
} catch (error) {
AppLogger.app.error('❌ Real-time API initialization failed:', error);
throw error;
}
}
// Initialize real-time API before starting server
initializeRealTimeAPI()
.then(() => {
startServer();
})
.catch(error => {
AppLogger.app.error('❌ Failed to initialize real-time API:', error);
process.exit(1);
});
// ============================================================================
// ERROR HANDLING
// ============================================================================
// Fixed: The error was caused by LocaleLoader constructor issue in routes/language.js
// Catch unhandled errors
process.on('uncaughtException', error => {
AppLogger.app.error('❌ Uncaught Exception:', error.message);
AppLogger.app.error('Stack:', error.stack);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
AppLogger.app.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
// ============================================================================
// SERVER INITIALIZATION
// ============================================================================
/**
* Initialize and start the MicroCoaster server
* @async
* @function startServer
*/
async function startServer() {
try {
// Real-time API already initialized above
// Initialiser les handlers Socket.IO (clients web uniquement)
websocketHandler(io, null); // Temporaire: sans bridge
databaseManager.startModuleStatusCleanup(1, 5);
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
AppLogger.app.info(`🚀 MicroCoaster Server running on port ${PORT}`);
AppLogger.app.info(`📱 Web interface: http://localhost:${PORT}`);
AppLogger.app.info(`🔌 WebSocket: ws://localhost:${PORT}`);
// Initialiser ESP32 APRÈS que le serveur soit opérationnel
setTimeout(() => {
try {
AppLogger.app.info('🔄 Initializing ESP32 WebSocket Server...');
const esp32Server = new ESP32WebSocketServer(server, realTimeAPI);
esp32Server.initialize();
esp32Server.startHeartbeatChecker();
AppLogger.app.info('🔄 Initializing Socket-WebSocket Bridge...');
const socketWSBridge = new SocketWSBridge(realTimeAPI, esp32Server);
app.locals.esp32Server = esp32Server;
app.locals.socketWSBridge = socketWSBridge;
AppLogger.app.info('✅ ESP32 WebSocket Server initialized successfully');
} catch (error) {
AppLogger.app.error('❌ ESP32 initialization failed:', error);
}
}, 1000); // Délai de 1 seconde après démarrage
});
} catch (error) {
AppLogger.app.error('❌ Failed to start server:', error);
process.exit(1);
}
}
module.exports = { app, server, io };