Skip to content
This repository has been archived by the owner on Sep 29, 2024. It is now read-only.

Commit

Permalink
Add demos
Browse files Browse the repository at this point in the history
  • Loading branch information
aliams committed May 8, 2018
1 parent 8e84e08 commit 76a1058
Show file tree
Hide file tree
Showing 41 changed files with 1,446 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ typings/
# dotenv environment variables file
.env

.vscode/
3 changes: 3 additions & 0 deletions LICENSES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Background Image
https://www.pexels.com/photo/air-atmosphere-blue-blue-sky-96622/
CC0 License
51 changes: 49 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,49 @@
# serviceworker-demo
Service Worker demos
# Service Worker App Demo

This is a demo for service workers and web push notifications that work in modern web browsers.

## How to use

First, install all Node.js dependencies via `npm install`.

This demo requires access to a mongodb instance for storing push subscription info to send push updates at some other point in time. It also requires specifying a public and private key for identifying your server to the push service's server. These keys, known as VAPID public/private keys, can be generated and printed to the console when first executing the site. The site can be executed by running `node index.js` which will start a server on port `2020`. You'll need to populate those keys as environment variables and execute `node index.js` again to ensure that push messages can be configured from your server.

If you are using VS Code you can set the environment variables mentioned above in your `launch.json` file as follows:

```js
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch demo",
"program": "${workspaceFolder}/serve.js",
"env": {
"DATABASE_CONNECTION_URI": "YOUR CONNECTION STRING",
"VAPID_PUBLIC_KEY": "YOUR PUBLIC KEY",
"VAPID_PRIVATE_KEY": "YOUR PRIVATE KEY",
}
},
{
"type": "node",
"request": "launch",
"name": "Job",
"program": "${workspaceFolder}/notify.js",
"env": {
"DATABASE_CONNECTION_URI": "YOUR CONNECTION STRING",
"VAPID_PUBLIC_KEY": "YOUR PUBLIC KEY",
"VAPID_PRIVATE_KEY": "YOUR PRIVATE KEY",
}
}
]
}
```

Alternatively, you can modify `configured-web-push.js` and `db.js` and set the values there explicitly:

```js
const databaseConnectionURI = process.env.DATABASE_CONNECTION_URI || '';
const vapidPublicKey = process.env.VAPID_PUBLIC_KEY || '';
const vapidPrivateKey = process.env.VAPID_PRIVATE_KEY || '';
```
21 changes: 21 additions & 0 deletions configured-web-push.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const webPush = require('web-push');

const vapidPublicKey = process.env.VAPID_PUBLIC_KEY || '';
const vapidPrivateKey = process.env.VAPID_PRIVATE_KEY || '';

if (vapidPublicKey === '' || vapidPrivateKey === '') {
console.log("You must set the VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY " +
"environment variables. You can use the following ones:");
console.log(webPush.generateVAPIDKeys());
} else {
webPush.setVapidDetails(
   'mailto:[email protected]',
  vapidPublicKey,
   vapidPrivateKey
);
}

module.exports = {
webPush: webPush,
vapidPublicKey: vapidPublicKey
}
35 changes: 35 additions & 0 deletions db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const databaseConnectionURI = process.env.DATABASE_CONNECTION_URI || '';

if (databaseConnectionURI === '') {
console.error('Database connection URI not defined.');
}

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

const { Schema } = mongoose;

const SubscriptionSchema = new Schema({
endpoint: { type: String, index: true },
keys: {
auth: { type: String },
p256dh: { type: String }
},
created: {type: Date, default: Date.now }
}, { collection: 'serviceworkerapp' });

const Subscription = mongoose.model('Subscription', SubscriptionSchema);

const connect = async function() {
try {
await mongoose.connect(databaseConnectionURI);
} catch (e) {
console.error('Connection the database failed.');
}
}

connect();

module.exports = {
Subscription
};
44 changes: 44 additions & 0 deletions notify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const { Subscription } = require('./db');
const configuredWebPush = require('./configured-web-push');

const init = async function() {
let pushMessage = "Extreme weather! Come check it out!";

try {
const cursor = Subscription.find().cursor();
await cursor.eachAsync(function(sub) {
return configuredWebPush.webPush.sendNotification({
endpoint: sub.endpoint,
keys: {
auth: sub.keys.auth,
p256dh: sub.keys.p256dh
}
}, pushMessage, {contentEncoding: 'aes128gcm'})
.then(function(push) {
console.log(push);
})
.catch(function(e) {
// 404 for FCM AES128GCM
if (e.statusCode === 410 || e.statusCode === 404) {
// delete invalid registration
return Subscription.remove({endpoint: sub.endpoint}).exec()
.then(function(sub) {
console.log('Deleted: ' + sub.endpoint);
})
.catch(function(sub) {
console.error('Failed to delete: ' + sub.endpoint);
});
}
});
});
} catch (e) {
console.log(e);
}

console.log('Job executed correctly');
};

