217 lines
6.2 KiB
JavaScript
217 lines
6.2 KiB
JavaScript
var os = require("os");
|
|
|
|
require('../models/subscribers');
|
|
|
|
var Url = require('url-parse');
|
|
|
|
const mongoose = require('mongoose');
|
|
const Subscription = mongoose.model('subscribers');
|
|
|
|
const server_constants = require('../tools/server_constants');
|
|
|
|
// SETTINGS WebPush Configuration
|
|
const webpush = require('web-push');
|
|
|
|
const subject = process.env.URLBASE_APP1; //'mailto:' + process.env.EMAIL_FROM
|
|
const publicVapidKey = process.env.PUBLIC_VAPI_KEY;
|
|
const privateVapidKey = process.env.PRIVATE_VAPI_KEY;
|
|
|
|
if (process.env.GCM_API_KEY !== "")
|
|
webpush.setGCMAPIKey(process.env.GCM_API_KEY);
|
|
|
|
webpush.setVapidDetails(subject, publicVapidKey, privateVapidKey);
|
|
console.log('setVapidDetails... config...');
|
|
|
|
|
|
module.exports = {
|
|
getHostname: function () {
|
|
return os.hostname()
|
|
},
|
|
testing: function () {
|
|
return (process.env.TESTING_ON === '1')
|
|
},
|
|
|
|
mylog: function (...args) {
|
|
if (!this.testing())
|
|
console.log(args)
|
|
},
|
|
|
|
mylogoff: function (...args) {
|
|
// doing nothing
|
|
},
|
|
|
|
mylogshow: function (...args) {
|
|
console.log(args)
|
|
},
|
|
|
|
mylogserr: function (...args) {
|
|
console.error(args)
|
|
},
|
|
|
|
allfieldTodo: function () {
|
|
return ['userId', 'pos', 'category', 'descr', 'priority', 'completed', 'created_at', 'modify_at',
|
|
'completed_at', 'expiring_at', 'enableExpiring', 'id_prev', 'progress', 'modified']
|
|
},
|
|
|
|
allfieldTodoWithId: function () {
|
|
return ['_id', ...this.allfieldTodo()]
|
|
},
|
|
|
|
sendBackNotif: function (subscription, payload) {
|
|
|
|
console.log('sendBackNotif:', subscription, payload);
|
|
// Pass object into sendNotification
|
|
webpush.sendNotification(subscription, JSON.stringify(payload)).catch(err => console.error(err))
|
|
.catch(err => {
|
|
if (err.statusCode === 410) {
|
|
// Gone: is not valid anymore (Expired probably!), so I have to delete from my db
|
|
return Subscription.findOneAndRemove({ _id: subscription._id })
|
|
} else {
|
|
console.log('Subscription is no longer valid: ', err);
|
|
}
|
|
})
|
|
},
|
|
|
|
sendNotificationToUser: function (userId, title, content, openUrl, tag) {
|
|
|
|
let 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 conta = 0
|
|
let parallelSubscriptionCalls = subscriptions.map((subscription) => {
|
|
const trovati = subscriptions.length
|
|
return new Promise((resolve, reject) => {
|
|
const pushSubscription = {
|
|
endpoint: subscription.endpoint,
|
|
keys: {
|
|
p256dh: subscription.keys.p256dh,
|
|
auth: subscription.keys.auth
|
|
}
|
|
};
|
|
|
|
conta++;
|
|
|
|
|
|
const parse = require('url-parse');
|
|
const parsedUrl = parse(subscription.endpoint);
|
|
const audience = parsedUrl.protocol + '//' + parsedUrl.hostname;
|
|
|
|
const vapidHeaders = webpush.getVapidHeaders(
|
|
audience,
|
|
process.env.URLBASE_APP1,
|
|
process.env.PUBLIC_VAPI_KEY,
|
|
process.env.PRIVATE_VAPI_KEY,
|
|
'aes128gcm'
|
|
);
|
|
|
|
const pushOptions = {
|
|
vapidDetails: {
|
|
subject: process.env.URLBASE_APP1,
|
|
privateKey: process.env.PRIVATE_VAPI_KEY,
|
|
publicKey: process.env.PUBLIC_VAPI_KEY,
|
|
},
|
|
TTL: payload.ttl,
|
|
headers: vapidHeaders
|
|
};
|
|
|
|
console.log('************ INVIO WEBPUSH.SENDNOTIFICATION N° ', conta, '/', trovati, 'A', subscription.browser);
|
|
console.log('vapidDetails', pushOptions.vapidDetails);
|
|
|
|
payload.title = process.env.URLBASE_APP1 + ' Msg n° ' + conta + '/' + trovati;
|
|
// payload.message += subscription.browser ;
|
|
|
|
const pushPayload = JSON.stringify(payload);
|
|
|
|
console.log('A1) SUBS: pushSubscription', pushSubscription);
|
|
console.log('A2) OPZIONI: pushOptions', pushOptions);
|
|
console.log('A3) MSG_TO_SEND: 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.body)
|
|
});
|
|
});
|
|
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
|
|
// console.info(pushResults);
|
|
// });
|
|
// res.json({
|
|
// data: 'Push triggered'
|
|
// });
|
|
return true;
|
|
}
|
|
});
|
|
|
|
},
|
|
// **********************
|
|
// SORT WITH PREV_ID
|
|
// **********************
|
|
mapSort: function (linkedList) {
|
|
var sortedList = [];
|
|
var map = new Map();
|
|
var currentId = null;
|
|
|
|
// console.log('linkedList', linkedList);
|
|
|
|
// index the linked list by previous_item_id
|
|
for (var i = 0; i < linkedList.length; i++) {
|
|
var item = linkedList[i];
|
|
if (item.id_prev === server_constants.LIST_START) {
|
|
// first item
|
|
currentId = String(item._id);
|
|
// console.log('currentId', currentId);
|
|
sortedList.push(item);
|
|
} else {
|
|
map.set(item.id_prev, i);
|
|
}
|
|
}
|
|
|
|
while (sortedList.length < linkedList.length) {
|
|
// get the item with a previous item ID referencing the current item
|
|
var nextItem = linkedList[map.get(currentId)];
|
|
if (nextItem === undefined)
|
|
break;
|
|
sortedList.push(nextItem);
|
|
currentId = String(nextItem._id);
|
|
}
|
|
|
|
// console.log('DOPO sortedList', sortedList);
|
|
|
|
return sortedList;
|
|
}
|
|
|
|
};
|
|
|