-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
574 lines (548 loc) · 16.8 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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
"use strict";
const express = require('express');
const path = require('path');
const favicon = require('static-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const childProcess = require('child_process');
const config = require('./config');
const rp = require('request-promise');
//impotrt from somewhere
var admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert(config.firebase_config.serviceAccount),
databaseURL: "https://admin-notifications-7d944.firebaseio.com"
});
const dbInit = require('./utils/dbInit');
dbInit();
const Notification = require('./models/Notification');
const Constant = require('./models/Constant');
const User = require('./models/User');
const secretString = "I_am_aw3sOme";
const app = express();
const fs = require('fs');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
limit: '50mb'
}));
app.use(cookieParser());
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
let name = req.headers['x-nitt-app-username']; //change as per needs
if(!name){
res.json({success: false, message: "Pass proper params!"});
}else{
User.findOne({
name
}, function(err, data){
if(err){
console.log(err);
}else{
let isAdmin = (req.headers['x-nitt-app-is-admin'] === "true");
Constant.findOne({
key: "categories"
})
.then(constant => {
console.log(constant);
let categories = !constant || constant.values === '' ? [] : constant.values;
if(data){
//res.render('index', {isAdmin: req.body.X_USER_IS_ADMIN});
res.render('index', {
isAdmin,
url: config.url,
port: config.port,
categories,
firstTime: false
});
}else{
let user = new User({
name,
muted_topics: []
});
user.save(err => {
if(err) console.log(err); //send error page here
res.render('index', {
isAdmin,
url: config.url,
port: config.port,
categories,
firstTime: true
});
})
}
})
.catch(err => {
console.log(err);
res.json({success: false, message: "Server Error"});
})
}
})
}
})
app.use(express.static('public'));
app.get('/get_notifications', (req, res) => {
//console.log(req.body);
//console.log(req.headers['x-nitt-app-username']);
Notification.find({
$or:[
{status: true, to : ''},
{status: false, to: req.headers['x-nitt-app-username']}
]
}, (err, notifications) => {
res.json({
success: true,
notifications: notifications
});
});
});
app.get('/muted_categories', (req, res) => {
let name = req.headers['x-nitt-app-username'];
if(!name){
return res.json({success: false, message: "Pass proper params"});
}
User.findOne({
name
}, (err, data)=>{
if(err){
console.log(err);
res.json({success: false, message: "Internal Server Error"});
}else{
res.json({success: true, muted_topics: !data ? [] : data.muted_topics})
}
})
});
app.post('/mute', (req, res) => {
let name = req.headers['x-nitt-app-username'];
let topic = req.body.topic;
console.log(name, topic, req.headers, req.body);
if(!name || !topic){
console.log('hey');
return res.json({success: false, message: "Pass proper params"});
}
User.findOne({
name
}, function(err, data){
if(err){
console.log(err);
res.json({success: false, message: "Internal Server Error"});
}else{
if(data){
data.muted_topics.push(topic);
data.save(function(err, saved){
if(err){
console.log(err);
res.json({success: false, message: "Internal Server Error"});
}else{
//subscribe user to a specific topic
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
data.device_token
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
admin.messaging().unsubscribeFromTopic(registrationTokens, topic)
.then(function(response) {
console.log('Successfully subscribed to topic:', response);
res.json({success: true, message: "Preference saved!"});
})
.catch(function(error) {
console.log('Error subscribing to topic:', error);
});
}
})
}else{
res.json({success: false, message: 'User Not found!'});
}
}
});
});
app.post('/unmute', function(req, res){
let name = req.headers['x-nitt-app-username'];
let topic = req.body.topic;
User.findOne({
name
}, function(err, data){
if(err){
console.log(err);
res.json({success: false, message: "Internal Server Error"});
}else{
if(data){
let topicIndex = data.muted_topics.indexOf(topic);
if(topicIndex === -1){
return res.json({success: false, message: "Topic not muted!"});
}else{
data.muted_topics.splice(topic, 1);
}
data.save(function(err, saved){
if(err){
console.log(err);
res.json({success: false, message: "Internal Server Error"});
}else{
//unsubscribe user from a specific topic
const registrationTokens = [
data.device_token
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
admin.messaging().unsubscribeFromTopic(registrationTokens, topic)
.then(function(response) {
res.json({success: true, message: "Preference saved!"});
console.log('Successfully subscribed to topic:', response);
})
.catch(function(error) {
console.log('Error subscribing to topic:', error);
});
}
})
}
}
});
})
app.post('/add_admin', (req, res) => {
let name = req.body.name;
let username = req.body.username;
Constant.findOne({key: "admins"}, (err, constant) => {
if(err) return res.json({success: true, message : "Internal Server Error"});
if(constant){
let admins = constant.values || [];
if(admins.findIndex(value => value.username === username) != -1){
return res.json({success: false, message: "User is already admin"});
}
admins.push({name, username});
constant.values = admins;
constant.save((err, saved) => {
if(err){
return res.json({success: true, message : "Internal Server Error"});
}else{
res.json({success: true, message: "Admin added"});
}
})
}else{
res.json({success: true, message: 'sd'});
//handle later the case when admins document doesn't exist at all
}
})
})
app.post('/remove_admin', (req, res) => {
let name = req.body.name;
let username = req.body.username;
Constant.findOne({key: "admins"}, (err, constant) => {
if(err) return res.json({success: true, message : "Internal Server Error"});
if(constant){
let admins = constant.values || [];
if(admins.findIndex(value => value.username === username) === -1){
return res.json({success: false, message: "User doesn\'t exist"});
}
admins.splice(admins.indexOf({name, username}), 1);
constant.values = admins;
constant.save((err, saved) => {
if(err){
return res.json({success: true, message : "Internal Server Error"});
}else{
res.json({success: true, message: "Admin removed"});
}
})
}else{
//handle later the case when admins document doesn't exist at all
res.json({success: false, message: "User doesn\'t exist!"});
}
})
})
app.get('/floating_tokens', (req, res) => {
if(req.headers['x-nitt-app-is-admin'] === "false"){
return res.json({success: true, message: "You aren\'t authorized to come here"});
}
Notification.find({status: false, to:'' }, (err, notifications) => {
if(err) return res.json({success: false, message: "Internal Server Error"});
res.json({success: true, notifications});
})
})
app.post('/notification_token', (req, res) => {
let title = req.body.title;
let description = req.body.description;
let category = req.body.category;
if (!(title && description && category)) {
res.json({
success: false,
message: 'Send proper parameters'
});
}else{
Notification.create({
title,
description,
category,
status: 0,
to: '',
author: req.headers['x-nitt-app-username']
}, (err, data) => {
res.json({success: true, message: 'Notification requested!'});
Constant.findOne({key: "admins"}, (err, constant) => {
let admins = constant.values;
console.log(admins);
let notifications = [];
for(var i=0; i< admins.length; i++){
console.log(admins[i]);
let notificationTemplate = {
title: 'Notification Request',
description: `${req.headers['x-nitt-app-name']} requested to add a notification, head to dashboard to approve it!`,
category: 'general', //?
to: admins[i],
author: '',
status: false
};
notifications.push(notificationTemplate);
}
Notification.create(notifications, function(err, notificationsCreated){
if(err){
console.log(err);
}
})
});
console.log(err, data);
});
}
})
app.post('/approve_token', (req, res) => {
let id = req.body.notif_id;
Notification.findById(id, (err, notification) => {
notification.status = 1;
notification.to = '';
notification.save(function(err, saved){
if(err) res.json({success: false, message: "Internal Server Error"});
else res.json({success: true, message: "approved"});
});
addNotificationToFirebase(notification);
User.findOne({username: notification.author}, function(err, user){
if(err){console.log(err);}
addNotificationToUser(notification, user.token);
})
//add notification to group
//send individual notification to user
})
})
app.post('/discard_token', (req, res) => {
let id = req.body.notif_id;
Notification.deleteOne({_id: id}, (err, success) => {
res.json({success: true, message: 'Deleted'});
//send reject notification to user
});
})
app.post('/notification', (req, res) => {
if(req.headers['x-nitt-app-is-admin'] === "false"){
return res.json({success: false, message: "Only admins can post notifications!"});
}
let title = req.body.title;
let description = req.body.description;
let category = req.body.category;
if (!(title && description && category)) {
res.json({
success: false,
message: 'Send proper parameters'
});
}else{
//add notification to firebase
const notification = {
title,
description,
category,
status: 1,
to: '',
author: req.headers['x-nitt-app-username']
};
Notification.create(notification, (err, data) => {
res.json({success: true, message: 'Notification added!'})
addNotificationToFirebase(notification);
var message = {
data: {
score: '850',
time: '2:45'
},
token: "daIshKnLqzw:APA91bEz0t2qOu0VjXhauadLYuUt7pJHjgqj7PIc0steLwpJx23qrCJBSf18wm4dPbA5WnWrwCRUAYygP0L5St4mo-rMh9ouMe8dkFPXv-x4T6s3waztDGsMo7o4ZhsguHyD3Fsm1i4W"
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
console.log(err, data);
});
}
});
app.post('/category', (req, res) => {
//subscribe everyone to this category
let name = req.body.name
if (!name) {
res.json({
success: false,
message: "Pass with appropriate parameters!"
});
}
Constant.findOne({
key: 'categories'
}, function (err, data) {
console.log(data);
//handle error
if (err) {
console.log(err);
return res.json({
success: false,
message: 'Server error!'
})
}
data = data && data.values ? data : new Constant({ key: "categories", values: [] });
data.values.push(name);
data.save((err) => {
if (err) {
console.log(err);
return res.json({
success: false,
message: 'Internal Server Error'
});
} else {
return res.json({
success: true,
message: 'Category Added!'
})
}
})
});
});
app.get('/categories', (req, res) => {
Constant.find({
key: "categories"
}, function (err, data) {
if (err) {
res.json({
success: false,
message: 'Internal Server Error'
});
} else {
data = (data && data.length) ? data[0].values : [];
res.json({success: true, categories: data});
}
})
})
app.post('/subscribe_all', function(req, res){
Constant.find({
key: "categories"
}, function (err, data) {
if (err) {
res.json({
success: false,
message: 'Internal Server Error'
});
} else {
User.findOne({
name:req.headers['x-nitt-app-username']
}, function(err, user){
if(err){
console.log(err);
}
if(user.device_token == req.body.token){
return res.json({success: true, message: "No update required for now!"});
}else{
User.update({
name:req.headers['x-nitt-app-username']
},{
device_token: req.body.token
}, (err, user) => {
if(!err){
data = (data && data.length) ? data[0].values : [];
// These registration tokens come from the client FCM SDKs.
let registrationTokens = [
user.admin_token
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
let promisesP = [];
for(let i=0; i<data.length; i++){
//subscribe to each topic
let x = admin.messaging().subscribeToTopic(registrationTokens, data[i])
.then(function(response) {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully subscribed to topic:', response);
})
.catch(function(error) {
console.log('Error subscribing to topic:', error);
});
promisesP.push(x);
}
Promise.all(promisesP)
.then(data => {
console.log("First handler", data);
})
.catch(err => {
console.log("Error", err);
});
//wait for promises to resolve
//following response is dummy
res.json({success: true})
}
})
}
})
}
})
})
app.post('/notify', (req, res) => {
//notify to firebase
});
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
const err = new Error('Not Found');
err.status = 404;
console.log(err);
next(err);
});
app.listen(3002);
function addNotificationToFirebase(notification){
//` The topic name can be optionally prefixed with "/topics/".
var topic = notification.category;
// See documentation on defining a message payload.
var message = {
data: {
topic,
title: notification.title,
description: notification.description
},
topic
};
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
}
function addNotificationToUser(notification, token){
var topic = notification.category;
var message = {
data: {
topic,
title: notification.title,
description: notification.description
},
token
};
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
}