- cleaned some code.
- routing offline - pushNotification
This commit is contained in:
@@ -4,33 +4,81 @@ const mongoose = require('mongoose');
|
||||
const Subscription = mongoose.model('subscribers');
|
||||
const webpush = require('web-push');
|
||||
|
||||
var { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
const isValidSaveRequest = (req, res) => {
|
||||
try {
|
||||
if (!req.body || !req.body.subs.endpoint) {
|
||||
res.status(400);
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.send(JSON.stringify({
|
||||
error: {
|
||||
id: 'no-endpoint',
|
||||
message: 'Subscription must have an endpoint'
|
||||
}
|
||||
}));
|
||||
return false
|
||||
}
|
||||
return true
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
};
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
console.log('req.body.others', req.body.others);
|
||||
|
||||
if (!isValidSaveRequest(req, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let subscriptionModel = new Subscription(req.body.subs);
|
||||
subscriptionModel.userId = req.body.others.userId
|
||||
subscriptionModel.userId = req.body.others.userId;
|
||||
subscriptionModel.access = req.body.others.access;
|
||||
|
||||
subscriptionModel.save((err, subscription) => {
|
||||
if (err) {
|
||||
console.error(`Error occurred while saving subscription. Err: ${err}`);
|
||||
res.status(500).json({
|
||||
error: 'Technical error occurred'
|
||||
// Find if already exist
|
||||
Subscription.findOne( {userId: subscriptionModel.userId, access: subscriptionModel.access})
|
||||
.then(itemsub => {
|
||||
return itemsub
|
||||
})
|
||||
.catch(err => {
|
||||
// Not found
|
||||
return null
|
||||
})
|
||||
.then(myitem => {
|
||||
|
||||
if (myitem === null)
|
||||
myitem = subscriptionModel;
|
||||
|
||||
myitem.save((err, subscription) => {
|
||||
if (err) {
|
||||
console.error(`Error occurred while saving subscription. Err: ${err}`);
|
||||
res.status(500).json({
|
||||
error: 'Technical error occurred'
|
||||
});
|
||||
} else {
|
||||
// Send 201 - resource created
|
||||
// res.status(201).json({ data: 'Subscription saved.' });
|
||||
res.send({ data: 'Subscription saved.' });
|
||||
|
||||
tools.sendBackNotif(subscription, req.body.options)
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Send 201 - resource created
|
||||
res.status(201).json({ data: 'Subscription saved.' });
|
||||
|
||||
sendBackNotif(subscription, req.body.options)
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
router.delete('/del', authenticate, (req, res) => {
|
||||
// tools.mylog("TOKENREM = " + req.token);
|
||||
Subscription.findOneAndRemove( { userId: req.user._id, access: req.access } ).then(() => {
|
||||
res.status(200).send();
|
||||
}, () => {
|
||||
res.status(400).send();
|
||||
});
|
||||
});
|
||||
|
||||
function sendBackNotif(subscription, payload) {
|
||||
|
||||
console.log('payload');
|
||||
// Pass object into sendNotification
|
||||
webpush.sendNotification(subscription, JSON.stringify(payload)).catch(err => console.error(err));
|
||||
|
||||
}
|
||||
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
|
||||
// SETTINGS WebPush Configuration
|
||||
const webpush = require('web-push');
|
||||
|
||||
const publicVapidKey = process.env.PUBLIC_VAPI_KEY;
|
||||
const privateVapidKey = process.env.PRIVATE_VAPI_KEY;
|
||||
webpush.setVapidDetails('mailto:' + process.env.EMAIL_FROM, publicVapidKey, privateVapidKey);
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
@@ -27,11 +34,7 @@ router.post('/', authenticate, (req, res) => {
|
||||
|
||||
// todo.expiring_at = new Date(todo.expiring_at);
|
||||
|
||||
tools.mylogshow('TODO', todo);
|
||||
|
||||
tools.mylog('ID :', todo._id);
|
||||
|
||||
tools.mylog('userid', todo.userId, req.user._id);
|
||||
tools.mylog('ID :', todo._id, todo.descr, todo.userId, req.user._id);
|
||||
|
||||
if (!('descr' in req.body)){
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
||||
@@ -50,14 +53,19 @@ router.post('/', authenticate, (req, res) => {
|
||||
console.log('RECORD NON VALIDO !?', req.body)
|
||||
}
|
||||
|
||||
sendNotificationToUser(todo.userId, 'New Todo', 'New Todo added!', '/' + todo.category, 'todo');
|
||||
|
||||
todo.save().then((writeresult) => {
|
||||
let idobj = writeresult._id;
|
||||
Todo.findById(idobj)
|
||||
.then(record => {
|
||||
tools.mylog('REC SAVED :', record.descr);
|
||||
res.send({record});
|
||||
|
||||
try {
|
||||
sendNotificationToUser(todo.userId, 'Todo: ' + record.descr, record.descr, '/' + todo.category, 'todo');
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
|
||||
})
|
||||
}).catch((e) => {
|
||||
console.log('ERRORE in TODO POST', e.message);
|
||||
@@ -80,7 +88,7 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
|
||||
// tag: req.body.tag
|
||||
};
|
||||
|
||||
Subscription.find({userId: userId}, (err, subscriptions) => {
|
||||
Subscription.find({ userId }, (err, subscriptions) => {
|
||||
if (err) {
|
||||
console.error(`Error occurred while getting subscriptions`);
|
||||
res.status(500).json({
|
||||
@@ -108,6 +116,10 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
|
||||
headers: {}
|
||||
};
|
||||
|
||||
// console.log('pushSubscription', pushSubscription);
|
||||
// console.log('pushOptions', pushOptions);
|
||||
// console.log('pushPayload', pushPayload);
|
||||
|
||||
webpush.sendNotification(
|
||||
pushSubscription,
|
||||
pushPayload,
|
||||
@@ -126,8 +138,7 @@ function sendNotificationToUser(userId, title, content, openUrl, tag) {
|
||||
});
|
||||
});
|
||||
}).catch(error => {
|
||||
console.log('ERROR: sendNotificationToUser', error
|
||||
)
|
||||
console.log('ERROR: sendNotificationToUser', error.data)
|
||||
});
|
||||
});
|
||||
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
|
||||
@@ -154,7 +165,7 @@ router.patch('/:id', authenticate, (req, res) => {
|
||||
|
||||
|
||||
Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
|
||||
tools.mylogshow(' TODO TO MODIFY: ', todo)
|
||||
tools.mylogshow(' TODO TO MODIFY: ', todo.descr, todo.expiring_at);
|
||||
if (!todo) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
@@ -193,7 +204,7 @@ router.get('/:userId', authenticate, (req, res) => {
|
||||
// Extract all the todos of the userId only
|
||||
Todo.findAllByUserId(userId).then((todos) => {
|
||||
|
||||
tools.mylog('todos', todos);
|
||||
tools.mylog('todos', todos.length);
|
||||
|
||||
res.send({ todos: todos });
|
||||
}).catch((e) => {
|
||||
|
||||
@@ -15,6 +15,19 @@ var reg = require('../reg/registration');
|
||||
|
||||
var { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose');
|
||||
const Subscription = mongoose.model('subscribers');
|
||||
|
||||
function existSubScribe(userId, access) {
|
||||
return Subscription.findOne({ userId, access })
|
||||
.then(itemsub => {
|
||||
return itemsub
|
||||
})
|
||||
.catch(err => {
|
||||
return null
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
// POST /users
|
||||
router.post('/', (req, res) => {
|
||||
@@ -90,29 +103,72 @@ router.post('/login', (req, res) => {
|
||||
if (!user) {
|
||||
tools.mylogshow("NOT FOUND !");
|
||||
res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
|
||||
} else {
|
||||
return user.generateAuthToken(req).then((token) => {
|
||||
var usertosend = User();
|
||||
usertosend.username = user.username;
|
||||
usertosend.email = user.email;
|
||||
usertosend.userId = user._id.toHexString();
|
||||
usertosend.verified_email = user.verified_email;
|
||||
}
|
||||
})
|
||||
.then(user => {
|
||||
let mytoken = '';
|
||||
return user.generateAuthToken(req).then((token) => {
|
||||
var usertosend = User();
|
||||
usertosend.username = user.username;
|
||||
usertosend.email = user.email;
|
||||
usertosend.userId = user._id.toHexString();
|
||||
usertosend.verified_email = user.verified_email;
|
||||
|
||||
// tools.mylog("user.verified_email:" + user.verified_email);
|
||||
tools.mylog("usertosend.userId", usertosend.userId);
|
||||
// tools.mylog("user.verified_email:" + user.verified_email);
|
||||
tools.mylog("usertosend.userId", usertosend.userId);
|
||||
|
||||
// tools.mylog("usertosend:");
|
||||
// tools.mylog(usertosend);
|
||||
res.header('x-auth', token).send({usertosend, code: server_constants.RIS_CODE_OK});
|
||||
// tools.mylog("usertosend:");
|
||||
// tools.mylog(usertosend);
|
||||
return usertosend
|
||||
})
|
||||
.then((usertosend) => {
|
||||
const useragent = req.get('User-Agent');
|
||||
const access = 'auth ' + useragent;
|
||||
// if (usertosend.tokens.length > 0)
|
||||
// access = usertosend.tokens[usertosend.tokens.length - 1].access;
|
||||
|
||||
return existSubScribe(usertosend.userId, access)
|
||||
.then(subscribe => {
|
||||
if (subscribe === null) {
|
||||
// Doesn't exist, so save sub passed in INPUT
|
||||
let subscriptionModel = new Subscription(req.body.subs);
|
||||
subscriptionModel.userId = usertosend._id;
|
||||
subscriptionModel.access = access;
|
||||
|
||||
return subscriptionModel.save((err, subscription) => {
|
||||
if (err) {
|
||||
console.error(`Error occurred while saving subscription. Err: ${err}`);
|
||||
res.status(500).json({
|
||||
error: 'Technical error occurred'
|
||||
});
|
||||
} else {
|
||||
// Send 201 - resource created
|
||||
// res.status(201).json({ data: 'Subscription saved.' });
|
||||
// res.send({ data: 'Subscription saved.' });
|
||||
|
||||
tools.sendBackNotif(subscription, req.body.options)
|
||||
}
|
||||
|
||||
return { usertosend }
|
||||
});
|
||||
} else {
|
||||
return { usertosend }
|
||||
}
|
||||
});
|
||||
})
|
||||
.then((usertosend) => {
|
||||
console.log('res', mytoken, usertosend);
|
||||
|
||||
res.header('x-auth', mytoken).send({ usertosend, code: server_constants.RIS_CODE_OK });
|
||||
// tools.mylog("TROVATOOO!");
|
||||
|
||||
tools.mylog('FINE LOGIN')
|
||||
});
|
||||
}
|
||||
}).catch((e) => {
|
||||
tools.mylog("ERRORE IN LOGIN: " + e);
|
||||
res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
||||
});
|
||||
})
|
||||
.catch((e) => {
|
||||
tools.mylog("ERRORE IN LOGIN: " + e);
|
||||
res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
||||
});
|
||||
});
|
||||
|
||||
router.delete('/me/token', authenticate, (req, res) => {
|
||||
|
||||
Reference in New Issue
Block a user