Skip to content

Commit

Permalink
Add support of different apps (#100)
Browse files Browse the repository at this point in the history
* Add support of different apps

* Fix batch push notifications

* Use fixed version of smart-config

* Add default app config
  • Loading branch information
kostia-official authored Dec 21, 2016
1 parent 1fd27a4 commit 5091005
Show file tree
Hide file tree
Showing 17 changed files with 158 additions and 55 deletions.
5 changes: 3 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@
"rules": {
"quotes": [2, "single"],
"max-len": [2, {"code": 120, "tabWidth": 2}],
"no-console": 2,
"no-console": 1,
"handle-callback-err": 2,
"no-trailing-spaces": 0,
"no-use-before-define": 0,
"arrow-body-style": 0,
"padded-blocks": 0,
"no-shadow": 0,
Expand All @@ -39,4 +40,4 @@
"no-param-reassign": 0,
"func-names": 0
}
}
}
7 changes: 5 additions & 2 deletions config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
"secret": "VAIwf/lXL6vlPkn2DyPwjrWT2JaTm6YJ3Dc1p6Pi",
"region": "us-east-1",
"title": "Outfit",
"gsmAppArn": "arn:aws:sns:us-east-1:093525834944:app/GCM/outfit-development",
"apnsAppArn": "arn:aws:sns:us-east-1:093525834944:app/APNS_SANDBOX/outfit-development"
"appsArns": {
"android": "arn:aws:sns:us-east-1:093525834944:app/GCM/outfit-development",
"ios": "arn:aws:sns:us-east-1:093525834944:app/APNS_SANDBOX/outfit-development"
},
"defaultApp": "android"
},
"amqp": {
"url": "amqp://localhost"
Expand Down
4 changes: 2 additions & 2 deletions config/production.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
"secret": "PUSH_SECRET",
"region": "PUSH_REGION",
"title": "PUSH_TITLE",
"gsmAppArn": "GSM_APP_ARN",
"apnsAppArn": "APNS_APP_ARN"
"appsArns": "APPS_ARNS",
"defaultApp": "DEFAULT_APP"
},
"amqp": {
"url": "AMQP_URL"
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "pingeon",
"description": "",
"version": "1.0.1",
"version": "1.1.0",
"homepage": "",
"main": "src/",
"keywords": [
Expand Down Expand Up @@ -61,7 +61,7 @@
"promdash": "1.1.0",
"raven": "0.12.1",
"serve-favicon": "2.3.0",
"smart-config": "0.7.1",
"smart-config": "0.7.2",
"source-map-support": "0.4.2",
"worque": "0.9.3"
},
Expand Down
10 changes: 7 additions & 3 deletions src/helpers/aws-utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const _ = require('lodash');
const config = require('smart-config');
const { title, gsmAppArn, apnsAppArn } = config.get('push');
const { title, appsArns, defaultApp } = config.get('push');
const debug = require('debug')('app:helpers:aws-utils');
const RecipientProfile = require('../services/recipient-profile/model');

Expand All @@ -20,8 +20,12 @@ function getPushMessage({ platform, message, payload }) {
return JSON.stringify(pushMessage);
}

function getPlatformApplicationArn(platform) {
return platform === 'android' ? gsmAppArn : apnsAppArn;
function getPlatformApplicationArn(app) {
app = _.get(app, 'name') || app || defaultApp;

const appArn = appsArns[app];
if (!appArn) throw new Error('No ARN for the app ' + app);
return appArn;
}

function getLogGroup(platformApplicationArn) {
Expand Down
20 changes: 15 additions & 5 deletions src/helpers/push-receive-status.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
const debug = require('debug')('app:helpers:push-receive-status');
const Notification = require('../services/notification/model');

function saveSuccessful({ platformApplicationArn, providerMessageId, platform, token, message, payload }) {
const result = { sendDate: new Date(), platformApplicationArn, providerMessageId, platform, token, message, payload };
function saveSuccessful({ app, platformApplicationArn, providerMessageId, platform, token, message, payload }) {
const result = {
sendDate: new Date(),
app,
platformApplicationArn,
providerMessageId,
platform,
token,
message,
payload
};
Notification.create(result);
debug('push sent', result);

return result;
}

function saveFailed({ platform, token, message, payload, error }) {
const failedPush = { platform, token, message, payload, error };
Notification.create(failedPush);
function saveFailed({ error, ...failedPush }) {
error = { message: error.message, stack: error.stack };

Notification.create({ error, ...failedPush });
debug('push sent', failedPush);
}

Expand Down
9 changes: 4 additions & 5 deletions src/helpers/push-send.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ const AWS = require('aws-sdk');
AWS.config.update({ accessKeyId: key, secretAccessKey: secret, region });
const sns = promisifyAll(new AWS.SNS());

async function send({ platform, token, message, payload }) {
async function send({ app, platform, token, message, payload }) {
try {

const platformApplicationArn = awsUtils.getPlatformApplicationArn(platform);
const platformApplicationArn = awsUtils.getPlatformApplicationArn(app);
const pushMessage = awsUtils.getPushMessage({ platform, message, payload });

const { EndpointArn } = await sns.createPlatformEndpointAsync({
Expand All @@ -26,11 +25,11 @@ async function send({ platform, token, message, payload }) {
Message: pushMessage, MessageStructure: 'json',
TargetArn: EndpointArn
});

return pushReceiveStatus.saveSuccessful({
platformApplicationArn,
providerMessageId: MessageId,
platform, token, message, payload
platform, token, message, payload, app
});
} catch (error) {
if (awsUtils.isOldToken(error)) return awsUtils.deleteOldToken(token);
Expand Down
1 change: 1 addition & 0 deletions src/services/notification/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const schema = new Schema({
token: String,
payload: Object,
message: String,
app: Object,
providerMessageId: String,
sendDate: Date,
received: Boolean,
Expand Down
4 changes: 2 additions & 2 deletions src/services/provider/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ module.exports = function () {

app.service('/provider/push/token', {
create(data) {
const { message, payload, token } = data;
return pushNotifyToken({ message, payload, token });
const { message, payload, token, app } = data;
return pushNotifyToken({ message, payload, token, app });
}
});

Expand Down
35 changes: 16 additions & 19 deletions src/services/provider/routes/push-notify-recipient.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
const RecipientProvider = require('../../recipient-profile/model');
const Notification = require('../../notification/model');
const _ = require('lodash');
const Promise = require('bluebird');
const pushHelper = require('../../../helpers/push-send');

module.exports = async({ message, payload, recipientId }) => {
const credentials = await getRecipientCredentials({ recipientId, message, payload });
return await send(credentials);
};

async function createNotifications({ recipientId, message, payload }) {
return await Promise.all(
_(await RecipientProvider.find({ recipientId, providerType: 'push' }))
.uniq('token')
.map(({ recipientId, token, platform, deviceId }) => {
return Notification.create({ recipientId, token, platform, deviceId, message, payload });
})
.value()
);
}

function send(toSend) {
return Promise.map(toSend, push => pushHelper.send(push));
}

const pushes = await createNotifications({ recipientId, message, payload });
async function getRecipientCredentials({ recipientId, message, payload }) {
return await Promise.all(
_(await RecipientProvider.find({ recipientId, providerType: 'push' }))
.uniq('token')
.map((pushProfile) => {
return { recipientId, message, payload, ...pushProfile.toJSON() };
})
.value()
);
}

return await send(pushes);
};
function send(toSend) {
return Promise.map(toSend, push => pushHelper.send(push));
}
4 changes: 2 additions & 2 deletions src/services/provider/routes/push-notify-token.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const Notification = require('../../notification/model');
const pushHelper = require('../../../helpers/push-send');

module.exports = async({ token, message, payload, platform, deviceId }) => {
const push = { token, message, payload, platform, deviceId };
module.exports = async({ token, message, payload, platform, deviceId, app }) => {
const push = { token, message, payload, platform, deviceId, app };
await Notification.create(push);

return await pushHelper.send(push);
Expand Down
1 change: 1 addition & 0 deletions src/services/recipient-profile/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const schema = new Schema({
default: Date.now
},
deviceId: String,
app: Object,
token: String
});
schema.plugin(renameId({ newIdName: 'id', mongoose }));
Expand Down
4 changes: 2 additions & 2 deletions src/services/recipient-profile/routes/push-register.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const RecipientProvider = require('../model');

module.exports = async({ platform, deviceId, token, recipientId }) => {
module.exports = async({ platform, deviceId, token, recipientId, app }) => {
const newRecipientProvider = {
recipientId, deviceId, token, platform,
recipientId, deviceId, token, platform, app,
providerType: 'push', registeredDate: new Date()
};

Expand Down
76 changes: 76 additions & 0 deletions test/batch-notify-push.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
require('./test-env');

const config = require('smart-config');
const { toObject } = require('node-helpers');
const Notification = require('../src/services/notification/model');

const platform = 'android';
const app = { name: 'android' };
const token = String(new Date());

describe('Push send', () => {

describe('success', () => {
let recipientId;
const message = String(new Date());

before(async() => {
const recipient = await helpers.createRandomRecipient();
recipientId = String(recipient.id);
ctx.recipientProfile = await helpers.createRecipientProfile({
recipientId, providerType: 'push', platform, app, token
});
});

it('should be sent', async() => {
await request
.post('/notification/batch')
.send({
recipients: [recipientId],
providers: { push: { message } }
});

await helpers.timeout(1000);
const notification = toObject(await Notification.findOne({ message }));

assert.equal(notification.token, token);
assert.equal(notification.platform, platform);
assert.equal(notification.app.name, app.name);
assert.equal(notification.message, message);
assert(notification.sendDate);
});
});

describe('default app', () => {

let recipientWithoutApp;
const message = String(new Date() + 'no app');

before(async() => {
const recipient = await helpers.createRandomRecipient();
recipientWithoutApp = String(recipient.id);
ctx.recipientProfile = await helpers.createRecipientProfile({
recipientId: recipientWithoutApp, providerType: 'push', platform, token
});
});

it('should use default app', async() => {
await request
.post('/notification/batch')
.send({
recipients: [recipientWithoutApp],
providers: { push: { message } }
});

await helpers.timeout(1000);
const notification = toObject(await Notification.findOne({ message }));

assert.equal(notification.token, token);
assert.equal(notification.platform, platform);
assert.equal(notification.message, message);
assert(notification.sendDate);
assert(!notification.error);
});
});

});
7 changes: 7 additions & 0 deletions test/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ function createRandomRecipient(recipient) {
}, recipient));
}

function timeout(ms) {
return new Promise(res => {
setTimeout(res, ms);
});
}

async function createRecipientProfile({ recipientId, address = 'some', ...other }) {
recipientId = recipientId || (await createRandomRecipient({ id: recipientId })).id;

Expand All @@ -24,5 +30,6 @@ module.exports = {
createRandomRecipient,
createRecipientProfile,
db,
timeout,
randomId
};
14 changes: 8 additions & 6 deletions test/push-send-helper.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const Notification = require('../src/services/notification/model');
const RecipientProfile = require('../src/services/recipient-profile/model');

const platform = 'android';
const app = { name: 'android' };
const token = String(new Date());
const message = String(new Date());
const error = { message: String(new Date()) };
Expand All @@ -30,9 +31,10 @@ describe('Push', () => {

it('should be sent', () => {
return pushProvider
.send({ platform, token, message, payload })
.send({ platform, token, message, payload, app })
.then(async res => {
assert.equal(res.platform, platform);
assert.equal(res.app, app);
assert.equal(res.message, message);
assert.equal(res.token, token);
assert.deepEqual(res.payload, payload);
Expand All @@ -55,7 +57,7 @@ describe('Push', () => {
});

before(() => {
pushProvider.send({ platform, token, message, payload });
pushProvider.send({ platform, token, message, payload, app });
});

it('should be fail', async() => {
Expand All @@ -71,22 +73,22 @@ describe('Push', () => {
const oldTokenError = { message: 'Invalid parameter: This endpoint is already registered with a different token.' };
const oldToken = String(new Date());

before(async () => {
await pushRegister({ token: oldToken, deviceId: 'some', recipientId: 'some' });
before(async() => {
await pushRegister({ token: oldToken, deviceId: 'some', recipientId: 'some', app });
});

before(async() => {
const res = await RecipientProfile.findOne({ token: oldToken });
assert.ok(res);
});

before(() => {
createEndpointStub.returns({ EndpointArn });
publishStub.throws(oldTokenError);
});

before(() => {
pushProvider.send({ platform, token: oldToken, message, payload });
pushProvider.send({ platform, token: oldToken, message, payload, app });
});

it('should be no old device token', async() => {
Expand Down
Loading

0 comments on commit 5091005

Please sign in to comment.