First version of backend

Skeleton frontend
This commit is contained in:
Mark van Renswoude 2021-08-17 19:35:40 +02:00
parent 68b63ac740
commit 781e5e38c5
30 changed files with 14251 additions and 0 deletions

2
.gitignore vendored
View File

@ -1,2 +1,4 @@
node_modules
config.js config.js
data.json data.json

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"javascript.suggestionActions.enabled": false
}

25
config.default.js Normal file
View File

@ -0,0 +1,25 @@
module.exports = {
port: 3369,
publicUrl: 'https://your.domain.name/',
authToken: '<token required to push notifications>',
dataFilename: './data.json',
salt: '<generate a random string of characters>',
reminders: {
enabled: true,
interval: { days: 1 },
title: 'Reminder',
message: 'One or more notifications are still disabled'
},
contacts: [
{
type: 'pushover',
description: 'Pushover Example',
user: '<log in to your Pushover dashboard to find your user key>',
token: '<follow the instructions in the Pushover API documentation to create a token>',
urlTitle: 'Manage notifications'
}
]
}

3
frontend/.browserslistrc Normal file
View File

@ -0,0 +1,3 @@
> 1%
last 2 versions
not dead

23
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

19
frontend/README.md Normal file
View File

@ -0,0 +1,19 @@
# notificationlatch
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).

5
frontend/babel.config.js Normal file
View File

@ -0,0 +1,5 @@
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}

12142
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

24
frontend/package.json Normal file
View File

@ -0,0 +1,24 @@
{
"name": "notificationlatch-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-typescript": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"sass": "^1.26.5",
"sass-loader": "^8.0.2",
"typescript": "~4.1.5"
}
}

View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

30
frontend/src/App.vue Normal file
View File

@ -0,0 +1,30 @@
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view/>
</template>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@ -0,0 +1,61 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>
For a guide and recipes on how to configure / customize this project,<br>
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
</p>
<h3>Installed CLI Plugins</h3>
<ul>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-router" target="_blank" rel="noopener">router</a></li>
<li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-typescript" target="_blank" rel="noopener">typescript</a></li>
</ul>
<h3>Essential Links</h3>
<ul>
<li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
<li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
<li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
<li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
<li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
</ul>
<h3>Ecosystem</h3>
<ul>
<li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
<li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
<li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
<li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'HelloWorld',
props: {
msg: String,
},
});
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>

5
frontend/src/main.ts Normal file
View File

@ -0,0 +1,5 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')

View File

@ -0,0 +1,25 @@
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router

6
frontend/src/shims-vue.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
/* eslint-disable */
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}

View File

@ -0,0 +1,5 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>

View File

@ -0,0 +1,18 @@
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
export default defineComponent({
name: 'Home',
components: {
HelloWorld,
},
});
</script>

39
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,39 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}

6
frontend/vue.config.js Normal file
View File

@ -0,0 +1,6 @@
module.exports = {
devServer: {
port: 3370,
proxy: 'http://localhost:3369'
}
};

32
index.js Normal file
View File

@ -0,0 +1,32 @@
const fshelpers = require('./lib/fshelpers');
const express = require('express');
const repository = require('./lib/repository');
const facade = require('./lib/facade');
async function asyncMain()
{
if (await fshelpers.exists('config.js'))
global.config = require('./config.js');
else
global.config = require('./config.default.js');
facade.init(global.config.contacts);
await repository.init(global.config.dataFilename, global.config.salt);
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/api', require('./routes/api'));
app.use('/', express.static('frontend/dist'));
app.listen(global.config.port, () =>
{
console.log(`NotificationLatch listening at http://localhost:${global.config.port}`);
});
}
asyncMain();

117
lib/facade.js Normal file
View File

@ -0,0 +1,117 @@
const repository = require('./repository');
const subjectParser = require('./subjectparser');
const { DateTime } = require('luxon');
function init(contacts, maxAttempts, retryInterval)
{
if (global.facadeData)
throw new Error("Facade is already initialized");
const transportMap = {
"pushover": require('./transport/pushover')
}
global.facadeData = {
maxAttempts: maxAttempts,
retryInterval: retryInterval,
contacts: contacts.filter(c =>
{
if (!transportMap.hasOwnProperty(c.type))
{
console.error(`Unknown transport type '${c.type}', skipping contact`)
return false;
}
return true;
}),
transportMap: transportMap
}
}
async function postNotification(subject, message, priority)
{
var parsedSubject = subjectParser.parse(subject);
console.log(parsedSubject);
const token = await repository.storeNotification(parsedSubject.id, parsedSubject.title);
if (token === null)
return;
sendNotification({
id: parsedSubject.id,
token: token,
title: parsedSubject.title,
message: message,
priority: priority,
sound: parsedSubject.sound,
timestamp: Math.floor(DateTime.now().toSeconds()),
url: 'https://www.hierhaduwurlkunnenstaan.nl/'
});
}
async function resetNotification(token)
{
await repository.resetNotification(token);
}
function sendNotification(notification)
{
if (!global.facadeData)
throw new Error('Facade not initialized, call init() first');
global.facadeData.contacts.forEach(contact =>
{
const transport = global.facadeData.transportMap[contact.type];
retryableSend(transport, contact, notification);
});
}
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function retryableSend(transport, contact, notification)
{
let attempt = 1;
while (true)
{
try
{
console.info(`Sending notification '${notification.id}' with token '${notification.token}' to '${contact.description}' (attempt ${attempt})`);
await transport.send(contact, notification);
console.info(`Notification '${notification.id}' succesfully sent to '${contact.description}'`);
return;
}
catch (err)
{
if (attempt >= global.facadeData.maxAttempts)
{
console.info(`Error while sending notification '${notification.id}' to '${contact.description}', max attempts reached: ${err}`);
return;
}
console.info(`Error while sending notification '${notification.id}' to '${contact.description}', retrying in ${global.facadeData.retryInterval} seconds: ${err}`);
await delay(global.facadeData.retryInterval * 1000);
attempt++;
}
}
}
module.exports = {
init,
postNotification,
resetNotification
}

