-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
107 lines (87 loc) · 2.49 KB
/
worker.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
95
96
97
98
99
100
101
102
103
104
105
106
107
var http = require('http');
var fs = require('fs');
const webpush = require('web-push');
var fetch = require('node-fetch');
var jsonObj = null;
const apiKey = 'AIzaSyBxVBLQyEIX6rRy5upkg5HRiG8ELFV_zro';
const vapidKeys = webpush.generateVAPIDKeys();
var privateKey = vapidKeys.privateKey;
fs.writeFile('privateKey/privateKey.txt', privateKey);
var publicKey = vapidKeys.publicKey;
fs.writeFile('publicKey/publicKey.txt', publicKey);
const options = {
gcmAPIKey: apiKey,
vapidDetails: {
subject: 'mailto:[email protected]',
publicKey: publicKey,
privateKey: privateKey,
}
};
http.createServer(function (req, res) {
var body = '';
req.on('data', function (chunk) {
console.log('received a request..');
body += chunk;
jsonObj = JSON.parse(body);
if(req.url == '/registkey'){
fs.writeFile('publicKey/publicKey.txt', encodeBase64URL(jsonObj.serverKey));
}
var privateKey = fs.readFileSync('privateKey/privateKey.txt', 'utf-8');
var publicKey = fs.readFileSync('publicKey/publicKey.txt', 'utf-8');
webpush.setGCMAPIKey(apiKey);
webpush.setVapidDetails(
'mailto:[email protected]',
publicKey,
privateKey
);
var options = {
gcmAPIKey: apiKey,
vapidDetails: {
subject: 'mailto:[email protected]',
publicKey: publicKey,
privateKey: privateKey,
},
TTL: 86400
};
var pushSubscription = {
endpoint : jsonObj.endpoint,
keys: {
auth : jsonObj.auth,
p256dh : jsonObj.p256dh
}
};
const payload = JSON.stringify({
title: jsonObj.title,
message: jsonObj.message
});
webpush.sendNotification(pushSubscription, payload, options).then(function(result){
console.log(result);
}).catch(function(error){
console.log(error);
});
});
res.writeHead(200, {
'Content-Type': 'text/json',
'Access-Control-Allow-Origin': 'http://localhost:8080',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'Content-Type'
});
res.end('publicKey');
}).listen(3000, '127.0.0.1');
function encodeBase64URL(data) {
let output = '';
for(i in data){
output += String.fromCharCode(data[i]);
}
return btoa(output.replace(/\+/g, '-').replace(/\//g, '_')).replace(/=+$/, '');
}
function btoa(str) {
var buffer;
if (Buffer.isBuffer(str)) {
buffer = str;
}
else {
buffer = new Buffer(str.toString(), 'binary');
}
return buffer.toString('base64');
};