-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
328 lines (289 loc) · 10.2 KB
/
server.js
File metadata and controls
328 lines (289 loc) · 10.2 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const { parse } = require('querystring');
const { spawn } = require('child_process'); // Add child_process for spawning Python scraper
// Import our backend modules
const auth = require('./backend/auth');
const users = require('./backend/users');
const preferences = require('./backend/preferences');
const locations = require('./backend/locations');
const PORT = 8000;
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.md': 'text/markdown'
};
// Simple session storage (in production, use a proper session store)
const sessions = {};
// Parse POST body
function parseBody(body) {
const obj = {};
body.split('&').forEach(part => {
const [key, val] = part.split('=');
obj[decodeURIComponent(key)] = decodeURIComponent(val.replace(/\+/g, ' '));
});
return obj;
}
// Get user from request
function getUserFromRequest(req) {
const authHeader = req.headers.authorization;
if (!authHeader) return null;
try {
const token = authHeader.split(' ')[1];
const decoded = auth.verifyToken(token);
return decoded;
} catch (err) {
return null;
}
}
// Start the Python scraper as a child process
function startScraper() {
console.log('Starting AQI scraper...');
const scraperProcess = spawn('python', ['AQI_Scraper/scraper.py'], {
cwd: __dirname, // Set current working directory to project root
stdio: ['pipe', 'pipe', 'pipe'] // stdin, stdout, stderr
});
scraperProcess.stdout.on('data', (data) => {
console.log(`Scraper stdout: ${data}`);
});
scraperProcess.stderr.on('data', (data) => {
console.error(`Scraper stderr: ${data}`);
});
scraperProcess.on('close', (code) => {
console.log(`Scraper process exited with code ${code}`);
});
scraperProcess.on('error', (err) => {
console.error('Failed to start scraper:', err);
});
return scraperProcess;
}
// Start the scraper when the server starts
const scraperProcess = startScraper();
const server = http.createServer(async (req, res) => {
console.log(`Request received: ${req.url}`);
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
// Handle API routes
if (pathname.startsWith('/api/')) {
try {
// CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// NEW: AQI data endpoint - serve local JSON file
if (pathname === '/api/aqi' && req.method === 'GET') {
try {
const aqiData = fs.readFileSync('./AQI_Scraper/aqi.json', 'utf8');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(aqiData);
} catch (error) {
console.error('Error reading AQI data:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Could not read AQI data' }));
}
return;
}
// Authentication routes
if (pathname === '/api/auth/login' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const { email, password } = parseBody(body);
const result = await auth.authenticateUser(email, password);
sessions[result.token] = result.user;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (err) {
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
if (pathname === '/api/auth/register' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const { name, email, password } = parseBody(body);
const user = await auth.registerUser(name, email, password);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(user));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
if (pathname === '/api/auth/logout' && req.method === 'POST') {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
delete sessions[token];
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Logged out successfully' }));
return;
}
// Check authentication for protected routes
const user = getUserFromRequest(req);
if (!user) {
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Unauthorized' }));
return;
}
// User routes
if (pathname === '/api/user' && req.method === 'GET') {
const userData = await users.getUserById(user.userId);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(userData));
return;
}
// Preferences routes
if (pathname === '/api/preferences' && req.method === 'GET') {
const prefs = await preferences.getUserPreferences(user.userId);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(prefs));
return;
}
if (pathname === '/api/preferences' && req.method === 'PUT') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const prefs = parseBody(body);
const result = await preferences.updateUserPreferences(user.userId, prefs);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
// Locations routes
if (pathname === '/api/locations' && req.method === 'GET') {
const savedLocations = await locations.getSavedLocations(user.userId);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(savedLocations));
return;
}
if (pathname === '/api/locations' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const { location_name } = parseBody(body);
const result = await locations.saveLocation(user.userId, location_name);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
if (pathname.startsWith('/api/locations/') && req.method === 'DELETE') {
const locationId = pathname.split('/')[3];
const result = await locations.removeLocation(user.userId, locationId);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
return;
}
// Check if location is saved
if (pathname.startsWith('/api/location-check/') && req.method === 'GET') {
const locationName = decodeURIComponent(pathname.split('/')[3]);
const isSaved = await locations.isLocationSaved(user.userId, locationName);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ saved: isSaved }));
return;
}
// If no route matched
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Route not found' }));
return;
} catch (err) {
console.error('API Error:', err);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Internal server error' }));
return;
}
}
// Serve static files
let filePath = '.' + pathname;
// Serve index.html by default
if (filePath === './') {
filePath = './index.html';
}
// Resolve the file extension
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = MIME_TYPES[extname] || 'application/octet-stream';
// Read the file
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
// File not found
fs.readFile('./404.html', (err, content404) => {
if (err) {
res.writeHead(404);
res.end('404 Not Found');
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(content404, 'utf-8');
}
});
} else {
// Server error
res.writeHead(500);
res.end(`Server Error: ${error.code}`);
}
} else {
// Success
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
// Clean up the scraper process when the server shuts down
process.on('SIGTERM', () => {
console.log('Shutting down server...');
if (scraperProcess) {
scraperProcess.kill();
}
process.exit(0);
});
process.on('SIGINT', () => {
console.log('Shutting down server...');
if (scraperProcess) {
scraperProcess.kill();
}
process.exit(0);
});