-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
116 lines (91 loc) · 3.23 KB
/
index.js
File metadata and controls
116 lines (91 loc) · 3.23 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
import express from 'express';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import url from 'node:url';
import { DateTime, Duration } from 'luxon';
import { WebSocketServer } from 'ws';
const PORT = process.env.PORT || 2224;
const timeZone = 'UTC';
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
const loadBases = async () => {
const data = await readFile(path.join(__dirname, 'buses.json'), 'utf-8');
return JSON.parse(data);
};
const getNextDeparture = (firstDepartureTime, frequencyMinutes) => {
const now = DateTime.now().setZone(timeZone);
const [hour, minute] = firstDepartureTime.split(':').map(Number);
let departure = DateTime.now().set({ hour, minute, second: 0 }).setZone(timeZone);
const endOfDay = DateTime.now().set({ hour: 23, minute: 59 }).setZone(timeZone);
while (now > departure) {
departure = departure.plus({ minutes: frequencyMinutes });
if (now > endOfDay) {
departure = DateTime.now().set({ hour, minute }).plus({ days: 1 }).setZone(timeZone);
}
}
return departure;
};
const sendUpdatedData = async () => {
const buses = await loadBases();
const now = DateTime.now().setZone(timeZone);
const updatedBases = buses.map(bus => {
const nextDeparture = getNextDeparture(bus.firstDepartureTime, bus.frequencyMinutes);
const timeRemaining = Duration.fromMillis(nextDeparture.diff(now).toMillis());
return {
...bus,
nextDeparture: {
date: nextDeparture.toFormat('yyyy-MM-dd'),
time: nextDeparture.toFormat('HH:mm:ss'),
remaining: timeRemaining.toFormat('hh:mm:ss'),
},
};
});
return updatedBases;
};
const sortBuses = buses =>
[...buses].sort(
(a, b) =>
new Date(`${a.nextDeparture.date}T${a.nextDeparture.time}Z`) -
new Date(`${b.nextDeparture.date}T${b.nextDeparture.time}Z`),
);
app.get('/next-departure', async (req, res) => {
try {
const updatedBases = await sendUpdatedData();
const sortedBuses = sortBuses(updatedBases);
res.json(sortedBuses);
} catch (error) {
console.error(error);
res.status(500).send('На сервере произошла ошибка, попробуйте оправить запрос позже');
}
});
const wss = new WebSocketServer({ noServer: true });
const clients = new Set();
wss.on('connection', ws => {
console.log('Client WebSocket connection');
clients.add(ws);
const setUpdates = async () => {
try {
const updatedBases = await sendUpdatedData();
const sortedBuses = sortBuses(updatedBases);
ws.send(JSON.stringify(sortedBuses));
} catch (error) {
console.error(`Error WebSocket connection: ${error}`);
}
};
const intervalId = setInterval(setUpdates, 1000);
ws.on('close', () => {
clearInterval(intervalId);
clients.delete(ws);
console.log('Client WebSocket closed');
});
});
const server = app.listen(PORT, 'localhost', () => {
console.log(`Сервер запущен на http://localhost:${PORT}`);
});
server.on('upgrade', (req, socket, head) => {
wss.handleUpgrade(req, socket, head, ws => {
wss.emit('connection', ws, req);
});
});