-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
345 lines (318 loc) · 10.1 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
var express = require('express');
var session = require('express-session');
var router = require('./app/routes');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var crypto = require('crypto');
var passport = require('passport');
var multer = require('multer');
var fs = require('fs');
var path = require('path');
require('./config/passport')(passport);
var DB_URI = "mongodb://localhost:27017/sea-project";
var app = express();
var http = require('http'); // http module
http.globalAgent.maxSockets = 100;
var server = http.createServer(app); // creating server
var io = require('socket.io'); // using sockets
var ios = io.listen(server); // listening sockets
var formidable = require('formidable'); // file upload module
var util = require('util');
var nickname = [];
var i = [];
var x = [];
var online_member = [];
var temp1;
var socket_id;
var socket_data;
var files_array = [];
var expiryTime = 8;
var routineTime = 1;
// Loading Angular Components ..
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/app/upload/images'));
app.use(express.static(__dirname + '/public/app/upload/music'));
app.use(express.static(__dirname + '/public/app/upload/doc'));
var stripe=require("stripe")("sk_test_gtcTf8YKE9yBoqxAup4XPAfV");
app.set('view engine', 'ejs');
// configure app
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json())
app.use(express.static(__dirname+ '/public'));
app.use(session({secret: 'ADSADS', cookie: { maxAge : 3600000 * 48 }}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(DB_URI);
app.use(router);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
ios.on('connection', function(socket){
// creating new user if nickname doesn't exists
socket.on('new user', function(data, callback){
if(nickname[data.username])
{
callback({success:false});
}else{
callback({success:true});
socket.username = data.username;
socket.userAvatar = data.userAvatar;
nickname[data.username] = socket;
}
});
// sending online members list
socket.on('get-online-members', function(data){
var online_member = [];
i = Object.keys(nickname);
for(var j=0;j<i.length;j++ )
{
socket_id = i[j];
socket_data = nickname[socket_id];
temp1 = {"username": socket_data.username, "userAvatar":socket_data.userAvatar};
online_member.push(temp1);
}
ios.sockets.emit('online-members', online_member);
});
// sending new message
socket.on('send-message', function(data, callback){
if (nickname[data.username]) {
if(data.hasMsg){
ios.sockets.emit('new message', data);
callback({success:true});
}else if(data.hasFile){
if(data.istype == "image"){
socket.emit('new message image', data);
callback({success:true});
} else if(data.istype == "music"){
socket.emit('new message music', data);
callback({success:true});
} else if(data.istype == "PDF"){
socket.emit('new message PDF', data);
callback({success:true});
}
}else{
callback({ success:false});
}
}
});
// disconnect user handling
socket.on('disconnect', function () {
delete nickname[socket.username];
online_member = [];
x = Object.keys(nickname);
for(var k=0;k<x.length;k++ )
{
socket_id = x[k];
socket_data = nickname[socket_id];
temp1 = {"username": socket_data.username, "userAvatar":socket_data.userAvatar};
online_member.push(temp1);
}
ios.sockets.emit('online-members', online_member);
});
});
// route for uploading images asynchronously
app.post('/v1/uploadImage',function (req, res){
var imgdatetimenow = Date.now();
var form = new formidable.IncomingForm({
uploadDir: __dirname + '/public/app/upload/images',
keepExtensions: true
});
form.on('end', function() {
res.end();
});
form.parse(req,function(err,fields,files){
var data = {
username : fields.username,
userAvatar : fields.userAvatar,
repeatMsg : true,
hasFile : fields.hasFile,
isImageFile : fields.isImageFile,
istype : fields.istype,
showme : fields.showme,
dwimgsrc : fields.dwimgsrc,
dwid : fields.dwid,
serverfilename : baseName(files.file.path),
msgTime : fields.msgTime,
filename : files.file.name,
size : bytesToSize(files.file.size)
};
var image_file = {
dwid : fields.dwid,
filename : files.file.name,
filetype : fields.istype,
serverfilename : baseName(files.file.path),
serverfilepath : files.file.path,
expirytime : imgdatetimenow + (3600000 * expiryTime)
};
files_array.push(image_file);
ios.sockets.emit('new message image', data);
});
});
// route for uploading audio asynchronously
app.post('/v1/uploadAudio',function (req, res){
var userName, useravatar, hasfile, ismusicfile, isType, showMe, DWimgsrc, DWid, msgtime;
var imgdatetimenow = Date.now();
var form = new formidable.IncomingForm({
uploadDir: __dirname + '/public/app/upload/music',
keepExtensions: true
});
form.on('end', function() {
res.end();
});
form.parse(req,function(err,fields,files){
console.log("files : ",files);
console.log("fields : ", fields);
var data = {
username : fields.username,
userAvatar : fields.userAvatar,
repeatMsg : true,
hasFile : fields.hasFile,
isMusicFile : fields.isMusicFile,
istype : fields.istype,
showme : fields.showme,
dwimgsrc : fields.dwimgsrc,
dwid : fields.dwid,
serverfilename : baseName(files.file.path),
msgTime : fields.msgTime,
filename : files.file.name,
size : bytesToSize(files.file.size)
};
var audio_file = {
dwid : fields.dwid,
filename : files.file.name,
filetype : fields.istype,
serverfilename : baseName(files.file.path),
serverfilepath : files.file.path,
expirytime : imgdatetimenow + (3600000 * expiryTime)
};
files_array.push(audio_file);
ios.sockets.emit('new message music', data);
});
});
// route for uploading document asynchronously
app.post('/v1/uploadPDF',function (req, res){
var imgdatetimenow = Date.now();
var form = new formidable.IncomingForm({
uploadDir: __dirname + '/public/app/upload/doc',
keepExtensions: true
});
form.on('end', function() {
res.end();
});
form.parse(req,function(err,fields,files){
var data = {
username : fields.username,
userAvatar : fields.userAvatar,
repeatMsg : true,
hasFile : fields.hasFile,
isPDFFile : fields.isPDFFile,
istype : fields.istype,
showme : fields.showme,
dwimgsrc : fields.dwimgsrc,
dwid : fields.dwid,
serverfilename : baseName(files.file.path),
msgTime : fields.msgTime,
filename : files.file.name,
size : bytesToSize(files.file.size)
};
var pdf_file = {
dwid : fields.dwid,
filename : files.file.name,
filetype : fields.istype,
serverfilename : baseName(files.file.path),
serverfilepath : files.file.path,
expirytime : imgdatetimenow + (3600000 * expiryTime)
};
files_array.push(pdf_file);
ios.sockets.emit('new message PDF', data);
});
});
// route for checking requested file , does exist on server or not
app.post('/v1/getfile', function(req, res){
var data = req.body.dwid;
var filenm = req.body.filename;
var dwidexist = false;
var req_file_data;
for(var i = 0; i<files_array.length; i++)
{
if(files_array[i].dwid == data)
{
dwidexist = true;
req_file_data = files_array[i];
}
}
// CASE 1 : File Exists
if(dwidexist == true)
{
//CASE 2 : File Expired and Deleted
if(req_file_data.expirytime < Date.now())
{
var deletedfileinfo = {
isExpired : true,
expmsg : "File has beed removed."
};
fs.unlink(req_file_data.serverfilepath, function(err){
if (err) {
return console.error(err);
}
res.send(deletedfileinfo);
});
var index = files_array.indexOf(req_file_data);
files_array.splice(index,1);
}else{
// CASE 3 : File Exist and returned serverfilename in response
var fileinfo = {
isExpired : false,
filename : req_file_data.filename,
serverfilename : req_file_data.serverfilename };
res.send(fileinfo);
}
}else{
// CASE 4 : File Doesn't Exists.
var deletedfileinfo = {
isExpired : true,
expmsg : "File has beed removed."
};
res.send(deletedfileinfo);
}
});
// Routine Clean up call
setInterval(function() {routine_cleanup();}, (3600000 * routineTime));
// Size Conversion
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
if (i == 0) return bytes + ' ' + sizes[i];
return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
};
//get file name from server file path
function baseName(str)
{
var base = new String(str).substring(str.lastIndexOf('/') + 1);
return base;
}
// Routine cleanup function (files delete after specific interval)
function routine_cleanup()
{
for(var i=0; i<files_array.length; i++)
{
if(Date.now() > files_array[i].expirytime)
{
fs.unlink(files_array[i].serverfilepath, function(err)
{
if (err) {
return console.error(err);
}
});
files_array.splice(i,1);
}
}
};
// start the server
server.listen(8080, function(){
console.log("server is listening on port 8080");
});