-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
112 lines (91 loc) · 2.53 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
var MongoClient = require('mongodb')
var url = 'mongodb://localhost:27017'
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
/*var data = {
t: 13313113, //tiempo en el que se envia el msg
oid: "[email protected]", //id del cliente origen
oname: "chef1", //nombre del cliente origen
did: "[email protected]", //id del destinatario del msg
msg: "olakase", //msg
plate: "aros", //nombre del plato
plateid: 3231 //id del plato
}*/
var sUsers = {}
io.on('connection', function(socket) {
let userID = socket.handshake.query.loggeduser
sUsers[userID]=socket
console.log("Connected user: "+userID);
sendCachedMsgByDid(userID, socket)
socket.on('sendThat', function(data, callback) {
if (isConnected(data.did)) {
sUsers[data.did].emit('incomingMsg', [data]);
}
else {
add2db(data)
}
callback(true)
});
socket.on('disconnect', function() {
delete sUsers[userID]
console.log(userID);
});
});
function isConnected(id) {
if (sUsers[id]!=undefined) {
return true
}
return false
}
function sendCachedMsgByDid(did, s) {
MongoClient.connect(url, { useNewUrlParser: true }, function(err, client){
if (err)
throw err
console.log("Connected to db");
const db = client.db('chatserver')
const collection = db.collection('PendingMessages');
collection.find({}, { query: { did: did } }).toArray(function(err, result) {
if (err) throw err;
console.log("emit");
s.emit('incomingMsg', result, function(success) {
if (success) {
deleteCachedMsgByDid(did, s)
}
});
});
})
}
function deleteCachedMsgByDid(did, s){
MongoClient.connect(url, { useNewUrlParser: true }, function(err, client){
if (err)
throw err
console.log("Connected to db");
const db = client.db('chatserver')
const collection = db.collection('PendingMessages');
collection.deleteMany({did:did}, function(err, obj){
if (err) throw err
})
})
}
function add2db(data) {
MongoClient.connect(url, { useNewUrlParser: true }, function(err, client){
if (err)
throw err
console.log("Connected to db");
const db = client.db('chatserver')
const collection = db.collection('PendingMessages');
collection.insertOne(data, (err, result)=>{
if (err) throw err
})
})
}
server.listen(80, function() {
console.log('Servidor corriendo en http://localhost:80');
});
/*
app.get('/', function (req,res) {
res.send('Hello');
});
*/