From: ebelcrom Date: Sun, 16 Feb 2020 20:44:08 +0000 (+0100) Subject: cleaned up X-Git-Tag: v1.0.0~5 X-Git-Url: http://www.binomiant.duckdns.org/9wAuyR5S/?a=commitdiff_plain;h=4a3d48ace2c14b2294f1b0e3acd066db63ac17e5;p=garnod.git cleaned up --- diff --git a/app.js b/app.js index 38455b2..e11e36e 100644 --- a/app.js +++ b/app.js @@ -6,6 +6,7 @@ const cors = require('cors'); const log = require('./lib/logger')(__filename.slice(__dirname.length + 1)); const ver = 'v1'; +const notify = require('./lib/notify'); const indexRouter = require('./routes/index'); @@ -65,4 +66,11 @@ app.use('/' + ver + '/test/settings', testSettings); // api-docs app.use('/' + ver + '/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); +// subscribe notification after 2s +setTimeout(subscribeNotification, 2000); + +function subscribeNotification() { + notify.subscribe('prod', null); +} + module.exports = app; diff --git a/init/initcloud.js b/init/initcloud.js deleted file mode 100644 index a986f70..0000000 --- a/init/initcloud.js +++ /dev/null @@ -1,12 +0,0 @@ - - -function generateVAPIDKeys() { - var curve = crypto.createECDH('prime256v1'); - curve.generateKeys(); - - return { - publicKey: curve.getPublicKey(), - privateKey: curve.getPrivateKey(), - }; -} - diff --git a/init/settings.json b/init/settings.json new file mode 100644 index 0000000..20e6a70 --- /dev/null +++ b/init/settings.json @@ -0,0 +1,7 @@ +{ + "publicKey": "", + "privateKey": "", + "fcmApiKey": "", + "prodApiKey": "", + "testApiKey": "2TTqCD4mNNny" +} diff --git a/init/vapid.json b/init/vapid.json deleted file mode 100644 index 530596e..0000000 --- a/init/vapid.json +++ /dev/null @@ -1 +0,0 @@ -{"publicKey":"BLDSdGasI5sLks30brbIWvlLMFqzoxxkOs7aW_E9PDBzIO_mDs6-tvtb2U0-BVFDafNd58DJgoXxdK5711FF29c","privateKey":"_AFTIegzYV_l_5RYwzOCc22cpYcMUmpkA8bLbrlNq9I"} diff --git a/lib/db.js b/lib/db.js index 8d35a61..64f7b1c 100644 --- a/lib/db.js +++ b/lib/db.js @@ -206,8 +206,11 @@ function getNotification(data, callback) { return reject(msg.dbError); } if (res.key !== data.key) { - log.info('API key doesn\'t match'); - return reject(msg.keyMismatch); + // notification request on start? + if (data.key !== null) { + log.info('API key doesn\'t match'); + return reject(msg.keyMismatch); + } } log.debug('API key is valid'); resolve(msg.ok); diff --git a/lib/gpio.js b/lib/gpio.js index a39204a..9f9d376 100644 --- a/lib/gpio.js +++ b/lib/gpio.js @@ -8,7 +8,6 @@ const DELAY = 300; var reedState; var controlCallback = null; var notificationCallback = null; -var apiKey = null; var timer = null; function init() { @@ -26,7 +25,7 @@ function trigger() { rpio.msleep(500); rpio.write(RELAIS, rpio.LOW); - log.debug('relais triggered'); + log.debug('Relais triggered'); } function readDebounced(pin) { @@ -35,7 +34,7 @@ function readDebounced(pin) { rpio.msleep(1000); if (state != rpio.read(pin)) { - log.debug('state unknown'); + log.debug('State unknown'); return UNKNOWN; } else { return state; @@ -48,7 +47,7 @@ function pollcb(pin) if (state != UNKNOWN && reedState != UNKNOWN) { if (state != reedState) { - log.debug('reed state changed, now:', state); + log.debug('Reed state changed, now:', state); if (controlCallback != null) { // handle callbacks @@ -91,15 +90,14 @@ function read() { } } -function subscribe(callback, key) { +function subscribe(callback) { notificationCallback = callback; - apiKey = key; } function evaluation(state) { if (notificationCallback != null) { if (state == rpio.HIGH) { - timer = setTimeout(notificationCallback, DELAY * 1000, apiKey); + timer = setTimeout(notificationCallback, DELAY * 1000); log.debug('Open door evaluation started'); } else { clearTimeout(timer); diff --git a/lib/notify.js b/lib/notify.js new file mode 100644 index 0000000..0a28a87 --- /dev/null +++ b/lib/notify.js @@ -0,0 +1,93 @@ +const log = require('./logger')(__filename.slice(__dirname.length + 1)); +const db = require('./db'); +const gpio = require('./gpio'); +const settings = require('./../init/settings.json'); +const fs = require('fs'); +const webpush = require('web-push'); + +var data = { + area: null, + key: null +}; + +function subscribe(area, key) { + data.area = area; + data.key = key; + + // subscribe notification + gpio.subscribe(onDoorOpen); + log.info('Open door event subscribed'); +} + +function onDoorOpen() { + // get settings + db.getNotification({ + area: data.area, + key: data.key + }, (err, data) => { + if (err) { + switch (err) { + case db.msg.dbError: + log.info('Server error response'); + break; + case db.msg.keyMismatch: + log.info('Unauthorized access'); + break; + default: + log.error('Error result unexpected'); + break; + } + } else { + executeNotification(data); + } + }); +} + +function executeNotification(notification) { + const pushSubscription = { + endpoint: notification.endpoint, + keys: { + auth: notification.keys.auth, + p256dh: notification.keys.p256dh + } + }; + + const options = { + gcmAPIKey: settings.fcmApiKey, + vapidDetails: { + subject: 'mailto:ebelcrom@gmail.com', + publicKey: settings.publicKey, + privateKey: settings.privateKey + }, + headers: { + 'Urgency': 'high' + }, + contentEncoding: 'aes128gcm' + }; + + const icon = 'data:image/png;base64,' + + fs.readFileSync(__dirname + '/../public/images/icon.png', 'base64'); + const payload = { + message: 'The garage door is open!', + icon: icon + }; + log.debug('Paylod length:', JSON.stringify(payload).length); +/* + const details = webpush.generateRequestDetails(pushSubscription, JSON.stringify(payload), options); + log.debug('Request details:', JSON.stringify(details)); +*/ + webpush.sendNotification(pushSubscription, JSON.stringify(payload), options) + .then(data => { + if (data) { + log.debug('Notification sent, data:', JSON.stringify(data)); + } + }) + .catch(err => { + log.error('Notification sending failed:', JSON.stringify(err)); + }); +} + +module.exports = { + subscribe, + executeNotification +} diff --git a/lib/webcam.js b/lib/webcam.js index 2ace8fa..bf822c1 100644 --- a/lib/webcam.js +++ b/lib/webcam.js @@ -5,7 +5,7 @@ const username = 'view'; const options = { host: '192.168.3.2', path: '/snapshot.cgi', - mthod: 'GET', + method: 'GET', headers: { 'Authorization': 'Basic ' + new Buffer(username + ':').toString('base64') } diff --git a/routes/v1/events.js b/routes/v1/events.js index 3b34896..96762cd 100644 --- a/routes/v1/events.js +++ b/routes/v1/events.js @@ -4,6 +4,7 @@ const qStr = require('query-string'); const router = express.Router(); const db = require('./../../lib/db'); const EventEmitter = require('events'); +const webcam = require('./../../lib/webcam'); const events = new EventEmitter(); var response = null; @@ -86,18 +87,20 @@ events.on('stateChanged', (state) => { }; if (image) { webcam.getImage() - .then(image => { - content['image'] = new Buffer(image).toString('base64'); - res.json(content); + .then(img => { + content['image'] = new Buffer(img).toString('base64'); + response.json(content); + response = null; }) .catch(err => { log.error('Error on getting webcam image', JSON.stringify(err)); - res.status(500).send(); + response.status(500).send(); + response = null; }); } else { - res.json(content); + response.json(content); + response = null; } - response = null; } }); diff --git a/routes/v1/notification.js b/routes/v1/notification.js index cf2c699..81e90e7 100644 --- a/routes/v1/notification.js +++ b/routes/v1/notification.js @@ -4,8 +4,8 @@ const qStr = require('query-string'); const router = express.Router(); const db = require('./../../lib/db'); const gpio = require('./../../lib/gpio'); +const notify = require('./../../lib/notify'); const fs = require('fs'); -const webpush = require('web-push'); /* Disables caching in client */ function nocache(req, res, next) { @@ -85,86 +85,12 @@ router.post('/', nocache, function(req, res, next) { } } else { // subscribe notification - gpio.subscribe(onDoorOpen, req.header('X-API-Key')); - log.debug('Open door event subscribed'); + notify.subscribe('prod', req.header('X-API-Key')); + log.debug('Notification subscribed'); res.status(200).send(); } }); } }); -function onDoorOpen(key) { - // get settings - db.getNotification({ - area: 'prod', - key: key - }, (err, data) => { - if (err) { - switch (err) { - case db.msg.dbError: - log.info('Server error response'); - res.status(500).send(); - break; - case db.msg.keyMismatch: - log.info('Unauthorized access'); - res.status(401).send(); - break; - default: - log.error('Error result unexpected'); - res.status(500).send(); - break; - } - } else { - executeNotification(data); - } - }); -} - -function executeNotification(notification) { - const pushSubscription = { - endpoint: notification.endpoint, - keys: { - auth: notification.keys.auth, - p256dh: notification.keys.p256dh - } - }; - - const options = { - gcmAPIKey: 'AAAAUtHuYco:APA91bEBTxCRGaez9_glljXAlit3PY5HMwhLSqWYMC1j-jFSp6' - + 'nvnNqjI42jAVFApQbM0oyAOQjCUilIovB76cwTFxyZTP96wm9n09XwiMRXJjhwiJX1hO3' - + '2mBB2zwK6X-w7epE1V67K', - vapidDetails: { - subject: 'mailto:ebelcrom@gmail.com', - publicKey: 'BLDSdGasI5sLks30brbIWvlLMFqzoxxkOs7aW_E9PDBzIO_mDs6-tvtb2U0-' - + 'BVFDafNd58DJgoXxdK5711FF29c', - privateKey: '_AFTIegzYV_l_5RYwzOCc22cpYcMUmpkA8bLbrlNq9I' - }, - headers: { - 'Urgency': 'high' - }, - contentEncoding: 'aes128gcm' - }; - - const icon = 'data:image/png;base64,' + - fs.readFileSync(__dirname + '/../../public/images/icon.png', 'base64'); - const payload = { - message: 'The garage door is open!', - icon: icon - }; - log.debug('Paylod length:', JSON.stringify(payload).length); - - const details = webpush.generateRequestDetails(pushSubscription, JSON.stringify(payload), options); - log.debug('Request details:', JSON.stringify(details)); - - webpush.sendNotification(pushSubscription, JSON.stringify(payload), options) - .then(data => { - if (data) { - log.info('sent, data:', JSON.stringify(data)); - } - }) - .catch(err => { - log.info('sent, err:', JSON.stringify(err)); - }); -} - module.exports = router; diff --git a/routes/v1/test/notification.js b/routes/v1/test/notification.js index 8295a96..3d59eae 100644 --- a/routes/v1/test/notification.js +++ b/routes/v1/test/notification.js @@ -3,6 +3,8 @@ const log = require('./../../../lib/logger')(__filename.slice(__dirname.length + const qStr = require('query-string'); const router = express.Router(); const db = require('./../../../lib/db'); +const notify = require('./../../../lib/notify'); +const fs = require('fs'); /* Disables caching in client */ function nocache(req, res, next) { diff --git a/routes/v1/test/settings.js b/routes/v1/test/settings.js index 27e3f13..8236567 100644 --- a/routes/v1/test/settings.js +++ b/routes/v1/test/settings.js @@ -4,6 +4,7 @@ const qStr = require('query-string'); const router = express.Router(); const db = require('./../../../lib/db'); const fs = require('fs'); +const notify = require('./../../../lib/notify'); const webpush = require('web-push'); const delayMin = -1; @@ -154,7 +155,7 @@ router.post('/', function(req, res, next) { if (typeof req.body.notification == 'object' ) { if (typeof req.body.notification.delay == 'number' && req.body.notification.delay !== delayMin) { - notify(req, res, next, settings.notification.delay); + subscribe(req, res, next, settings.notification.delay); } else { res.status(200).send(); } @@ -164,7 +165,7 @@ router.post('/', function(req, res, next) { } }); -function notify(req, res, next, delay) { +function subscribe(req, res, next, delay) { // get settings db.getNotification({ area: 'test', @@ -206,50 +207,7 @@ function executeNotification(notification) { clearTimeout(timer); timer = null; - const pushSubscription = { - endpoint: notification.endpoint, - keys: { - auth: notification.keys.auth, - p256dh: notification.keys.p256dh - } - }; - - const options = { - gcmAPIKey: 'AAAAUtHuYco:APA91bEBTxCRGaez9_glljXAlit3PY5HMwhLSqWYMC1j-jFSp6' - + 'nvnNqjI42jAVFApQbM0oyAOQjCUilIovB76cwTFxyZTP96wm9n09XwiMRXJjhwiJX1hO3' - + '2mBB2zwK6X-w7epE1V67K', - vapidDetails: { - subject: 'mailto:ebelcrom@gmail.com', - publicKey: 'BLDSdGasI5sLks30brbIWvlLMFqzoxxkOs7aW_E9PDBzIO_mDs6-tvtb2U0-' - + 'BVFDafNd58DJgoXxdK5711FF29c', - privateKey: '_AFTIegzYV_l_5RYwzOCc22cpYcMUmpkA8bLbrlNq9I' - }, - headers: { - 'Urgency': 'high' - }, - contentEncoding: 'aes128gcm' - }; - - const icon = 'data:image/png;base64,' + - fs.readFileSync(__dirname + '/../../../public/images/icon.png', 'base64'); - const payload = { - message: 'The garage door is open!', - icon: icon - }; - log.debug('Paylod length:', JSON.stringify(payload).length); - - const details = webpush.generateRequestDetails(pushSubscription, JSON.stringify(payload), options); - log.debug('Request details:', JSON.stringify(details)); - - webpush.sendNotification(pushSubscription, JSON.stringify(payload), options) - .then(data => { - if (data) { - log.info('sent, data:', JSON.stringify(data)); - } - }) - .catch(err => { - log.info('sent, err:', JSON.stringify(err)); - }); + notify.executeNotification(notification); } module.exports = router;