Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

first #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .env
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
EXPRESS_PORT=8000
DB_PATH = '.database/subscriptions.db'
MAILTO='mailto:[email protected]'
PUBLIC_KEY="YOUR_PUBLIC_KEY"
PRIVATE_KEY="YOUR_PRIVATE_KEY"
PUBLIC_KEY="BPB3wdNSAqqKC7tfAQCM2QGPNKD8_MLwEDuq72NE1-V7Z6uQCKs5Bp02cjoiKE-f-wKGuEtmmOWV7NRId5k-igg"
PRIVATE_KEY="tG8VcMtgjmDdk_Ua3eC1vGwbA80dByOcWJk5cqf2EAo"
NOTIFICATION_ICON="https://pablomagaz.com/assets/images/icons/logo512.png"
2,599 changes: 2,599 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"esm": "3.2.22",
"express": "4.16.4",
"husky": "1.3.1",
"nedb": "1.8.0",
"nedb": "^1.8.0",
"web-push": "3.3.3"
},
"devDependencies": {
Expand Down
61 changes: 29 additions & 32 deletions src/public/index.html
Original file line number Diff line number Diff line change
@@ -1,34 +1,31 @@
<html lang="utf-8">
<head>
<title>Webpush Server</title>
<script>
const sendEndpoint = "http://localhost:8000/send";
const sendNotification = async () => {
const data = document.getElementById("notification").value;
const res = await fetch(sendEndpoint, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(JSON.parse(data))
});
return res.status === 200 ? res.json() : false;
};
</script>
</head>

<body>
<div id="root">
<textarea rows="3" cols="70" id="notification">
{"title": "Notification title", "body": "View in my site.", "url":"https://mysite.com"}</textarea
>
<input
type="button"
onClick="javascript:sendNotification();"
value="Send notification"
/>
</div>
<script src="/register.js"></script>
</body>
</html>
<head>
<title>Webpush Server</title>
<script>
const sendEndpoint = "http://localhost:8000/send";
const sendNotification = async () => {
const data = document.getElementById("notification").value;
const res = await fetch(sendEndpoint, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(JSON.parse(data))
});
return res.status === 200 ? res.json() : false;
};
</script>
</head>

<body>
<div id="root">
<textarea rows="3" cols="70" id="notification">
{"title": "Notification title", "body": "View in my site.", "url":"http://localhost:8000/index.html"}</textarea>
<input type="button" onClick="javascript:sendNotification();" value="Send notification" />
</div>
<script src="/register.js"></script>
</body>

</html>
18 changes: 15 additions & 3 deletions src/public/register.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-restricted-syntax */
const registerUrl = 'http://localhost:8000/register';
const registerUrl = 'http://localhost:8000/register?ssid='+navigator.userAgent;
const serviceWorkerUrl = 'http://localhost:8000/serviceWorker.js';
const publicVapidKey = 'YOUR_PUBLIC_KEY';
const publicVapidKey = 'BPB3wdNSAqqKC7tfAQCM2QGPNKD8_MLwEDuq72NE1-V7Z6uQCKs5Bp02cjoiKE-f-wKGuEtmmOWV7NRId5k-igg';

const urlBase64ToUint8Array = base64String => {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
Expand Down Expand Up @@ -35,10 +35,14 @@ const generateSubscription = async swRegistration => {
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
});
console.log("pushSubscription first time", subscription);
const saved = await saveSubscription(subscription);
if (saved) return saved;
throw Error('Subscription not saved!');
} else return pushSubscription;
} else {
console.log("pushSubscription reused", pushSubscription);
return pushSubscription;
}
};

