Skip to content

Instantly share code, notes, and snippets.

@1hakr
Last active June 5, 2018 07:55
Show Gist options
  • Save 1hakr/8a69b04cd0d2e556fececb5ccebebb5c to your computer and use it in GitHub Desktop.
Save 1hakr/8a69b04cd0d2e556fececb5ccebebb5c to your computer and use it in GitHub Desktop.
Cloud function for sending notification to android, ios and amazon
function sendAlertNotification(userId, instanceId, notificationKey) {
// Notification details.
const payload = {
notification: {
title: `Price Alert`,
body: 'Body',
sound: 'default',
icon: 'ic_alerts',
android_channel_id: "alerts_channel",
tag: 'unique_key'
}
};
// Set the message as high priority and have it expire after 24 hours.
var options = {
priority: "high",
timeToLive: ttl,
mutableContent: true,
};
return sendNotification(userId, instanceId, notificationKey, payload, options);
}
'use strict';
const admin = require('firebase-admin');
const serviceAccount = require('../service-account.json');
const firebaseAppOptions = {
credential: admin.credential.cert(serviceAccount),
databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`
};
var firebaseApp = admin.initializeApp(firebaseAppOptions);
const RSVP = require('rsvp');
const Logging = require('@google-cloud/logging');
const logging = Logging();
const IAM_USER = "XXXX";
const API_KEY = "XXXX";
const SENDER_ID = "XXXX";
const FCM_SERVER_KEY = "XXXX";
//ADM
const ADM_CLIENT_ID = "XXXX";
const ADM_CLIENT_SECRET = "XXXX";
var adm = require('node-adm');
var options = {
client_id: ADM_CLIENT_ID,
client_secret: ADM_CLIENT_SECRET
};
var admSender = new adm.Sender(options);
function sendNotification(userId, instanceId, notificationKey, payload, options) {
const comboKey = payload.notification.tag;
notificationKey = "";
if (instanceId.startsWith('amzn1')) {
payload.expiresAfter = options.timeToLive;
return sendADMNotification(userId, instanceId, payload);
}
const sendRequest = notificationKey ? admin.messaging().sendToDeviceGroup(notificationKey, payload, options)
: admin.messaging().sendToDevice(instanceId, payload, options)
return sendRequest.then(response => {
if (notificationKey) {
if (response.failureCount > 0 || response.successCount) {
const failedIds = response.failedRegistrationTokens;
reportError("error", {user: userId, tokens: failedIds});
}
return logInfo("Successfully sent message group message", {user: userId, key : comboKey});
} else {
RSVP.all(response.results.map((result, index) => {
const error = result.error;
if (error) {
reportError(error, {user: userId, token: instanceId});
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
return admin.database().ref(`/users/${userId}/instanceId`).remove().then(result => {
logInfo('Removed invalid instanceId', {user: userId, token: instanceId});
return admin.database().ref(`/users/${uid}/clients`).once('value').then(clientSnapshot => {
clientSnapshot.forEach(function(dataSnapshot) {
const clientKey = dataSnapshot.key;
const childInstanceId = dataSnapshot.val().instanceId;
if(childInstanceId == instanceId) {
return admin.database().ref(`/users/${userId}/clients/${clientKey}`).remove();
}
});
});
})
.catch(error => {
return reportError(error, {user: uid, type: 'database_write', context: 'delete instanceId'});
});
}
}
return logInfo("Successfully sent message", {user: userId, key : comboKey});
}));
}
})
.catch(error => {
return reportError(error, {user: userId, token: instanceId, type: 'fcm_message'});
});
}
function sendADMNotification(userId, instanceId, payload) {
return admSender.send(payload, instanceId, function(error, result) {
if (error || result.error) {
return reportError(error, {user: userId, token: instanceId});
} else {
return logInfo("Successfully sent message", {user: userId, response : result});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment