Skip to content

Commit

Permalink
See #28 Se agrega una conexion MongoDB para almacenar temporalmente l…
Browse files Browse the repository at this point in the history
…os boards
  • Loading branch information
glozano committed Aug 11, 2018
1 parent 0d719a3 commit e954e49
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 4 deletions.
58 changes: 54 additions & 4 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,25 @@ var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require("fs");
var MongoClient = require("mongodb").MongoClient;
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 = [];

// MongoDB vars
var db = null;
const url = 'mongodb://localhost:27017';
const dbName = 'mongo_trazos';

// Mapea los socket ids con el id generado por cada cliente
var clients = {};

// Lo uso para generar ids de boards
var boards = 0;
var boardSeed = 0;
var boards = [];

// Importo la carpeta public para poder routear assets
// estaticos.
Expand All @@ -34,6 +41,14 @@ function includeSidebarAndSend(html, res) {
});
}

function initDB(){
// Use connect method to connect to the server
MongoClient.connect(url, { useNewUrlParser: true },function(err, client) {
console.log("Connected successfully to Mongo");
db = client.db(dbName);
});
}

function saveImage(rawData) {
var regex = /^data:.+\/(.+);base64,(.*)$/;

Expand Down Expand Up @@ -72,9 +87,8 @@ app.post('/sendMail', function(req, res) {

// Crea un nuevo board y redirige
app.get('/board/', function(req, res) {
boards++;
var board_id = hashids.encode(boards,boards);
// var board_id = 0;
boardSeed++;
var board_id = hashids.encode(boardSeed,boardSeed);
res.redirect('/board/'+board_id);
});

Expand Down Expand Up @@ -110,6 +124,15 @@ io.on('connection', function(socket) {

// Suma una conexion
connections++;
if(boards[room_id]){
boards[room_id].connections++;
}else{
boards[room_id] = {
"id":room_id,
"connections":1
};
}

console.log('Usuarios conectados: ', connections);

// Usuario conectado
Expand Down Expand Up @@ -178,6 +201,7 @@ io.on('connection', function(socket) {

// Movimiento de los trazos
socket.on('externalMouseEvent',function(data){
db.collection("lines").insert({board:room_id,data:data,user:client_id,timestamp:new Date()});
socket.broadcast.to(room_id).emit('externalMouseEvent',data);
});

Expand Down Expand Up @@ -218,13 +242,39 @@ io.on('connection', function(socket) {
'id': id
}
socket.broadcast.to(room_id).emit("deleteEvent", del);
// db.collection("lines").deleteMany({"user":client_id});
}
console.log(JSON.stringify(boards));
boards[room_id].connections--;
if(boards[room_id].connections < 1){
// db.collection("lines").deleteMany({"board":room_id});
}

delete clients[client_id];
});

setTimeout(function(){
db.collection('lines').find({"board":room_id}).toArray(function (err, result) {
if(result.length){
socket.emit("previousLines",result);
}
});
},1000);

});

// Levantamos el servidor en el puerto 3000
server.listen(3000, function() {
console.log('Running on *:3000');
initDB();
console.log('Mongo running on '+url);

// Borramos boards viejos
setInterval(function () {
var THREE_HOURS = 3 * 60 * 60 * 1000; /* ms */
db.collection("lines").deleteMany(
{
"timestamp" : {$lt : new Date((new Date())-THREE_HOURS)}
});
}, 1 * 60 * 60 * 1000);
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"express": "^4.10.2",
"hashids": "1.0.1",
"mkdirp": "^0.5.1",
"mongodb": "^3.1.1",
"node-uuid": "^1.4.7",
"socket.io": "^1.3.6"
},
Expand Down
6 changes: 6 additions & 0 deletions public/js/trazos/board.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,10 @@ function initSocketObservers(){
log('attempt to reconnect has failed');
});
socket.on('externalMouseEvent', externalMouseEvent);

socket.on('previousLines', function(lines){
lines.forEach(function(line){
externalMouseEvent(line.data);
})
});
}

0 comments on commit e954e49

Please sign in to comment.