-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (78 loc) · 2.47 KB
/
index.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
//B"H
// Import the web-push library
const webPush = require("web-push");
const http = require("http");
//var awts = require("./awtsmoosPush.js");
const PORT = 3000
const server = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") {
// Handle preflight requests
res.writeHead(200);
res.end();
return;
}
var vapidKeys = {
"publicKey": "BMFDU3eBLj5pJKRz9lTkadYlfURJRHs0lEe8QB1aMY8yyoS5VhpB9w76b71hrykAxDwOZEFPMj5zglw6HB9uYDI",
"privateKey": process.env.vapidPrivate
}
var VAPID_PUBLIC_KEY = vapidKeys.publicKey;
var VAPID_PRIVATE_KEY = vapidKeys.privateKey;
try {
// Configure VAPID details for web-push
webPush.setVapidDetails(
"https://awtsmoos.com/",
VAPID_PUBLIC_KEY,
VAPID_PRIVATE_KEY
);
} catch(e) {
res.end("LOL had issue: " + e.stack);
}
if (req.method === "GET" && req.url === "/vapidPublicKey") {
// Return the VAPID public key
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(VAPID_PUBLIC_KEY);
} else if (req.method === "POST" && req.url === "/register") {
// Handle subscription registration (not stored in this example)
res.writeHead(201);
res.end("Subscription registered successfully.");
} else if (req.method === "POST" && req.url === "/sendNotification") {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
try {
const { subscription, payload, ttl, delay } = JSON.parse(body);
const options = { TTL: ttl };
setTimeout(() => {
webPush
.sendNotification(subscription, payload, options)
.then(() => {
res.writeHead(201);
res.end("Notification sent successfully.");
})
.catch((error) => {
console.error("Notification error:", error);
res.writeHead(500);
res.end("Failed to send notification.");
});
}, (delay || 0) * 1000);
} catch (error) {
console.error("Invalid request body:", error);
res.writeHead(400);
res.end("Invalid request body");
}
});
} else {
// Handle unknown routes
res.writeHead(404);
res.end("Not Found");
}
});
server.listen(PORT, () => {
console.log(`B"H
Server is running on http://localhost:${PORT}`);
});