forked from kat09kat09/GigRTC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
559 lines (413 loc) · 15.2 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
var path = require('path');
var url = require('url');
var express = require('express');
var fs = require('fs');
var https = require('https');
var http = require('http');
var path = require('path');
var bcrypt = require('bcrypt-nodejs');
var CONFIG = require('./config.js')
var favicon = require('serve-favicon');
var db = require('./db/config');
var Users = require('./db/collections/users');
var User = require('./db/models/user');
var Artists = require('./db/collections/artists');
var Artist = require('./db/models/artist');
var Tags = require('./db/collections/tags');
var Tag = require('./db/models/tag');
var Performances = require('./db/collections/performances');
var Performance = require('./db/models/performance');
var Artist_User = require('./db/models/artist_user')
var options = {
key: fs.readFileSync('keys/server.key'),
cert: fs.readFileSync('keys/server.crt')
};
var app = express();
var port = 1338;
var server = https.createServer(options, app)
var io= require('socket.io').listen(server);
server.listen(port, function() {
console.log(`Running on port: ${port}`);
});
app.get('/populateDatabase',
function(req, res) {
var testUser = new User({
username: 'Jane Bond',
admin: true
});
var testPerf = new Performance({
room: 'Jim Bob Burshea',
title: 'Jimbo sings the blues',
short_description: 'My blues are outta control'
});
var testTag = new Tag({
tagname: 'doo wop'
});
// change testPerf to whatever database table you want to add a row to each time you go to /populateDatabase
testPerf.save()
.then(function(newEntry) {
// change Performances to the table you want to populate
Performances.add(newEntry);
res.status(200).send(newEntry);
})
.catch(function(err) {
console.error(err);
});
}
);
///////////////////////////////////////////////\
var jwt = require('jsonwebtoken');
var expressJWT = require('express-jwt')
var bodyParser = require('body-parser');
var passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy
, GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
app.use(favicon(__dirname + '/client/public/img/favicon.png'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use('/',express.static(path.join(__dirname, 'client')));
app.use(expressJWT({secret : CONFIG.JWT_SECRET}).unless({path : ['/',/^\/auth\/.*/,'/authenticateFacebook','/about', /^\/api\/.*/, /^\/api\/messages\/.*/,/^\/activeStream\/.*/, /^\/public\/.*/, /^\/router\/.*/]}));
app.post('/auth/signIn/', (req, res) => {
new Artist({user_name: req.body.user_name}).fetch().then(function(found){
if(found){
var check = bcrypt.compareSync(req.body.password, found.get('password'))
if (check){
var myToken = jwt.sign({user_name:found.get('email_id')},CONFIG.JWT_SECRET)
res.status(200).json({token: myToken, artist_details : found});
}
else {
res.sendStatus(403).json({status : 'Incorrect password'});
}
}
else {
res.sendStatus(403).json({status : 'User does not exist, please sign up'});
}
});
});
app.post('/auth/signUp/', (req, res) => {
new Artist({user_name: req.body.user_name, password: req.body.password}).fetch().then(function (found) {
if (found) {
res.status(403);
}
else {
var newArtist = new Artist({
user_name: req.body.user_name,
password: req.body.password,
email_id: req.body.email_id,
brief_description: req.body.brief_description,
user_image: req.body.user_image,
display_name: req.body.display_name,
genre: req.body.genre
});
newArtist.save().then(function (artist) {
Artists.add(artist);
var myToken = jwt.sign({user_name: req.body.email_id}, CONFIG.JWT_SECRET)
res.status(200).json({token: myToken, artist_details: artist});
})
}
});
new Performance({active: false, room: req.body.user_name})
.save()
});
app.get('/getData/', (req, res) => {
res.status(200)
.json({data: 'Valid JWT found! This protected data was fetched from the server.'});
})
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new FacebookStrategy({
clientID: CONFIG.FB_CLIENT_ID,
clientSecret: CONFIG.FB_APP_SECRET,
callbackURL: CONFIG.FB_CALL_BACK,
profileFields: ['id','email', 'displayName', 'photos']
},
function(accessToken, refreshToken, profile, done) {
new User({facebook_id : profile.id}).fetch().then(function(response){
if(response){
return done(null,response.attributes)
}
else{
var facebookUser = new User({
facebook_id : profile.id,
email_id : profile.emails[0].value ? profile.emails[0].value : profile.displayName,
display_name : profile.displayName,
user_image : profile.photos[0].value
})
facebookUser.save().then(function(newFacebookUser) {
Users.add(newFacebookUser);
return done(null,newFacebookUser)
});
}
});
}
));
passport.use(new GoogleStrategy({
clientID: CONFIG.G_CLIENT_ID,
clientSecret: CONFIG.G_APP_SECRET,
callbackURL: CONFIG.G_CALL_BACK
},
function(accessToken, refreshToken, profile, done) {
new User({google_id : profile.id}).fetch().then(function(response){
if(response){
return done(null,response.attributes)
}
else{
var googleUser = new User({
google_id : profile.id,
email_id : profile.emails[0].value ? profile.emails[0].value : profile.displayName ,
display_name : profile.displayName,
user_image : profile.photos[0].value
})
googleUser.save().then(function(newGoogleUser) {
Users.add(newGoogleUser);
return done(null,newGoogleUser)
});
}
});
}
));
app.use(passport.initialize());
app.get('/auth/facebook/',
passport.authenticate('facebook',{scope : 'email'}));
var current_token;
var current_user;
app.get('/auth/facebook/callback/',
passport.authenticate('facebook', { failureRedirect: '/' }),
function(req, res) {
current_user = req.user;
current_token = jwt.sign({user_name: (req.user.email_id ) },CONFIG.JWT_SECRET);
res.redirect('/router/socialLogin')
}
);
app.get('/auth/google/',
passport.authenticate('google',{scope : 'email'}));
app.get('/auth/google/callback/',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
current_user = req.user;
current_token = jwt.sign({user_name: (req.user.email_id ) },CONFIG.JWT_SECRET);
res.redirect('/router/socialLogin')
}
);
app.get('/auth/validateSocialToken',(req, res) => {
res.json({token: current_token, user_details : current_user});
});
/////////////////ACTIVE STREAM//////////
app.put('/api/describe/', (req, res) => {
Performance.where({ room: req.body.room }).fetch().then(function(updatedPerf){
updatedPerf.save({
long_description: req.body.long_description,
performance_image: req.body.performance_image,
rated_r: JSON.parse(req.body.rated_r),
short_description: req.body.short_description,
title: req.body.title
}, {patch: true})
.then(function(perf) {
Performances.add(perf);
var responseObject = {
title: perf.get('title'),
short_description: perf.get('short_description'),
long_description: perf.get('long_description'),
performance_image: perf.get('performance_image')
};
res.status(200).json(responseObject); // this object is returned to the client
});
});
});
app.put('/api/activeStreams', function(req, res){
Performance.where({ room: req.body.room }).fetch()
.then(performance => {
performance.save({active: req.body.active}, {patch: true});
res.json({active : req.body.active})
})
});
app.get('/api/activeStreams', function(req, res) {
Performances
// .query({where: {active: true}})
.fetch({withRelated:['tags']}).then(function (performances) {
res.status(200).send(performances.models);
});
});
app.get('/api/allStreams', function(req, res) {
Performances
.fetch().then(function (performances) {
res.status(200).send(performances.models);
});
});
app.put('/api/updatePerformanceViewCount', function(req, res) {
Performance.forge({room: req.body.room})
.fetch({require: true})
.then((performance)=>{
performance.save({
number_of_viewers : performance.get('number_of_viewers') + 1
})
res.json({views : (performance.get('number_of_viewers') + 1)})
})
});
app.get('/api/currentViewers', function(req, res) {
Performances.query({where: {room: req.body.room}}).fetch().then(function (performance) {
res.status(200).json({views : performance.get('number_of_viewers')});
});
});
//*********Tags
app.post('/api/addTag', function (req,res){
var tagName= req.body.tagname;
var userId= req.body.user_Id;
var performanceId= req.body.performanceId;
Tag.where({ tagname: tagName }).fetch()
.then(tag => {
if(tag) {
Performance.where({id: performanceId}).fetch()
.then(performance => {
performance.tags().attach(tag.id);
res.status(200).send({tagname: null, performanceId: performanceId}); //return nothing if tag is already in db
})
} else {
var newTag= new Tag({
tagname: tagName,
user_id: userId
})
newTag.save().then (function (tag){
Tags.add(tag);
Performance.where({id: performanceId}).fetch()
.then(performance => {
performance.tags().attach(tag.id);
res.status(200).send({tagId: tag.id, tagname: tag.attributes.tagname, performanceId: performanceId}); //return the performance with updated tags
})
})
}
})
});
//**********RETOKENIZE LOGIN
app.get('/auth/getTokenizedUserDetails',(req,res)=>{
Artist.query({where: {email_id: req.query.email}}).fetch().then(function(found){
if(found){
var myToken = jwt.sign({user_name:found.get('email_id')},CONFIG.JWT_SECRET)
res.status(200).json({token: myToken, artist_details : found});
}
else {
User.query({where: {email_id: req.query.email}}).fetch().then(function(response){
if(response){
res.status(200).json({token: myToken, artist_details : response});
}
else{
res.status(404).json({status : 'User does not exist, please sign up'});
}
});
}
});
})
//**************UPLOAD IMAGE************************
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: CONFIG.CLOUD_NAME,
api_key: CONFIG.CLOUD_API_KEY,
api_secret: CONFIG.CLOUD_API_SECRET
});
app.post('/api/uploadImage',function(req,res){
cloudinary.uploader.upload(req.body.image,{tags:'basic_sample'})
.then(function(image){
res.json({url : image.url})
})
});
//********* Fetch all registered users
app.get('/api/allRegisteredArtists',function(req,res){
new Artist().fetchAll().then((allArtists)=>{
res.status(302).json({registeredArtists : allArtists.models})
})
})
//***************** Create Artist User Relation
app.post('/api/subscribeToArtist',function(req,res){
var data = req.body;
new Artist_User({
artist_id: data.artist_id,
user_id: data.user_id
})
.save()
.then(function(data){
res.json({data : 'Subscribed successfully'});
})
})
//************** Get all artist subscribers
app.get('/api/emailAllSubscribers',function(req,res){
var data = []
Artist_User.query({where: {artist_id :req.query.artist_id }}).fetchAll().then(function(emails){
emails.models.map(function(user_id){
User.query({where : {id : user_id.attributes.user_id}}).fetch().then(function(model){
sendEmailTo(model.get('email_id'),req.query.artist_name,req,res)
})
})
});
res.json("EMAIL SENDING")
});
//************NODE EMAIL
var emailJS = require('emailjs/email')
var sendmail = emailJS.server.connect({
user: CONFIG.G_MAIL_ADDRESS,
password: CONFIG.G_PASSWORD,
host: "smtp.gmail.com",
ssl: true
});
function sendEmailTo (email_id,artist_name,req,res){
var message = {
from: "GIGG.TV <[email protected]>",
to: "User <" + email_id + ">",
subject: artist_name + " IS LIVE NOW!",
text: "Click on gigg.tv/router/activeStream/" + artist_name + " . Join in for a good time"
};
sendmail.send(message, function (err, message) {
var body = null;
if (err) {
body = err.toString();
} else {
console.log("EMAIL SENT IN SERVER")
}
});
}
//******* Test Chat **************
//set env vars
// var mongoose= require('mongoose');
// process.env.MONGOLAB_URI = process.env.MONGOLAB_URI || 'mongodb://localhost/chat_dev';
// process.env.PORT = process.env.PORT || 3000;
// connect our DB
// mongoose.connect(process.env.MONGOLAB_URI);
//load routers
var messageRouter = express.Router();
require('./server/routes/message_routes.js')(messageRouter);
app.use('/api', messageRouter);
var socketioJwt= require('socketio-jwt');
io.set('transports', ["websocket", "polling"]);
io.on('connection', function (socket){
socket.join('Lobby');
socket.on('chat mounted', function(user) {
// TODO: Does the server need to know the user?
socket.emit('receive socket', socket.id)
})
socket.on('leave channel', function(channel) {
socket.leave(channel)
})
socket.on('join channel', function(channel) {
socket.join(channel.name)
})
socket.on('new message', function(msg) {
socket.broadcast.to(msg.channelID).emit('new bc message', msg);
});
socket.on('new channel', function(channel) {
socket.broadcast.emit('new channel', channel)
});
socket.on('typing', function (data) {
socket.broadcast.to(data.channel).emit('typing bc', data.user);
});
socket.on('stop typing', function (data) {
socket.broadcast.to(data.channel).emit('stop typing bc', data.user);
});
});
//********* End Test Chat **********
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'client', 'index.html'))
})
module.exports.server = server;