This repository has been archived by the owner on Sep 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender.js
94 lines (81 loc) · 2.6 KB
/
sender.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
// const workerpool = require('workerpool');
// const webpush = require('web-push');
const url = require('url');
const https = require('https');
// const vapid = require('./secrets/vapid.js');
const encryptionHelper = require('./node_modules/web-push/src/encryption-helper.js');
// const webPushConstants = require('./node_modules/web-push/src/web-push-constants.js');
const vapidHelper = require('./node_modules/web-push/src/vapid-helper.js');
async function sendNotification(
subscription, payload,
vapid, options
) {
// var time = Date.now();
var encoding = 'aes128gcm';
const urlParts = url.parse(subscription.endpoint);
const audience = urlParts.protocol + '//'
+ urlParts.host;
// console.log(vapid.subject);
let requestDetails = {
method: 'POST',
headers: {
TTL: 2419200,
'Content-Length': 0,
'Content-Type': 'application/octet-stream',
'Content-Encoding': encoding,
'Connection': 'close',
Authorization: vapidHelper.getVapidHeaders(
audience,
vapid.subject,
vapid.publicKey,
vapid.privateKey,
encoding
).Authorization
},
endpoint: subscription.endpoint
};
if (payload) {
const encrypted = encryptionHelper.encrypt(
subscription.keys.p256dh,
subscription.keys.auth,
payload,
requestDetails.headers["Content-Encoding"]
);
requestDetails.headers['Content-Length'] = encrypted.cipherText.length;
requestDetails.body = encrypted.cipherText;
};
// try {
// requestDetails = webpush.generateRequestDetails(subscription, payload, options);
// // console.log(requestDetails);
// } catch (err) {
// }
const httpsOptions = {};
httpsOptions.hostname = urlParts.hostname;
httpsOptions.port = urlParts.port;
httpsOptions.path = urlParts.path;
httpsOptions.headers = requestDetails.headers;
httpsOptions.method = requestDetails.method;
// requestDetails.timeout = httpsOptions.timeout = 1000;
if (requestDetails.agent) {
httpsOptions.agent = requestDetails.agent;
}
if (requestDetails.proxy) {
const HttpsProxyAgent = require('https-proxy-agent'); // eslint-disable-line global-require
httpsOptions.agent = new HttpsProxyAgent(requestDetails.proxy);
}
const pushRequest = https.request(httpsOptions, () => {
pushRequest.destroy();
});
if (requestDetails.timeout) {
pushRequest.on('timeout', function () {
pushRequest.destroy();
});
}
if (requestDetails.body) {
pushRequest.write(requestDetails.body);
}
};
module.exports = sendNotification;
// workerpool.worker({
// sendNotification: sendNotification
// });