-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
227 lines (188 loc) · 7.36 KB
/
index.js
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
////////////////////////////////////////////////////////////////////////////////
// server
////////////////////////////////////////////////////////////////////////////////
const shouldUseHttps = false;
const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const data = JSON.parse(fs.readFileSync('db/data.json'));
const app = express();
const http = shouldUseHttps ? null : require('http');
const https = shouldUseHttps ? require('https') : null;
const PORT = process.env.PORT || 3000;
const { v4: uuidv4 } = require('uuid');
// handle data in a nice way
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// static path
const publicPath = path.resolve(`${__dirname}/public`);
const emscriptenPath = path.resolve(`${publicPath}/emscripten`);
const pdPath = path.resolve(`${emscriptenPath}/pd`);
const socketioPath = path.resolve(`${__dirname}/node_modules/socket.io-client/dist`);
// set your static server
app.use(express.static(publicPath));
app.use(express.static(emscriptenPath));
app.use(express.static(pdPath));
app.use(express.static(socketioPath));
// views
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'views/index.html'));
});
// create http/https server
const key = shouldUseHttps ? fs.readFileSync(`${__dirname}/key.pem`) : null;
const cert = shouldUseHttps ? fs.readFileSync(`${__dirname}/cert.pem`) : null;
const server = shouldUseHttps ? https.createServer({ key: key, cert: cert }, app) : http.createServer(app);
// start listening
server.listen(PORT, () => {
console.log(`Server is running localhost on port: ${PORT}`)
});
////////////////////////////////////////////////////////////////////////////////
// http requests
////////////////////////////////////////////////////////////////////////////////
// get note data
app.get("/api/data/notes", async (req, res) => {
res.json(data.notes);
});
// add a note to data
app.post("/api/data/notes", (req, res) => {
data.notes.push({ id: uuidv4(), hue: req.body.hue, position: req.body.position });
res.json(data.notes);
});
// edit the existing note
app.put("/api/data/notes/:id", (req, res) => {
const index = data.notes.findIndex(note => note.id === req.params.id);
if (index != -1) {
data.notes[index] = { id: req.params.id, hue: req.body.hue, position: req.body.position };
}
res.json(data.notes);
});
// delete a note from data
app.delete("/api/data/notes/:id", (req, res) => {
const index = data.notes.findIndex(note => note.id === req.params.id);
if (index != -1) {
data.notes.splice(index, 1);
}
res.json(data.notes);
});
////////////////////////////////////////////////////////////////////////////////
// socket.io
////////////////////////////////////////////////////////////////////////////////
const io = require('socket.io')({
// "transports": ["xhr-polling"],
// "polling duration": 0
}).listen(server);
// clients object
const clients = {};
// used for assigning different hue values to clients
const hueInterval = 0.108;
let hue = -hueInterval;
// socket setup
io.on('connection', client => {
console.log('User ' + client.id + ' connected, there are ' + io.engine.clientsCount + ' clients connected');
// add a new client indexed by his id
clients[client.id] = {
isMobile: true,
hue: (hue += hueInterval) % 1,
position: [0, 0, 0],
quaternion: [0, 0, 0, 0],
rotation: [0, 0, 0],
noteToPlayIds: []
}
////////////////////////////////////////////////////////////////////////////////
// senders (client.emit: send to sender client only, io.sockets.emit: send to all connected clients)
////////////////////////////////////////////////////////////////////////////////
// make sure to send clients, his ID, and a list of all keys
client.emit('introduction', clients, client.id, Object.keys(clients));
// send the hue value to myself
client.emit('setHue', clients[client.id].hue);
// send the current notes data to myself
client.emit('updateNotes', data.notes);
////////////////////////////////////////////////////////////////////////////////
// receivers
////////////////////////////////////////////////////////////////////////////////
client.on('setMobile', (_data) => {
if (clients[client.id]) {
clients[client.id].isMobile = _data;
// update everyone that the number of users has changed
io.sockets.emit('newUserConnected', clients[client.id], io.engine.clientsCount, client.id);
}
});
client.on('playerMoved', (_data) => {
if (clients[client.id]) {
clients[client.id].position = _data[0];
clients[client.id].quaternion = _data[1];
clients[client.id].rotation = _data[2];
client.emit('updateClientMoves', clients); // send back to the sender
}
});
client.on('addNote', (_data) => {
if (clients[client.id]) {
const _id = uuidv4();
const _hue = clients[client.id].hue;
const _position = _data;
data.notes.push({ id: _id, hue: _hue, position: _position });
// send the added note id to myself
client.emit('addedNoteID', _id); // send back to the sender
// update everyone that notes has been updated
io.sockets.emit('updateNotes', data.notes);
}
});
client.on('eraseNotes', (_data) => {
if (clients[client.id]) {
for (let i = 0; i < _data.length; i++) {
const index = data.notes.map(function (note) { return note.id; }).indexOf(_data[i]);
if (index != -1) {
data.notes.splice(index, 1);
}
}
// update everyone that notes has been updated
io.sockets.emit('updateNotes', data.notes);
}
});
client.on('addNoteToPlayIds', (_data) => {
if (clients[client.id]) {
clients[client.id].noteToPlayIds = [];
for (let i = 0; i < _data.length; i++) {
const index = data.notes.map(function (note) { return note.id; }).indexOf(_data[i]);
if (index != -1) {
clients[client.id].noteToPlayIds.push(data.notes[index].id);
}
}
}
});
client.on('getNotesToPlayIds', () => {
if (clients[client.id]) {
// send the clients to myself
client.emit('updateNotesToPlayIds', clients);
}
});
// handle the disconnection
client.on('disconnect', () => {
io.sockets.emit('userDisconnected', clients[client.id], client.id);
console.log('User ' + client.id + ' diconnected, there are ' + io.engine.clientsCount + ' clients connected');
delete clients[client.id];
});
});
////////////////////////////////////////////////////////////////////////////////
// exit handler
////////////////////////////////////////////////////////////////////////////////
// so the program will not close instantly
process.stdin.resume();
// do something before exit
function exitHandler(options, exitCode) {
if (options.cleanup) {
console.log("\nwriting 'db/data.json' file");
fs.writeFileSync('db/data.json', JSON.stringify(data, null, 2));
}
if (options.exit) process.exit();
}
// do something when app is closing
process.on('exit', exitHandler.bind(null, { cleanup: true }));
// catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, { exit: true }));
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler.bind(null, { exit: true }));
process.on('SIGUSR2', exitHandler.bind(null, { exit: true }));
// catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, { exit: true }));