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'); var { authenticate } = require('../middleware/authenticate'); var mongoose = require('mongoose'); const Subscription = mongoose.model('subscribers'); var { Todo } = require('../models/todo'); const _ = require('lodash'); const { ObjectID } = require('mongodb'); router.post('/', authenticate, (req, res) => { var body = _.pick(req.body, tools.allfieldTodoWithId()); tools.mylogshow('INPUT', body); var todo = new Todo(body); // todo.expiring_at = new Date(todo.expiring_at); 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 }); } if (String(todo.userId) !== String(req.user._id)) { // I'm trying to write something not mine! tools.mylog('todo.userId = ', todo.userId, 'req.user._id', req.user._id) return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); } tools.mylog('TODO POST :', todo.descr, todo._id); todo.modified = false; if (!todo.descr) { console.log('RECORD NON VALIDO !?', req.body) } todo.save().then((writeresult) => { let idobj = writeresult._id; Todo.findById(idobj) .then(record => { tools.mylog('REC SAVED :', record.descr); sendNotificationToUser(todo.userId, 'Todo: ' + record.descr, record.descr, '/todo/' + todo.category, 'todo') .then(ris => { if (ris) { res.send({ record }); } else { // already sent the error on calling sendNotificationToUser } }) }) }).catch((e) => { console.log('ERRORE in TODO POST', e.message); res.status(400).send(e); }); }); function sendNotificationToUser(userId, title, content, openUrl, tag) { const payload = { title: title, message: content, url: openUrl, tag, // ttl: req.body.ttl, // icon: req.body.icon, // image: req.body.image, // badge: req.body.badge, // tag: req.body.tag }; return Subscription.find({ userId }, (err, subscriptions) => { if (err) { console.error(`Error occurred while getting subscriptions`); res.status(500).json({ error: 'Technical error occurred' }); return false; } else { let parallelSubscriptionCalls = subscriptions.map((subscription) => { return new Promise((resolve, reject) => { const pushSubscription = { endpoint: subscription.endpoint, keys: { p256dh: subscription.keys.p256dh, auth: subscription.keys.auth } }; const pushPayload = JSON.stringify(payload); const pushOptions = { vapidDetails: { subject: process.env.URLBASE_APP1, privateKey: process.env.PRIVATE_VAPI_KEY, publicKey: process.env.PUBLIC_VAPI_KEY, }, TTL: payload.ttl, headers: {} }; // console.log('pushSubscription', pushSubscription); // console.log('pushOptions', pushOptions); // console.log('pushPayload', pushPayload); webpush.sendNotification( pushSubscription, pushPayload, pushOptions ).then((value) => { resolve({ status: true, endpoint: subscription.endpoint, data: value }); }).catch((err) => { reject({ status: false, endpoint: subscription.endpoint, data: err }); }); }).catch(error => { console.log('ERROR: sendNotificationToUser', error.data) }); }); // q.allSettled(parallelSubscriptionCalls).then((pushResults) => { // console.info(pushResults); // }); // res.json({ // data: 'Push triggered' // }); return true; } }); } router.patch('/:id', authenticate, (req, res) => { var id = req.params.id; var body = _.pick(req.body, tools.allfieldTodo()); tools.mylogshow('PATCH TODO: ', id) if (!ObjectID.isValid(id)) { tools.mylog('ERROR: id not VALID', id); return res.status(404).send(); } Todo.findByIdAndUpdate(id, { $set: body }, { new: true }).then((todo) => { tools.mylogshow(' TODO TO MODIFY: ', todo.descr, todo.expiring_at); if (!todo) { return res.status(404).send(); } if (todo.userId !== String(req.user._id)) { // I'm trying to write something not mine! return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); } todo.modified = false; tools.mylog('PATCH ', todo.descr, todo._id); res.send({ todo }); }).catch((e) => { tools.mylogserr('Error patch TODO: ', e); res.status(400).send(); }) }); router.get('/:userId', authenticate, (req, res) => { var userId = req.params.userId; tools.mylog('GET : ', req.params); if (!ObjectID.isValid(userId)) { return res.status(404).send(); } if (userId !== String(req.user._id)) { // I'm trying to write something not mine! return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); } // Extract all the todos of the userId only Todo.findAllByUserId(userId).then((todos) => { tools.mylog('todos', todos.length); res.send({ todos: todos }); }).catch((e) => { console.log(e); res.status(400).send(e); }); }); router.delete('/:id', authenticate, (req, res) => { var id = req.params.id; if (!ObjectID.isValid(id)) { return res.status(404).send(); } Todo.findByIdAndRemove(id).then((todo) => { if (!todo) { return res.status(404).send(); } tools.mylog('DELETED ', todo.descr, todo._id); res.send({ todo }); }).catch((e) => { res.status(400).send(); }); }); module.exports = router;