const express = require('express'); const router = express.Router(); const webpush = require('web-push'); 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()); var todo = new Todo(body); // tools.mylogshow('ID :', todo._id) // tools.mylogshow('userid', todo.userId, req.user._id) if (!('descr' in req.body)){ return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC }); } 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 }); } tools.mylog('POST ', todo.descr); todo.modified = false; if (!todo.descr) { console.log('RECORD NON VALIDO !?', req.body) } sendNotificationToUser(todo.userId, 'New Todo', 'New Todo added!', '/' + todo.category, 'todo'); todo.save().then((doc) => { // tools.mylogshow('ID SAVED :', doc._id) res.send(doc); }).catch((e) => { console.log(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 }; Subscription.find({userId: userId}, (err, subscriptions) => { if (err) { console.error(`Error occurred while getting subscriptions`); res.status(500).json({ error: 'Technical error occurred' }); } 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: {} }; 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 }); }); }); }); // q.allSettled(parallelSubscriptionCalls).then((pushResults) => { // console.info(pushResults); // }); // res.json({ // data: 'Push triggered' // }); } }); } router.patch('/:id', authenticate, (req, res) => { var id = req.params.id; var body = _.pick(req.body, tools.allfieldTodo()); 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) => { 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; res.send({todo}); }).catch((e) => { res.status(400).send(); }) }); router.get('/:userId', authenticate, (req, res) => { var userId = req.params.userId; // tools.mylogshow('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.mylogshow('todos', todos) res.send({ todos }); }).catch((e) => { console.log(e); res.status(400).send(e); }); }); router.delete('/:id', (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(); } res.send({todo}); }).catch((e) => { res.status(400).send(); }); }); module.exports = router;