-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
235 lines (204 loc) · 7.31 KB
/
app.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
228
229
230
231
232
233
234
235
// Dependencias
var express = require('express');
var textBody = require("body");
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require("fs");
var uuid = require('node-uuid');
var mkdirp = require('mkdirp');
var Hashids = require("hashids"),
hashids = new Hashids("this is my salt",0, "0123456789abcdef");
var connections = 0;
var chatConnections = [];
// Mapea los socket ids con el id generado por cada cliente
var clients = {};
// Lo uso para generar ids de boards
var boards = 0;
// Importo la carpeta public para poder routear assets
// estaticos.
app.use(express.static(__dirname + '/public'));
//Dado que el sidebar se carga en más de una página hago un sólo archivo y lo incluyo
var SIDEBAR_INCLUDE = "{SIDEBAR}";
function includeSidebarAndSend(html, res) {
fs.readFile('./partials/sidebar.inc.html', function (err, sidebarHTML) {
html = html.toString();
sidebarHTML = sidebarHTML.toString();
var resultHTML = html.replace(SIDEBAR_INCLUDE,sidebarHTML);
res.send(resultHTML);
});
}
function saveImage(rawData) {
var regex = /^data:.+\/(.+);base64,(.*)$/;
var matches = rawData.match(regex);
var ext = matches[1];
var data = matches[2];
var buffer = new Buffer(data, 'base64');
const publicDir = 'public';
const usrImgDir = 'user-img';
const pubUserImgDir = publicDir + '/' + usrImgDir;
var filename = usrImgDir + '/' + uuid.v4() + '.' + ext;
mkdirp(pubUserImgDir, function(err) {});
fs.writeFile(publicDir + '/' + filename, buffer, function(err) {
if (err) throw err;
});
return filename;
}
// Main route, muestra la página de inicio
app.get('/', function(req, res) {
fs.readFile('./index.html', function (err, indexHTML) {
if (err) throw err;
includeSidebarAndSend(indexHTML, res);
});
});
// Página de informacion (singlePageInfo)
app.get('/info', function(req, res) {
res.sendFile(__dirname + '/about.html');
});
// Aca debería mandar un mail (capaz habría que tener cuidado con los spambots)
app.post('/sendMail', function(req, res) {
res.send("ok");
});
// Crea un nuevo board y redirige
app.get('/board/', function(req, res) {
let intro = req.query.intro;
let introQuery = '';
if(intro != null){
introQuery = '?intro';
}
boards++;
var board_id = hashids.encode(boards,boards);
// var board_id = 0;
res.redirect('/board/'+board_id+introQuery);
});
app.get('/board/:board_id',function(req,res){
fs.readFile('./board.html', function (err, html) {
if (err) throw err;
includeSidebarAndSend(html, res);
});
});
app.post('/files', function(req, res) {
const extract = function (err, data) {
if (!data) return
res.setHeader('Content-Type', 'application/json');
const filePath = saveImage(data);
res.send(JSON.stringify({ filename: filePath}));
console.log('Saved file: ' + filePath);
}
textBody(req, extract);
});
// Conexión
io.on('connection', function(socket) {
var chatUser = false;
// Recibo desde el cliente el room_id
var room_id = socket.handshake.query.room_id;
var client_id = socket.client.conn.id;
socket.join(room_id);
if (!chatConnections[room_id]) chatConnections[room_id] = {qty:0,usernames:[]};
// Suma una conexion
connections++;
console.log('Usuarios conectados: ', connections);
// Usuario conectado
socket.broadcast.emit('connections',{
connections: connections
});
// Usuario conectado
socket.emit('connections', {
connections: connections
});
socket.on('clientConnectionEvent', function(data) {
clients[client_id] = data.id;
console.log("Se conecto el usuario " + clients[client_id]);
});
// Mensaje del chat
socket.on('new message', function (data) {
socket.broadcast.to(room_id).emit('new message', {
username: socket.username,
message: data
});
});
// Nuevo usuario al chat
socket.on('add user', function (username) {
if (chatUser) return;
// we store the username in the socket session for this client
socket.username = username;
++chatConnections[room_id].qty;
chatConnections[room_id].usernames.push(username);
console.log('Usuarios conectados al chat: ', chatConnections[room_id].qty);
console.log("Se conecto al chat el usuario " + username);
chatUser = true;
socket.emit('chat login', {
numUsers: chatConnections[room_id].qty,
usernames: chatConnections[room_id].usernames
});
// echo globally (all clients) that a person has connected
socket.broadcast.to(room_id).emit('user joined', {
username: socket.username,
numUsers: chatConnections[room_id].qty,
usernames: chatConnections[room_id].usernames
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.to(room_id).emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.to(room_id).emit('stop typing', {
username: socket.username
});
});
// Movimiento del puntero
// socket.on('mousemove', function(data) {
// socket.broadcast.to(room_id).emit('move', data);
// });
// Movimiento de los trazos
socket.on('externalMouseEvent',function(data){
socket.broadcast.to(room_id).emit('externalMouseEvent',data);
});
socket.on('deleteEvent', function(data) {
socket.broadcast.to(room_id).emit('deleteEvent', data);
});
// Desconexion de un cliente
socket.on('disconnect', function(data) {
if(chatUser){
chatConnections[room_id].qty--;
for (var i=chatConnections[room_id].usernames.length-1; i>=0; i--) {
if (chatConnections[room_id].usernames[i] === socket.username) {
chatConnections[room_id].usernames.splice(i, 1);
// break; //<-- Uncomment if only the first term has to be removed
}
}
socket.broadcast.to(room_id).emit('chat logout', {
numUsers: chatConnections[room_id].qty,
usernames: chatConnections[room_id].usernames
});
}
connections--;
console.log("Se desconecto el usuario " + clients[client_id]);
console.log('Usuarios conectados: ', connections);
socket.broadcast.emit('user_disconnected', {
connections: connections
});
// socket.broadcast.to(room_id).emit('deleteEvent', {
// username: socket.username,
// connections: connections
// });
// Delete all gestures from this client
var id = clients[client_id];
for (var i = 0; i < 4; i++) {
var del = {
'layer': i,
'id': id
}
socket.broadcast.to(room_id).emit("deleteEvent", del);
}
delete clients[client_id];
});
});
// Levantamos el servidor en el puerto 3000
server.listen(3000, function() {
console.log('Running on *:3000');
});