Skip to content

Commit

Permalink
Merge pull request #9 from AJRedDevil/web-push-notifications
Browse files Browse the repository at this point in the history
Web push notifications
  • Loading branch information
AjanShrestha authored Jan 5, 2020
2 parents edf9034 + 92fb7f2 commit 36f61e2
Show file tree
Hide file tree
Showing 7 changed files with 261 additions and 14 deletions.
39 changes: 36 additions & 3 deletions functions/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});
const webpush = require('web-push');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
Expand All @@ -22,9 +23,41 @@ exports.storePostData = functions.https.onRequest((request, response) => {
location: request.body.location,
image: request.body.image,
})
.then(() =>
response.status(201).json({message: 'Data stored', id: request.body.id})
)
.then(() => {
webpush.setVapidDetails(
'mailto:ajan.shresh@gmail.com',
'BPMh9Hdrri8tao7OUshwND1y98BYJmRoxDEcbtZ4MJN3MITRPTo2u7YCRO7PFWbgtqzjpS_uH4vaGIsx1BNEvs8',
functions.config().pwagram.privatekey
);
return admin
.database()
.ref('subscriptions')
.once('value');
})
.then(subscriptions => {
subscriptions.forEach(sub => {
const pushConfig = {
endpoint: sub.val().endpoint,
keys: {
auth: sub.val().keys.auth,
p256dh: sub.val().keys.p256dh,
},
};
webpush
.sendNotification(
pushConfig,
JSON.stringify({
title: 'New Post',
content: 'New Post added',
openUrl: '/help',
})
)
.catch(err => console.error(err));
});
return response
.status(201)
.json({message: 'Data stored', id: request.body.id});
})
.catch(err => response.status(500).json({error: err}));
});
});
60 changes: 54 additions & 6 deletions functions/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,22 @@
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
"logs": "firebase functions:log",
"web-push": "web-push"
},
"engines": {
"node": "8"
},
"dependencies": {
"cors": "2.8.5",
"firebase-admin": "8.9.0",
"firebase-functions": "^3.3.0"
"firebase-functions": "^3.3.0",
"web-push": "3.4.3"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.1.6"
},
"private": true
}
}
6 changes: 5 additions & 1 deletion public/src/css/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@

.drawer-option {
padding: 16px;
}
}

.enable-notifications {
display: none;
}
97 changes: 97 additions & 0 deletions public/src/js/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
let deferredPrompt;
let enableNotificationsButtons = document.querySelectorAll(
'.enable-notifications'
);

if (!window.Promise) {
window.Promise = Promise;
Expand All @@ -16,3 +19,97 @@ window.addEventListener('beforeinstallprompt', event => {
deferredPrompt = event;
return false;
});

function displayConfirmNotificaiton() {
if ('serviceWorker' in navigator) {
const options = {
body: 'You successfully subscribed to our Notification service!',
icon: '/src/images/icons/app-icon-96x96.png',
image: '/src/images/sf-boat.jpg',
dir: 'ltr',
lang: 'en-US', // BCP 47
vibrate: [100, 50, 200], // vibration pause vibration ...
badge: '/src/images/icons/app-icon-96x96.png',
tag: 'confirm-notification',
renotify: true,
actions: [
{
action: 'confirm',
title: 'Okay',
icon: '/src/images/icons/app-icon-96x96.png',
},
{
action: 'cancel',
title: 'Cancel',
icon: '/src/images/icons/app-icon-96x96.png',
},
],
};
navigator.serviceWorker.ready.then(swreg => {
swreg.showNotification('Successfully subscribed ', options);
});
}
}

function configurePushSub() {
if (!('serviceWorker' in navigator)) {
return;
}

let reg;
navigator.serviceWorker.ready
.then(swreg => {
reg = swreg;
return swreg.pushManager.getSubscription();
})
.then(sub => {
if (sub === null) {
// Create a new subscription
const vapidPublicKey =
'BPMh9Hdrri8tao7OUshwND1y98BYJmRoxDEcbtZ4MJN3MITRPTo2u7YCRO7PFWbgtqzjpS_uH4vaGIsx1BNEvs8';
const convertedVapidPublicKey = urlBase64ToUint8Array(vapidPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidPublicKey,
});
} else {
// We have a subscription
}
})
.then(newSub => {
return fetch('https://pwagram-e7d99.firebaseio.com/subscriptions.json', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(newSub),
});
})
.then(res => {
if (res.ok) {
displayConfirmNotificaiton();
}
})
.catch(err => console.log(err));
}

function askForNotificationPermission() {
Notification.requestPermission(result => {
console.log(`User Choice ${result}`);
if (result !== 'granted') {
console.log('No notification permission granted!');
} else {
// Hide Button
// displayConfirmNotificaiton();
configurePushSub();
}
});
}

if ('Notification' in window && 'serviceWorker' in navigator) {
enableNotificationsButtons.forEach(button => {
button.style.display = 'inline-block';
button.addEventListener('click', askForNotificationPermission);
});
}
13 changes: 13 additions & 0 deletions public/src/js/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,16 @@ function deleteItemFromData(st, id) {
console.log('Item deleted!');
});
}

function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - (base64String.length % 4)) % 4);
var base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');

var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);

for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
Loading

0 comments on commit 36f61e2

Please sign in to comment.