forked from byrichardpowell/draw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
517 lines (433 loc) · 14.9 KB
/
Copy pathserver.js
File metadata and controls
517 lines (433 loc) · 14.9 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/**
* Module dependencies.
*/
var express = require("express");
var app = express();
var paper = require('paper');
paper.setup(new paper.Canvas(1920, 1080));
var socket = require('socket.io');
var ueberDB = require("ueberDB");
var db = new ueberDB.database("dirty", {"filename" : "var/dirty.db"});
var async = require('async');
var fs = require('fs');
app.configure(function(){
app.use(express.static(__dirname + '/'));
});
/**
* A setting, just one
*/
var port = 3000;
/** Below be dragons
*
*/
// SESSIONS
app.use(express.cookieParser());
app.use(express.session({secret: 'secret', key: 'express.sid'}));
// DEV MODE
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
// PRODUCTON MODE
app.configure('production', function(){
app.use(express.errorHandler());
});
// ROUTES
// Index page
app.get('/', function(req, res){
res.sendfile(__dirname + '/src/static/html/index.html');
});
// Drawings
app.get('/d/*', function(req, res){
res.sendfile(__dirname + '/src/static/html/draw.html');
});
// Front-end tests
app.get('/tests/frontend/specs_list.js', function(req, res){
async.parallel({
coreSpecs: function(callback){
exports.getCoreTests(callback);
},
pluginSpecs: function(callback){
exports.getPluginTests(callback);
}
},
function(err, results){
var files = results.coreSpecs; // push the core specs to a file object
files = files.concat(results.pluginSpecs); // add the plugin Specs to the core specs
//console.debug("Sent browser the following test specs:", files.sort());
// console.log("Sent browser the following test specs:", files.sort());
res.send("var specs_list = " + JSON.stringify(files.sort()) + ";\n");
});
});
// Used for front-end tests
var url2FilePath = function(url){
var subPath = url.substr("/tests/frontend".length);
if (subPath == ""){
subPath = "index.html"
}
subPath = subPath.split("?")[0];
var filePath = path.normalize(npm.root + "/../tests/frontend/")
filePath += subPath.replace("..", "");
return filePath;
}
// Used for front-end tests
app.get('/tests/frontend/specs/*', function (req, res) {
var specFilePath = url2FilePath(req.url);
var specFileName = path.basename(specFilePath);
fs.readFile(specFilePath, function(err, content){
if(err){ return res.send(500); }
content = "describe(" + JSON.stringify(specFileName) + ", function(){ " + content + " });";
res.send(content);
});
});
// Used for front-end tests
app.get('/tests/frontend/*', function (req, res) {
var filePath = url2FilePath(req.url);
res.sendfile(filePath);
});
// Used for front-end tests
app.get('/tests/frontend', function (req, res) {
res.redirect('/tests/frontend/');
});
// Used for front-end tests
exports.getPluginTests = function(callback){
var pluginSpecs = [];
var plugins = fs.readdirSync('node_modules');
plugins.forEach(function(plugin){
if(fs.existsSync("node_modules/"+plugin+"/static/tests/frontend/specs")){ // if plugins exists
var specFiles = fs.readdirSync("node_modules/"+plugin+"/static/tests/frontend/specs/");
async.forEach(specFiles, function(spec){ // for each specFile push it to pluginSpecs
pluginSpecs.push("/static/plugins/"+plugin+"/static/tests/frontend/specs/" + spec);
},
function(err){
// blow up if something bad happens!
});
}
});
callback(null, pluginSpecs);
}
// Used for front-end tests
exports.getCoreTests = function(callback){
fs.readdir('tests/frontend/specs', function(err, coreSpecs){ // get the core test specs
if(err){ return res.send(500); }
callback(null, coreSpecs);
});
}
// Static files IE Javascript and CSS
app.use("/static", express.static(__dirname + '/src/static'));
// LISTEN FOR REQUESTS
var server = app.listen(port);
var io = socket.listen(server);
// SocketIO into production mode
io.enable('browser client minification'); // send minified client
io.enable('browser client etag'); // apply etag caching logic based on version number
io.enable('browser client gzip'); // gzip the file
io.set('log level', 1); // reduce logging
// enable all transports (optional if you want flashsocket support, please note that some hosting
// providers do not allow you to create servers that listen on a port different than 80 or their
// default port)
io.set('transports', [
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
]);
// SOCKET IO
io.sockets.on('connection', function (socket) {
socket.on('disconnect', function () {
disconnect(socket);
});
// EVENT: User stops drawing something
// Having room as a parameter is not good for secure rooms
socket.on('draw:progress', function (room, uid, co_ordinates) {
if (!projects[room] || !projects[room].project) {
loadError(socket);
return;
}
io.sockets.in(room).emit('draw:progress', uid, co_ordinates);
progress_external_path(room, JSON.parse(co_ordinates), uid);
});
// EVENT: User stops drawing something
// Having room as a parameter is not good for secure rooms
socket.on('draw:end', function (room, uid, co_ordinates) {
if (!projects[room] || !projects[room].project) {
loadError(socket);
return;
}
io.sockets.in(room).emit('draw:end', uid, co_ordinates);
end_external_path(room, JSON.parse(co_ordinates), uid);
});
// User joins a room
socket.on('subscribe', function(data) {
subscribe(socket, data);
});
// User clears canvas
socket.on('canvas:clear', function(room) {
if (!projects[room] || !projects[room].project) {
loadError(socket);
return;
}
clearCanvas(room);
io.sockets.in(room).emit('canvas:clear');
});
// User removes an item
socket.on('item:remove', function(room, uid, itemName) {
removeItem(room, uid, itemName);
});
// User moves one or more items on their canvas - progress
socket.on('item:move:progress', function(room, uid, itemNames, delta) {
moveItemsProgress(room, uid, itemNames, delta);
});
// User moves one or more items on their canvas - end
socket.on('item:move:end', function(room, uid, itemNames, delta) {
moveItemsEnd(room, uid, itemNames, delta);
});
// User adds a raster image
socket.on('image:add', function(room, uid, data, position, name) {
addImage(room, uid, data, position, name);
});
});
var projects = {};
var closeTimer = {}; // setTimeout function for closing a project when
// there are no active connections
// Subscribe a client to a room
function subscribe(socket, data) {
var room = data.room;
// Subscribe the client to the room
socket.join(room);
// If the close timer is set, cancel it
if (closeTimer[room]) {
clearTimeout(closeTimer[room]);
}
// Create Paperjs instance for this room if it doesn't exist
var project = projects[room];
if (!project) {
projects[room] = {};
// Use the view from the default project. This project is the default
// one created when paper is instantiated. Nothing is ever written to
// this project as each room has its own project. We share the View
// object but that just helps it "draw" stuff to the invisible server
// canvas.
projects[room].project = new paper.Project(paper.projects[0].view);
projects[room].external_paths = {};
loadFromDB(room, socket);
} else { // Project exists in memory, no need to load from database
loadFromMemory(room, socket);
}
// Broadcast to room the new user count
var active_connections = io.sockets.manager.rooms['/' + room].length;
io.sockets.in(room).emit('user:connect', active_connections);
}
// Try to load room from database
function loadFromDB(room, socket) {
if (projects[room] && projects[room].project) {
var project = projects[room].project;
db.init(function (err) {
if(err) {
console.error(err);
}
db.get(room, function(err, value) {
if (value && project && project instanceof paper.Project && project.activeLayer) {
socket.emit('loading:start');
// Clear default layer as importing JSON adds a new layer.
// We want the project to always only have one layer.
project.activeLayer.remove();
project.importJSON(value.project);
socket.emit('project:load', value);
}
socket.emit('loading:end');
db.close(function(){});
});
});
} else {
loadError(socket);
}
}
// Send current project to new client
function loadFromMemory(room, socket) {
var project = projects[room].project;
if (!project) { // Additional backup check, just in case
loadFromDB(room, socket);
return;
}
socket.emit('loading:start');
var value = project.exportJSON();
socket.emit('project:load', {project: value});
socket.emit('loading:end');
}
// When a client disconnects, unsubscribe him from
// the rooms he subscribed to
function disconnect(socket) {
// Get a list of rooms for the client
var rooms = io.sockets.manager.roomClients[socket.id];
// Unsubscribe from the rooms
for(var room in rooms) {
if(room && rooms[room]) {
unsubscribe(socket, { room: room.replace('/','') });
}
}
}
// Unsubscribe a client from a room
function unsubscribe(socket, data) {
var room = data.room;
// Remove the client from socket.io room
// This is optional for the disconnect event, we do it anyway
// because we want to broadcast the new room population
socket.leave(room);
// Broadcast to room the new user count
if (io.sockets.manager.rooms['/' + room]) {
var active_connections = io.sockets.manager.rooms['/' + room].length;
io.sockets.in(room).emit('user:disconnect', active_connections);
} else {
// Wait a few seconds before closing the project to finish pending writes to pad
closeTimer[room] = setTimeout(function() {
// Iff no one left in room, remove Paperjs instance
// from the array to free up memory
var project = projects[room].project;
// All projects share one View, calling remove() on one project destroys the View
// for all projects. Set to false first.
project.view = false;
project.remove();
projects[room] = undefined;
}, 5000);
}
}
function loadError(socket) {
socket.emit('project:load:error');
}
// Ends a path
var end_external_path = function (room, points, artist) {
var project = projects[room].project;
project.activate();
var path = projects[room].external_paths[artist];
if (path) {
// Close the path
path.add(new paper.Point(points.end[1], points.end[2]));
path.closed = true;
path.smooth();
project.view.draw();
// Remove the old data
projects[room].external_paths[artist] = false;
}
writeProjectToDB(room);
};
// Continues to draw a path in real time
progress_external_path = function (room, points, artist) {
var project = projects[room].project;
project.activate();
var path = projects[room].external_paths[artist];
// The path hasn't already been started
// So start it
if (!path) {
projects[room].external_paths[artist] = new paper.Path();
path = projects[room].external_paths[artist];
// Starts the path
var start_point = new paper.Point(points.start[1], points.start[2]);
var color = new paper.Color(points.rgba.red, points.rgba.green, points.rgba.blue, points.rgba.opacity);
if(points.tool == "draw"){
path.fillColor = color;
}
else if (points.tool == "pencil"){
path.strokeColor = color;
path.strokeWidth = 2;
}
path.name = points.name;
path.add(start_point);
}
// Draw all the points along the length of the path
var paths = points.path;
var length = paths.length;
for (var i = 0; i < length; i++) {
path.add(new paper.Point(paths[i].top[1], paths[i].top[2]));
path.insert(0, new paper.Point(paths[i].bottom[1], paths[i].bottom[2]));
}
path.smooth();
project.view.draw();
};
function writeProjectToDB(room) {
var project = projects[room].project;
var json = project.exportJSON();
db.init(function (err) {
if(err) {
console.error(err);
}
db.set(room, {project: json});
});
}
function clearCanvas(room) {
var project = projects[room].project;
if (project && project.activeLayer && project.activeLayer.hasChildren()) {
// Remove all but the active layer
if (project.layers.length > 1) {
var activeLayerID = project.activeLayer._id;
for (var i=0; i<project.layers.length; i++) {
if (project.layers[i]._id != activeLayerID) {
project.layers[i].remove();
i--;
}
}
}
// Remove all of the children from the active layer
if (project && project.activeLayer && project.activeLayer.hasChildren()) {
project.activeLayer.removeChildren();
}
writeProjectToDB(room);
}
}
// Remove an item from the canvas
function removeItem(room, artist, itemName) {
var project = projects[room].project;
if (project && project.activeLayer && project.activeLayer._namedChildren[itemName] && project.activeLayer._namedChildren[itemName][0]) {
project.activeLayer._namedChildren[itemName][0].remove();
io.sockets.in(room).emit('item:remove', artist, itemName);
writeProjectToDB(room);
}
}
// Move one or more existing items on the canvas
function moveItemsProgress(room, artist, itemNames, delta) {
var project = projects[room].project;
if (project && project.activeLayer) {
for (x in itemNames) {
var itemName = itemNames[x];
var namedChildren = project.activeLayer._namedChildren;
if (namedChildren && namedChildren[itemName] && namedChildren[itemName][0]) {
project.activeLayer._namedChildren[itemName][0].position.x += delta[1];
project.activeLayer._namedChildren[itemName][0].position.y += delta[2];
}
}
if (itemNames) {
io.sockets.in(room).emit('item:move', artist, itemNames, delta);
}
}
}
// Move one or more existing items on the canvas
// and write to DB
function moveItemsEnd(room, artist, itemNames, delta) {
var project = projects[room].project;
if (project && project.activeLayer) {
for (x in itemNames) {
var itemName = itemNames[x];
var namedChildren = project.activeLayer._namedChildren;
if (namedChildren && namedChildren[itemName] && namedChildren[itemName][0]) {
project.activeLayer._namedChildren[itemName][0].position.x += delta[1];
project.activeLayer._namedChildren[itemName][0].position.y += delta[2];
}
}
if (itemNames) {
io.sockets.in(room).emit('item:move', artist, itemNames, delta);
}
writeProjectToDB(room);
}
}
// Add image to canvas
function addImage(room, artist, data, position, name) {
var project = projects[room].project;
if (project && project.activeLayer) {
var image = JSON.parse(data);
var raster = new paper.Raster(image);
raster.position = new paper.Point(position[1], position[2]);
raster.name = name;
io.sockets.in(room).emit('image:add', artist, data, position, name);
writeProjectToDB(room);
}
}