20
lib/fshelpers.js Normal file
View File

@ -0,0 +1,20 @@
const fs = require('fs').promises;
async function exists(path)
{
try
{
await fs.access(path);
return true;
}
catch
{
return false;
}
}
module.exports =
{
exists
}

130
lib/repository.js Normal file
View File

@ -0,0 +1,130 @@
const fs = require('fs').promises;
const fshelpers = require('./fshelpers');
const crypto = require('crypto');
const { DateTime } = require('luxon');
function checkInitialized()
{
if (!global.repositoryData)
throw new Error('Repository not initialized, call init() first');
}
async function init(filename, salt)
{
if (global.repositoryData)
throw new Error('Repository is already initialized');
global.repositoryData = {
filename: filename,
salt: salt,
notifications: {}
};
if (!(await fshelpers.exists(filename)))
return;
const contents = await fs.readFile(filename, 'utf8');
global.repositoryData.notifications = JSON.parse(contents.toString());
}
async function flush()
{
const contents = JSON.stringify(global.repositoryData.notifications, null, 2);
await fs.writeFile(global.repositoryData.filename, contents, 'utf8');
}
function getNotificationToken(id)
{
const hasher = crypto.createHmac("sha256", global.repositoryData.salt);
return hasher.update(id).digest("hex");
}
function getUnixTimestamp()
{
return Math.floor(DateTime.now().toSeconds());
}
// Returns the notification token if it should be sent out or null if the notification is latched
async function storeNotification(id, title)
{
checkInitialized();
const now = getUnixTimestamp();
const token = getNotificationToken(id);
if (!global.repositoryData.notifications.hasOwnProperty(token))
{
console.info(`New notification with id '${id}' and token '${token}', send permitted`);
global.repositoryData.notifications[token] = {
id: id,
title: title,
latched: true,
latchTime: now,
resetTime: null,
reminders: true,
remindTime: null
};
await flush();
return token;
}
const notification = global.repositoryData.notifications[token];
if (notification.latched)
{
console.info(`Notification with id ${id} and token '${token}' is already latched, send blocked`);
return null;
}
console.info(`Latching notification with id ${id} and token '${token}', send permitted`);
notification.latched = true;
notification.latchTime = now;
await flush();
return token;
}
async function resetNotification(token)
{
checkInitialized();
const now = getUnixTimestamp();
if (!global.repositoryData.notifications.hasOwnProperty(token))
{
console.info(`Notification token '${token}' does not exist, reset unneccesary`);
return;
}
const notification = global.repositoryData.notifications[token];
if (!notification.latched)
{
console.info(`Notification with id '${notification.id}' and token '${token}' is not latched, reset unneccesary`);
return;
}
console.info(`Resetting notification with id '${notification.id}' and token '${token}'`);
notification.latched = false;
notification.resetTime = now;
notification.reminders = true;
notification.remindTime = null;
await flush();
}
module.exports = {
init,
storeNotification,
resetNotification
}

27
lib/subjectparser.js Normal file
View File

@ -0,0 +1,27 @@
function parse(subject)
{
// Possible formats:
// Title
// |id| Title
// |id,sound| Title
// |,sound| Title
const match = subject.match(/^(?:\|([^,]*?)(?:,(.+?)){0,1}\|){0,1}\s*(.+?)$/m);
if (match == null)
return {
id: subject,
sound: null,
title: subject
};
return {
id: match[1] || match[3],
sound: match[2] || null,
title: match[3]
};
};
module.exports = {
parse
}

33
lib/transport/pushover.js Normal file
View File

@ -0,0 +1,33 @@
const axios = require('axios');
async function send(contact, notification)
{
try
{
const data = {
token: contact.token,
user: contact.user,
message: notification.message,
priority: notification.priority,
timestamp: notification.timestamp,
url: notification.url,
url_title: contact.urlTitle || 'Manage notifications'
};
if (notification.sound)
data.sound = notification.sound;
const response = await axios.post("https://api.pushover.net/1/messages.json", data);
return response.statu;
}
catch
{
return false;
}
}
module.exports = {
send
}

3
nodemon.json Normal file
View File

@ -0,0 +1,3 @@
{
"ignore": ["data.json", "frontend/*"]
}

1365
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "notificationlatch",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "Mark van Renswoude",
"license": "Unlicense",
"dependencies": {
"axios": "^0.21.1",
"express": "^4.17.1",
"luxon": "^2.0.2"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}

46
routes/api.js Normal file
View File

@ -0,0 +1,46 @@
const express = require('express');
const router = express.Router();
const facade = require('../lib/facade');
function logRequestWarning(req, message)
{
console.warn(`[${req.ip}] ${message}`);
}
router.post('/notification', async (req, res) =>
{
if (req.headers.authorization !== 'Bearer ' + global.config.authToken)
{
logRequestWarning(req, 'Missing or invalid authorization header');
res.sendStatus(401);
return;
}
if (!req.body || !req.body.subject || !req.body.message)
{
logRequestWarning(req, 'Missing body, subject and/or message parameters');
res.sendStatus(400);
return;
}
await facade.postNotification(req.body.subject, req.body.message, req.body.priority || 0);
res.sendStatus(200);
});
router.post('/notification/reset', async (req, res) =>
{
if (!req.body || !req.body.token)
{
logRequestWarning(req, 'Missing token');
res.sendStatus(400);
return;
}
await facade.resetNotification(req.body.token);
res.sendStatus(200);
});
module.exports = router;