Skip to content

Commit

Permalink
Updates Node to version 14, updates NPM modules (#335)
Browse files Browse the repository at this point in the history
Major Upgrade of Node and NPM packages

* Updates Node to version 14, updates dependencies to latest version.  Updates ejs views to use updated ejs include syntax.  Updates various methods due to NPM package updates and breaking changes.  Replaces no longer maintained NPM libraries with alternatives.

Signed-off-by: Dan Cunningham <[email protected]>

* update readme to node 14

Signed-off-by: Dan Cunningham <[email protected]>

* Fix updated APN methods and setters

Signed-off-by: Dan Cunningham <[email protected]>

* Refactors close logic due to Node upgrade changes to event order

Signed-off-by: Dan Cunningham <[email protected]>

* Updates APN2 for http/2 requireemnts, use new p8 auth key for PNS

Signed-off-by: Dan Cunningham <[email protected]>

* Updated FCM xmpp libray and logic

Signed-off-by: Dan Cunningham <[email protected]>
  • Loading branch information
digitaldan authored Mar 7, 2021
1 parent 73bf3e5 commit c8274fe
Show file tree
Hide file tree
Showing 43 changed files with 5,567 additions and 4,465 deletions.
5 changes: 1 addition & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
FROM node:8-alpine

# File Author / Maintainer
MAINTAINER Mehmet Arziman
FROM node:14-alpine

RUN apk add --no-cache tzdata gettext

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ node --version
```


If you see the node version, you are fine to continue (Note: openHAB Cloud is based on Node.js version 7.10.1).
If you see the node version, you are fine to continue (Note: openHAB Cloud is based on Node.js version 14).

To run openHAB Cloud you need to install the required software bundles/stacks:

Expand Down
124 changes: 62 additions & 62 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ var logger = require('./logger.js'),


//load and set our configuration, delete any cache first
var loadConfig = function() {
var loadConfig = function () {
delete require.cache[require.resolve('./config.json')];
config = require('./config.json');
system.setConfiguration(config);
Expand All @@ -45,12 +45,13 @@ var internalAddress = system.getInternalAddress();
logger.info('openHAB-cloud: Backend service is starting up...');

process.on('uncaughtException', function (err) {
console.log(JSON.stringify(err))
logger.error(err);
});

process.on('SIGHUP', function () {
logger.info('Reloading config...');
loadConfig();
logger.info('Reloading config...');
loadConfig();
});

logger.info('openHAB-cloud: Backend logging initialized...');
Expand All @@ -68,7 +69,6 @@ module.exports.config = config;
// Setup all homepage
var flash = require('connect-flash'),
express = require('express'),
methodOverride = require('method-override'),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
morgan = require('morgan'),
Expand All @@ -86,7 +86,6 @@ var flash = require('connect-flash'),
passport = require('passport'),
RedisStore = require('connect-redis')(session),
redis = require('./redis-helper'),
moment = require('moment'),
date_util = require('./date_util.js'),
appleSender = require('./notificationsender/aps-helper'),
oauth2 = require('./routes/oauth2'),
Expand All @@ -101,10 +100,10 @@ var mongoose = require('mongoose');
// MongoDB Caching for Item updates
var cachegoose = require('cachegoose');
cachegoose(mongoose, {
engine: 'redis',
port: config.redis.port,
host: config.redis.host,
password: config.redis.password,
engine: 'redis',
port: config.redis.port,
host: config.redis.host,
password: config.redis.password,
});
var cacheTTL = config.cacheTTL || 600;

Expand Down Expand Up @@ -169,13 +168,13 @@ if (taskEnv === 'main') {
Openhab.findOne({
uuid: offlineOpenhabUuid
}).exec(function (error, openhab) {
if (!openhab || error) {
return;
}
//if this has not connected to another server, then notify
if(openhab.serverAddress == internalAddress){
notifyOpenHABOwnerOffline(openhab);
}
if (!openhab || error) {
return;
}
//if this has not connected to another server, then notify
if (openhab.serverAddress == internalAddress) {
notifyOpenHABOwnerOffline(openhab);
}
});
}
}, 60000);
Expand All @@ -188,18 +187,18 @@ if (taskEnv === 'main') {
setInterval(function () {
var requests = requestTracker.getAll();
logger.debug('openHAB-cloud: Checking orphaned rest requests (' + requestTracker.size() + ')');
for (var requestId in requests) {
var res = requestTracker.get(requestId);
Object.keys(requests).forEach(function (requestId) {
var res = requests[requestId];
if (res.finished) {
logger.debug('openHAB-cloud: expiring orphaned response');
requestTracker.remove(requestId);
if(res.openhab) {
if (res.openhab) {
io.sockets.in(res.openhab.uuid).emit('cancel', {
id: requestId
});
}
}
}
})
}, 60000);

// Setup mongoose data models
Expand All @@ -214,6 +213,7 @@ var OpenhabAccessLog = require('./models/openhabaccesslog');

logger.info('openHAB-cloud: Scheduling a statistics job (every 5 min)');
var every5MinStatJob = require('./jobs/every5minstat');
const { request } = require('http');
every5MinStatJob.start();

// Configure the openHAB-cloud for development mode, if in development
Expand All @@ -229,18 +229,18 @@ app.use(favicon(__dirname + '/public/img/favicon.ico'));
if (system.getLoggerMorganOption())
app.use(system.getLoggerMorganOption());

app.use(bodyParser.json({verify:function(req,res,buf){req.rawBody=buf}}))
app.use(bodyParser.json({ verify: function (req, res, buf) { req.rawBody = buf } }))
app.use(bodyParser.urlencoded({
verify:function(req,res,buf){req.rawBody=buf},
extended: true
verify: function (req, res, buf) { req.rawBody = buf },
extended: true

}));
app.use(methodOverride());

app.use(cookieParser(config.express.key));

// Configurable support for cross subdomain cookies
var cookie = {};
if(config.system.subDomainCookies){
if (config.system.subDomainCookies) {
cookie.path = '/';
cookie.domain = '.' + system.getHost();
logger.info('openHAB-cloud: Cross sub domain cookie support is configured for domain: ' + cookie.domain);
Expand Down Expand Up @@ -271,10 +271,10 @@ app.use(function (req, res, next) {
}
// If host matches names for full /* proxying, go ahead and just proxy it.
if (host.indexOf('remote.') === 0 || host.indexOf('home.') === 0) {
//make sure this was not set by another server
if(req.url.indexOf('/remote') != 0){
req.url = '/remote' + req.url;
}
//make sure this was not set by another server
if (req.url.indexOf('/remote') != 0) {
req.url = '/remote' + req.url;
}
}
next();
});
Expand Down Expand Up @@ -328,7 +328,7 @@ app.use(function (req, res, next) {
} else {
res.locals.timeZone = 'undefined';
}
res.locals.moment = moment;

res.locals.date_util = date_util;

res.locals.legal = false;
Expand All @@ -347,7 +347,7 @@ var server = app.listen(system.getNodeProcessPort(), function () {
logger.info('openHAB-cloud: express server listening on port ' + system.getNodeProcessPort());
});

var io = require('socket.io').listen(server, {
var io = require('socket.io')(server, {
logger: logger
});

Expand Down Expand Up @@ -416,7 +416,7 @@ function sendIosNotifications(iosDeviceTokens, notification) {
}

// In case of polling transport set poll duration to 300 seconds
io.set('polling duration', 300);
//io.set('polling duration', 300);

io.use(function (socket, next) {
var handshakeData = socket.handshake;
Expand Down Expand Up @@ -481,7 +481,7 @@ io.sockets.on('connection', function (socket) {
// Make an event and notification only if openhab was offline
// If it was marked online, means reconnect appeared because of my.oh fault
// We don't want massive events and notifications when node is restarted
logger.info('openHAB-cloud: uuid ' + socket.handshake.uuid + ' server address ' + openhab.serverAddress + " my address " + internalAddress);
logger.info('openHAB-cloud: uuid ' + socket.handshake.uuid + ' server address ' + openhab.serverAddress + " my address " + internalAddress);
if (openhab.status === 'offline' || openhab.serverAddress !== internalAddress) {
openhab.status = 'online';
openhab.serverAddress = internalAddress;
Expand Down Expand Up @@ -884,10 +884,10 @@ io.sockets.on('connection', function (socket) {
logger.info('openHAB-cloud: openHAB ' + self.handshake.uuid + ' requested to update ' + data.type + ' config ' +
data.name + ' with timestamp = ' + data.timestamp);
OpenhabConfig.findOne({
openhab: openhab.id,
type: data.type,
name: data.name
},
openhab: openhab.id,
type: data.type,
name: data.name
},
function (error, openhabConfig) {
if (error) {
logger.warn('openHAB-cloud: Failed to find ' + self.openhab.uuid + ' config: ' + error);
Expand Down Expand Up @@ -964,31 +964,31 @@ io.sockets.on('connection', function (socket) {

function notifyOpenHABStatusChange(openhab, status) {

//we can mute notifications, for example when we are doing a deploy
if(system.getMuteNotifications()){
return;
}

User.find({
account: openhab.account,
role: 'master'
}, function (error, users) {
if (!error && users) {
for (var i = 0; i < users.length; i++) {
if (status === 'online') {
sendNotificationToUser(users[i], 'openHAB is online', 'openhab', 'good');
} else {
sendNotificationToUser(users[i], 'openHAB is offline', 'openhab', 'bad');
}
}
} else {
if (error) {
logger.warn('openHAB-cloud: Error finding users to notify: ' + error);
} else {
logger.warn('openHAB-cloud: Unable to find any masters for openHAB ' + openhab.uuid);
}
}
});
//we can mute notifications, for example when we are doing a deploy
if (system.getMuteNotifications()) {
return;
}

User.find({
account: openhab.account,
role: 'master'
}, function (error, users) {
if (!error && users) {
for (var i = 0; i < users.length; i++) {
if (status === 'online') {
sendNotificationToUser(users[i], 'openHAB is online', 'openhab', 'good');
} else {
sendNotificationToUser(users[i], 'openHAB is offline', 'openhab', 'bad');
}
}
} else {
if (error) {
logger.warn('openHAB-cloud: Error finding users to notify: ' + error);
} else {
logger.warn('openHAB-cloud: Unable to find any masters for openHAB ' + openhab.uuid);
}
}
});
}

function shutdown() {
Expand Down
7 changes: 7 additions & 0 deletions config-development.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@
"jid": "[email protected]",
"password": "password"
},
"apn" : {
"team": "PB1234567",
"keyId": "BLABLA1",
"host": "api.development.push.apple.com",
"defaultTopic": "es.spaphone.openhab",
"signingKey": "certs/aps/AuthKey.p8"
},
"ifttt" : {
"iftttChannelKey" : "key",
"iftttTestToken" : "token"
Expand Down
8 changes: 4 additions & 4 deletions config-production.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
"key" : "some express key"
},
"apn" : {
"gateway": "gateway.push.apple.com",
"cert": "certs/aps/aps_production_cert.pem",
"key": "certs/aps/aps_production_key.pem",
"passphrase": "passphrase"
"team": "PB1234567",
"keyId": "BLABLA1",
"defaultTopic": "es.spaphone.openhab",
"signingKey": "certs/aps/AuthKey.p8"
},
"gcm" : {
"jid": "[email protected]",
Expand Down
35 changes: 3 additions & 32 deletions date_util.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,11 @@
var moment = require('moment'),
tz = require('timezone/loaded'),
time = require('time');
var { DateTime } = require('luxon');

module.exports = function (date, timezone) {
var strftime_format = '%F %T %z', // used to convert a date into a normalized strftime format with timezone
moment_format = 'YYYY-MM-DD HH:mm:ss zz'; // moment.js LDML format for parsing date strings

/**
* Convert a Javascript Date into node-time wrapper with the appropriate timezone.
* @param date {Date} Javascript Date object
* @param timezone {String} Olson timezone for this date (e.g. 'America/New_York')
* @return node-time object with the appropriate timezone
*/
var to_local = function (date, timezone) {
var tz_date;

if (timezone === 'undefined') {
timezone = 'UTC';
}
tz_date = new time.Date(date);
tz_date.setTimezone(timezone); // localize the date into the specified timezone
return local_datetime = tz(tz_date, strftime_format, timezone); // localized format w timezone offset
}

/**
* Convert a Javascript Date into a Moment.js moment obj with the appropriate timezone.
* Using the returned moment, you can call for example 'moment.calendar()' to get a
* human readable relative time such as 'last Friday at 3:52 PM'.
* @param date {Date} Javascript Date object
* @param timezone {String} Olson timezone for this date (e.g. 'America/New_York')
* @return moment with the appropriate timezone
* @return luxon object with the appropriate timezone
*/
var to_moment = function (date, timezone) {
var local_datetime = to_local(date, timezone);
return moment(local_datetime, moment_format);
}

return to_moment(date, timezone);
return DateTime.fromJSDate(date).setZone(timezone || 'UTC')
}
Loading

0 comments on commit c8274fe

Please sign in to comment.