-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
369 lines (236 loc) · 9.51 KB
/
server.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
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
var express=require('express');
var app= express();
var http=require('http').Server(app);
var io=require('socket.io')(http);
var cookieParser=require('cookie-parser');
var bodyParser=require('body-parser');
var date=require('date-and-time');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MySQLStore = require('express-mysql-session')(session);
var flash = require('connect-flash');
var bcrypt= require('bcrypt');
var SocketIOFile = require('socket.io-file');
var users={};
var friends=new Array();
var fri=[];
var publicKeys={};
var privateKeys={};
require('dotenv').config();
app.use(express.static(__dirname + '/assets'));
app.set('views',__dirname+'/views');
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
var options={
host:process.env.DB_HOST,
user:process.env.DB_USER,
password:process.env.DB_PASSWORD,
database:process.env.DB_NAME
};
var sessionStore = new MySQLStore(options);
app.use(session({
secret: 'nodetutorial',
name: 'node-tutorial',
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: { secure: false }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
function(username, password, done) {
console.log(username);
console.log(password);
const db=require('./db.js');
db.query("SELECT user_id,user_name,user_password FROM users WHERE user_email = ?",[username],
function(err,results){
if(err) {done(err)};
//console.log(results.length);
if(results.length == 0){
return done(null,false,{message: 'Invalid UserName Or Password.'});
}
const hash = results[0].user_password;
bcrypt.compare(password,hash,function(err,response){
if(err){ return done(null,false,{message: 'Password Doesnot Matches'})}
return done(null,{user_id: results[0].user_id,user_name: results[0].user_name,user_password: results[0].user_password});
});
}
);
// return done(null, false,);
}
));
//app.engine('html', require('ejs').renderFile);
io.on('connection',function(socket){
const db=require('./db.js');
socket.on('check key',function(id,callback){
db.query("SELECT public_key,private_key FROM user_keys WHERE user_id=?",[id],function(err,result){
if(err) throw err;
if(result.length>0)
{
publicKeys[id]=result[0].public_key;
privateKeys[id]=result[0].private_key;
callback(result);
}
else
{
callback('nodata');
}
});
});
socket.on('set key',function(id,privatekey,publickey,callback){
db.query("INSERT INTO user_keys (`user_id`,`public_key`,`private_key`,`created_on`) VALUES (?,?,?,?)",[id,publickey,privatekey,date.format(new Date(),'YYYY-MM-DD HH:mm:ss')],function(err,result){
if(err) throw err;
publicKeys[id]=publickey;
privateKeys[id]=privatekey;
callback('ok');
});
});
socket.on('add user',function(data,username){
//console.log(session.passport);
// we store the username in the socket session for this client
socket.username = data;
// add the client's username to the global list
//friends[data]=[];
friends=[];
//check friends
db.query("SELECT * FROM friends where (user_id=? OR friend_id=?)",[data,data],function(err,result, fields){
if(err) throw err;
var c= 0;
Object.keys(result).forEach(function(key) {
var row = result[key];
if(row.user_id !=data)
{
friends.push(row.user_id);
//console.log(friends);
}
else{
//console.log(row.friend_id);
friends.push(row.friend_id);
//console.log(friends);
}
});
users[data] = [socket.id,username,publicKeys[data],friends];
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
//console.log(users);
io.emit('updateusers', users);
//console.log(users);
})
});
socket.on('get p key',function(id,callback){
callback(privateKeys[id]);
});
socket.on('chat message',function(socketid,from,to,encmsg,callback){
//console.log(socketid);
//console.log(encmsg);
callback('ok');
db.query("INSERT INTO chat_data (`chat_from`,`chat_to`,`chat_body`,`chat_at`,`chat_read`) VALUES (?,?,?,?,?)",[from,to,encmsg,date.format(new Date(),'YYYY-MM-DD HH:mm:ss'),'0'],function(err,result){
if(err) throw err;
io.to(socketid).emit('chat recieve',from,users[from][1],users[from][0],encmsg);
});
});
///FRIEND REQUEST////
socket.on('friend request',function(user_id,friend_id,sock){
console.log("userdata"+ users[user_id]);
io.to(sock).emit('friend request rec',users[user_id][1],user_id,friend_id);
})
socket.on('friend request acc',function(user_id,friend){
console.log("request:"+users[user_id][3]);
db.query("INSERT INTO friends (`user_id`,`friend_id`,`friend_created_at`) VALUES (?,?,?)",[user_id,friend,date.format(new Date(),'YYYY-MM-DD HH:mm:ss')],function(err,result){
if(err) throw err;
users[user_id][3].push(friend);
users[friend][3].push(user_id);
console.log(users);
});
//users[user_id][3]=friend;
// users[friend][3]=user_id;
io.emit('updateusers', users);
})
///FRIEND REQUEST ENDS////
var path = require('path');
var count = 0;
/***************FILE UPLOADING**************************/
var uploader = new SocketIOFile(socket, {
// uploadDir: { // multiple directories
// music: 'data/music',
// document: 'data/document'
// },
uploadDir: {
music: 'assets/uploads/audio',
image: 'assets/uploads/images',
video: 'assets/uploads/videos'
}, // simple directory
accepts: ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'audio/mp3', 'audio/mpeg', 'video/mp4'], // chrome and some of browsers checking mp3 as 'audio/mp3', not 'audio/mpeg'
maxFileSize: 10242880, // 4 MB. default is undefined(no limit)
chunkSize: 10240, // default is 10240(1KB)
transmissionDelay: 0, // delay of each transmission, higher value saves more cpu resources, lower upload speed. default is 0(no delay)
overwrite: true,
rename: function(filename) {
var file = path.parse(filename);
var fname = file.name;
var ext = file.ext;
return `${fname}_${count++}.${ext}`;
} // overwrite file if exists, default is true.
});
uploader.on('start', (fileInfo) => {
console.log('Start uploading');
console.log(fileInfo);
});
uploader.on('stream', (fileInfo) => {
console.log(`${fileInfo.wrote} / ${fileInfo.size} byte(s)`);
});
uploader.on('complete', (fileInfo) => {
console.log('Upload Complete.');
console.log(fileInfo);
});
uploader.on('error', (err) => {
console.log('Error!', err);
});
uploader.on('abort', (fileInfo) => {
console.log('Aborted: ', fileInfo);
});
/****************FILE UPLOADING ENDS********************/
socket.on('typing',function(msg,sockid,id){
io.to(sockid).emit('recieve typing',msg,id);
});
socket.on('data read',function(to,from,sock){
db.query("UPDATE chat_data SET chat_read='1' WHERE chat_from=? AND chat_to=?",[from,to],function(err,result){
if(err) throw err;
console.log('data read');
io.to(sock).emit('read','ok',to);
});
});
socket.on('get_data',function(id1,id2,sock,callback){
//console.log('ID1:'+id1+' , ID2:'+id2);
db.query("UPDATE chat_data SET chat_read='1' WHERE chat_from=? AND chat_to=?",[id1,id2],function(err,result){
});
//db.query("SELECT chat.* FROM ( SELECT C.chat_id,C.chat_from,C.chat_to,C.chat_at,C.chat_body,C.chat_read,U.user_name AS from_name,UT.user_name AS to_name FROM chat_data AS C JOIN users AS U ON C.chat_from=U.user_id JOIN users AS UT ON C.chat_to=UT.user_id WHERE (C.chat_from=? OR C.chat_from=?) AND (C.chat_to=? OR C.chat_to=?) ORDER BY C.chat_id DESC LIMIT 10) AS chat ORDER BY chat_id",[id1,id2,id1,id2],
db.query("SELECT C.chat_id,C.chat_from,C.chat_to,C.chat_at,C.chat_body,C.chat_read,U.user_name AS from_name,UT.user_name AS to_name FROM chat_data AS C JOIN users AS U ON C.chat_from=U.user_id JOIN users AS UT ON C.chat_to=UT.user_id WHERE (C.chat_from=? OR C.chat_from=?) AND (C.chat_to=? OR C.chat_to=?) ",[id1,id2,id1,id2],
function(err,result){
if(err) throw err;
callback(result,privateKeys[id1],privateKeys[id2]);
});
io.to(sock).emit('read','ok',id2);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete users[socket.username];
// update list of users in chat, client-side
io.emit('updateusers', users);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
require('./router/main_app')(app,date);
http.listen(3000,function(){
console.log('listening on *:3000');
});