Skip to content

Commit

Permalink
Merge branch 'FlorianSW-issue/182'
Browse files Browse the repository at this point in the history
  • Loading branch information
digitaldan committed Feb 27, 2019
2 parents 1439cfa + 61d51f1 commit c38d2c5
Show file tree
Hide file tree
Showing 9 changed files with 187 additions and 215 deletions.
34 changes: 5 additions & 29 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ logger.info('openHAB-cloud: Backend logging initialized...');
// Initialize the main configuration
var taskEnv = process.env.TASK || 'main';

// If Google Cloud Messaging is configured set it up
// If Firebase Cloud Messaging is configured set it up
if (system.isGcmConfigured()) {
require('./gcm-xmpp');
require('./fcm-xmpp');
}

module.exports.config = config;
Expand All @@ -71,6 +71,7 @@ var flash = require('connect-flash'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
favicon = require('serve-favicon'),
firebase = require('./notificationsender/firebase');
csurf = require('csurf'),
serveStatic = require('serve-static'),
homepage = require('./routes/homepage'),
Expand All @@ -83,18 +84,14 @@ var flash = require('connect-flash'),
redis = require('./redis-helper'),
moment = require('moment'),
date_util = require('./date_util.js'),
appleSender = require('./aps-helper'),
appleSender = require('./notificationsender/aps-helper'),
oauth2 = require('./routes/oauth2'),
auth = require('./auth.js'),
Limiter = require('ratelimiter'),
requesttracker = require('./requesttracker'),
routes = require('./routes'),
MongoConnect = require('./system/mongoconnect');

// Setup Google Cloud Messaging component
var gcm = require('node-gcm');
var gcmSender = require('./gcmsender.js');

// MongoDB connection settings
var mongoose = require('mongoose');
var cacheOpts = {
Expand Down Expand Up @@ -386,7 +383,7 @@ function sendNotificationToUser(user, message, icon, severity) {
}
// If we found any android devices, send notification
if (androidRegistrations.length > 0) {
sendAndroidNotifications(androidRegistrations, message);
firebase.sendNotification(androidRegistrations, message);
}
// If we found any ios devices, send notification
if (iosDeviceTokens.length > 0) {
Expand All @@ -403,27 +400,6 @@ function sendIosNotifications(iosDeviceTokens, message) {
}
}

function sendAndroidNotifications(registrationIds, message) {
redis.incr('androidNotificationId', function (error, androidNotificationId) {
if (!config.gcm || error) {
return;
}
var gcmMessage = new gcm.Message({
delayWhileIdle: false,
data: {
type: 'notification',
notificationId: androidNotificationId,
message: message
}
});
gcmSender.send(gcmMessage, registrationIds, 4, function (err, result) {
if (err) {
logger.error('openHAB-cloud: GCM send error: ' + err);
}
});
});
}

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

Expand Down
131 changes: 131 additions & 0 deletions fcm-xmpp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
const system = require('./system');

/**
* This module maintains XMPP connection to FCM to receive messages from Android
* app.
*/

const UserDevice = require('./models/userdevice'),
UserDeviceLocationHistory = require('./models/userdevicelocationhistory'),
xmpp = require('node-xmpp-client'),
Firebase = require('firebase-messaging'),
firebase = require('./notificationsender/firebase'),
logger = require('./logger.js'),
xmppOptions = {
type: 'client',
jid: system.getGcmJid(),
password: system.getGcmPassword(),
port: 5235,
host: 'fcm-xmpp.googleapis.com',
legacySSL: true,
};

let xmppClient;

const ACK_MESSAGE_TYPE = 'ack';
const NACK_MESSAGE_TYPE = 'nack';

logger.info('openHAB-cloud: Initializing XMPP connection to GCM');
xmppClient = new xmpp.Client(xmppOptions);

xmppClient.on('online', function() {
logger.info('openHAB-cloud: GCM XMPP connection is online');
});

function updateLocationOfDevice(messageData) {
logger.info('openHAB-cloud: This is a location message');
UserDevice.findOne({androidRegistration: messageData.from}, function (error, userDevice) {
let newLocation;

if (error) {
logger.warn('openHAB-cloud: Error finding user device: ' + error);
return;
}
if (!userDevice) {
logger.warn('openHAB-cloud: Unable to find user device with reg id = ' + messageData.from);
return;
}

userDevice.globalLocation = [messageData.data.latitude, messageData.data.longitude];
userDevice.globalAccuracy = messageData.data.accuracy;
userDevice.globalAltitude = messageData.data.altitude;
userDevice.lastGlobalLocation = new Date(messageData.data.timestamp);
userDevice.save();
newLocation = new UserDeviceLocationHistory({userDevice: userDevice.id});
newLocation.globalLocation = [messageData.data.latitude, messageData.data.longitude];
newLocation.when = new Date(messageData.data.timestamp);
newLocation.globalAltitude = messageData.data.altitude;
newLocation.globalAccuracy = messageData.data.accuracy;
newLocation.save();
});
}

function hideNotificationInfo(messageData) {
logger.info('openHAB-cloud: This is hideNotification message');
UserDevice.findOne({androidRegistration: messageData.from}, function (error, userDevice) {
if (error) {
logger.warn('openHAB-cloud: Error finding user device: ' + error);
return;
}

if (!userDevice) {
logger.warn('openHAB-cloud: Unable to find user device with reg id = ' + messageData.from);
return;
}

UserDevice.find({owner: userDevice.owner}, function (error, userDevices) {
// TODO: now send hideNotification data to all devices except the source one
const registrationIds = [];
for (let i = 0; i < userDevices.length; i++) {
const uDevice = userDevices[i];
// Skip the device which sent notification hide itself
if (uDevice.androidRegistration !== userDevice.androidRegistration) {
registrationIds.push(uDevice.androidRegistration);
}
}
if (registrationIds.length < 0) {
return;
}

firebase.hideNotification(registrationIds, messageData.data.notificationId);
});
});
}

xmppClient.on('stanza', function(stanza) {
if (!stanza.is('message') || stanza.attrs.type === 'error') {
return;
}

logger.info('openHAB-cloud: GCM XMPP received message');

const messageData = JSON.parse(stanza.getChildText('gcm'));
if (messageData && messageData.message_type === ACK_MESSAGE_TYPE || messageData.message_type === NACK_MESSAGE_TYPE) {
return;
}

const ackMsg = new xmpp.Element('message')
.c('gcm', { xmlns: 'google:mobile:data' })
.t(JSON.stringify({
'to': messageData.from,
'message_id': messageData.message_id,
'message_type': ACK_MESSAGE_TYPE
}));

xmppClient.send(ackMsg);

logger.info('openHAB-cloud: GCM XMPP ack sent');
if (messageData.data.type === 'location') {
updateLocationOfDevice(messageData);
}

if (messageData.data.type === 'hideNotification') {
hideNotificationInfo(messageData);
}
});

xmppClient.on('error', function (error) {
logger.warn('openHAB-cloud: GCM XMPP error: ' + error);
});

module.exports = xmppClient;
131 changes: 0 additions & 131 deletions gcm-xmpp.js

This file was deleted.

11 changes: 0 additions & 11 deletions gcmsender.js

This file was deleted.

4 changes: 2 additions & 2 deletions aps-helper.js → notificationsender/aps-helper.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var apn = require('apn'),
app = require('./app'),
logger = require('./logger'),
app = require('./../app'),
logger = require('./../logger'),
apnConnection = new apn.Connection(app.config.apn);

apnConnection.on('connected', function () {
Expand Down
Loading

0 comments on commit c38d2c5

Please sign in to comment.