init().catch(function(err) {
console.error(err);
process.exit(1);
});
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "serviceworker-demo",
"version": "1.0.0",
"description": "Service Worker demos",
"main": "serve.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/MicrosoftEdge/serviceworker-demo.git"
},
"author": "aliams",
"license": "ISC",
"bugs": {
"url": "https://github.com/MicrosoftEdge/serviceworker-demo/issues"
},
"homepage": "https://github.com/MicrosoftEdge/serviceworker-demo#readme",
"dependencies": {
"express": "^4.16.3",
"mongoose": "^5.0.17",
"web-push": "^3.3.0"
}
}
Binary file added public-common/bg.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
44 changes: 44 additions & 0 deletions public-common/common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
function updatePage(details) {
document.querySelector('.current').innerText = details.temp;
document.querySelector('.weather-info .description').innerText = details.description;

document.querySelector('.weather-info .details').innerHTML = '';
for (var i = 0; i < details.details.length; i++) {
var li = document.createElement('li');
var span = document.createElement('span');
span.innerText = details.details[i].label;
var text = document.createTextNode(' ' + details.details[i].value);
li.appendChild(span);
li.appendChild(text);
document.querySelector('.weather-info .details').appendChild(li);
}

var time = new Date(details.time);
var hours = time.getHours();
var ampm = hours >= 12 ? 'PM' : 'AM';
var minutes = time.getMinutes();
hours = hours % 12;
hours = hours ? hours : 12;
minutes = (minutes < 10 ? '0' : '') + minutes;
var lastUpdated = hours + ':' + minutes + ' ' + ampm;

document.querySelector('.weather-info .last-updated .time').innerText = lastUpdated;

document.querySelector('.wrapper').style.opacity = 1;
}

function displayNetworkError() {
var wrapperDiv = document.createElement('div');
wrapperDiv.className = 'wrapper';
var infoDiv = document.createElement('div');
infoDiv.className = 'weather-info';
var textSpan = document.createElement('span');
textSpan.className = 'last-updated';
textSpan.style.textAlign = 'center';
textSpan.style.paddingTop = '18rem';
textSpan.innerText = 'Please connect to the internet and retry.';
infoDiv.appendChild(textSpan);
wrapperDiv.appendChild(infoDiv);
document.querySelector('.wrapper').style.display = 'none';
document.querySelector('.bg').appendChild(wrapperDiv);
}
19 changes: 19 additions & 0 deletions public-common/fallback.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>Weather</title>
<link type="text/css" rel="stylesheet" href="styles.css">
</head>

<body class="desaturate">
<div class="bg">
<div class="wrapper">
<div class="weather-info">
<span class="last-updated" style="text-align: center; padding-top: 18rem;">
Please connect to the internet and retry.
</span>
</div>
</div>
</div>
</body>
</html>
Binary file added public-common/fonts/segoeui.ttf
Binary file not shown.
Binary file added public-common/fonts/segoeui.woff
Binary file not shown.
Binary file added public-common/fonts/segoeui.woff2
Binary file not shown.
Binary file added public-common/fonts/segoeuilight.ttf
Binary file not shown.
Binary file added public-common/fonts/segoeuilight.woff
Binary file not shown.
Binary file added public-common/fonts/segoeuilight.woff2
Binary file not shown.
Binary file added public-common/fonts/segoeuisemibold.ttf
Binary file not shown.
Binary file added public-common/fonts/segoeuisemibold.woff
Binary file not shown.
Binary file added public-common/fonts/segoeuisemibold.woff2
Binary file not shown.
28 changes: 28 additions & 0 deletions public-common/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html>
<head>
<title>Weather</title>
<link type="text/css" rel="stylesheet" href="styles.css">
</head>

<body class="desaturate">
<div class="bg">
<div class="wrapper" style="visibility: hidden">
<div class="current-info">
<span class="location">Seattle, WA</span>
<span class="current"></span>
<div class="type">°F</div>
</div>
<div class="weather-info">
<span class="description"></span>
<span class="last-updated"><a href="#" class="refresh">&#8635;</a> Updated as of <span class="time"></span></span>
<ul class="details"></ul>
</div>
</div>
</div>

<script src="common.js"></script>
<script src="util.js"></script>
<script src="main.js"></script>
</body>
</html>
Loading

0 comments on commit 76a1058

Please sign in to comment.