const registerServiceWorker = async () => {
Expand All @@ -48,6 +52,14 @@ const registerServiceWorker = async () => {
const register = async () => {
if ('serviceWorker' in navigator) {
const swRegistration = await registerServiceWorker();
navigator.serviceWorker.addEventListener('message', function(e) {
switch(e.data) {
default:
alert('client recv message from ws'+ e.data);
e.ports[0].postMessage(e.data);
break;
}
});
await generateSubscription(swRegistration);
} else throw new Error('ServiceWorkers are not supported by your browser!');
};
Expand Down
39 changes: 36 additions & 3 deletions src/public/serviceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,56 @@ const notificationDelay = 500;

const showNotification = (title, options) =>
new Promise(resolve => {
setTimeout(() => {
self.registration.showNotification(title, options).then(() => resolve());
}, notificationDelay);
// setTimeout(() => {
swPostMessageToAllClients(title);
//self.registration.showNotification(title, options).then(() => resolve());
// }, notificationDelay);
});

self.addEventListener('push', async event => {

const res = JSON.parse(event.data.text());
console.log("He recibido algo", res);
const { title, body, url, icon } = res.payload;
const options = {
body,
icon,
vibrate: [100],
data: { url }
};

event.waitUntil(showNotification(title, options));
});

function swPostMessageToAllClients(msg) {
console.log("swPostMessageToAllClients", msg);
clients.matchAll().then(function(clients) {
console.log("clients", clients);
clients.forEach(function(client) {
console.log("client", client)
swPostMessageToClient(client, msg).then(function(response) {
console.log('response from client', response);
});
});
});
}

function swPostMessageToClient(client, msg) {
return new Promise(function(resolve, reject) {
var msg_chan = new MessageChannel();

msg_chan.port1.onmessage = function(e) {
if (e.data.error) {
reject(e.data.error);
} else {
resolve(e.data);
}
};

client.postMessage(msg, [ msg_chan.port2 ]);
});
}

self.addEventListener('notificationclick', event => {
event.notification.close();
const { url } = event.notification.data;
Expand Down
16 changes: 12 additions & 4 deletions src/server/routing/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ const routes = [
method: 'post',
url: '/register',
handler: async (req, res) => {
console.log("req", req);
const subscription = req.body;
const saved = await saveSubscription(subscription);
console.log("register", subscription);
if (saved) res.status(200).json({ msg: 'Subscription saved!' });
else res.status(500).json({ err: 'Could not save subscription!' });
}
Expand All @@ -18,21 +20,27 @@ const routes = [
method: 'post',
url: '/send',
handler: async (req, res) => {
const { title, url, body } = req.body;
const { title, url, body, targets } = req.body;
const subscriptions = await getSubscriptions();
const data = JSON.stringify({
title,
payload: { title, body, url, icon: process.env.NOTIFICATION_ICON },
body: true
});
const sentSubscriptions = subscriptions.map(subscription =>
const sentSubscriptions = subscriptions.map(subscription =>{
console.log(subscription);
console.log("targets", targets);
if(typeof targets != "undefined" && Array.isArray(targets)&& targets.length > 0 && !targets.includes(subscription._id)){
console.log("AÑLSJHFLÑASDJKFL");
return false;
}
webpush
.sendNotification(subscription, data)
.then()
.catch(err => {
if (err.statusCode === 410) removeSubscription(subscription);
}));

})});
await Promise.all(sentSubscriptions).then(() => {
res.status(200).json({ msg: 'Notifications sent!' });
});
Expand Down
1 change: 1 addition & 0 deletions src/server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@ setRouting(app);
setStatics(app);

app.listen(process.env.EXPRESS_PORT, () => {
console.log(process);
console.log(`Webpush notification server up in ${ process.env.EXPRESS_PORT }`);
});
3 changes: 2 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1074,9 +1074,10 @@ natural-compare@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"

[email protected]:
nedb@^1.8.0:
version "1.8.0"
resolved "https://registry.yarnpkg.com/nedb/-/nedb-1.8.0.tgz#0e3502cd82c004d5355a43c9e55577bd7bd91d88"
integrity sha512-ip7BJdyb5m+86ZbSb4y10FCCW9g35+U8bDRrZlAfCI6m4dKwEsQ5M52grcDcVK4Vm/vnPlDLywkyo3GliEkb5A==
dependencies:
async "0.2.10"
binary-search-tree "0.2.5"
Expand Down