-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
131 lines (107 loc) · 2.77 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
var express = require('express');
var connect = require('connect');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://pro:[email protected]:11705/euphony');
console.log("Connected to db");
var port = process.env.PORT || 8080;
var server = app.listen(port);
var io = require('socket.io').listen(server);
//configuration
console.log("The app running on port " + port);
app.use(express.static(__dirname + '/public'));
app.use(connect.logger('dev'));
app.use(connect.json());
app.use(connect.urlencoded());
//routes
require('./routes/routes.js')(app);
var Conversation = require('./models/conversation');
var PendingConversation = require('./models/message');
var clients = [];
io.on('connection', function(socket) {
console.log('user connected');
console.log(clients);
socket.on('userId', function(id) {
var user = {};
user.id = id;
user.socket_id = socket.id;
user.online = "no";
console.log(user);
var x = clients.every(function(client) {
if(client.id == id) {
return false;
} else
return true;
});
if(x == true)
clients.push(user);
console.log(clients);
PendingConversation.find({ to: id }, function(err, messages) {
if(err)
console.log(err);
else {
var x = messages.length;
if(x != 0) {
console.log(x);
messages.forEach(function(message) {
socket.emit('message', message);
message.to = "";
message.frm = "";
message.message = "";
message.save(function(err) {
if(err)
console.log(err);
else
console.log("pendong deleteed");
});
});
}
}
});
});
socket.on('message', function(data) {
var message = data.message;
var to = data.to;
var frm = data.frm;
console.log(data);
var x = clients.every(function(client) {
if(client.id == to) {
console.log("sent" + client.socket_id);
var msg = {};
msg.message = message;
msg.frm = frm;
console.log(msg);
io.to(client.socket_id).emit('message', msg);
return false;
} else
return true;
});
if(x == true) {
var pendingConversation = new PendingConversation();
pendingConversation.to = to;
pendingConversation.frm = frm;
pendingConversation.message = message;
pendingConversation.save(function(err) {
if(err)
console.log(err);
});
}
});
socket.on('online', function(id) {
clients.forEach(function(client) {
if(client.id == id)
client.online = "yes";
});
});
socket.on('status', function(id) {
var x = 0;
clients.forEach(function(client) {
if(client.id == id) {
x = 1;
socket.emit('status', { 'online': client.online });
}
});
if(x == 0)
socket.emit('status', { 'online': "no" });
});
});