Skip to content

Instantly share code, notes, and snippets.

@accuervo
Last active November 19, 2016 15:08
Show Gist options
  • Save accuervo/71e48b98caa7a88bb28a7b67e0f3e6fa to your computer and use it in GitHub Desktop.
Save accuervo/71e48b98caa7a88bb28a7b67e0f3e6fa to your computer and use it in GitHub Desktop.
// gcm.js
/**
* Librería gcm - CommonJS - Alloy
* @author Andrés Castaño Cuervo
* @version 1.1.1
* Copyright Evomedia
* www.evoluciondigital.com.co
*/
// Inclusión del módulo.
var gcm = require("nl.vanvianen.android.gcm");
// exports object instance.
var exports = module.exports = {};
/** Métodos expuestos con interacción a controllers. **/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++*/
// subscription to topic.
exports.subscribe = function (topic){
return new Promise(function (resolve, reject) {
gcm.subscribe({
/* The Sender ID from Google Developers Console, see https://console.developers.google.com/project/XXXXXXXX/apiui/credential */
/* It's the same as your project id */
senderId: Alloy.CFG.senderId,
topic: '/topics/'+topic,
notificationSettings: {
smallIcon: 'appicon.png',
largeIcon: 'appicon.png',
vibrate: true,
localOnly: true,
priority: +2
},
success: function (event) {
Ti.API.info("Topic registration success: " + JSON.stringify(event));
resolve({
respuesta: event
});
/* Add code to send event.registrationId to your server */
},
error: function (event) {
Ti.API.info("Topic registration error: " + JSON.stringify(event));
reject({
error: event
});
},
callback: function (event) {
if(undefined !== event.data && undefined !== event.data.event){
Ti.App.fireEvent(event.data.event, event);
}else{
Ti.App.fireEvent('err_subscribe', event);
}
}
})
});
}
// Close subscription to topic.
exports.unsubscribe = function (topic){
gcm.unsubscribe({
senderId: Alloy.CFG.senderId,
topic: '/topics/'+topic,
callback: function (event){
Ti.App.fireEvent('unsubscribe', event);
}
});
};
// Register to pub/sub with registrationId.
exports.register = function (){
return new Promise(function (resolve, reject) {
gcm.registerPush({
/* The Sender ID from Google Developers Console, see https://console.developers.google.com/project/XXXXXXXX/apiui/credential */
/* It's the same as your project id */
senderId: Alloy.CFG.senderId,
notificationSettings: {
smallIcon: 'appicon.png',
largeIcon: 'appicon.png',
vibrate: true,
localOnly: true,
priority: +2
},
success: function (event) {
// Ti.API.info("Push registration success: " + JSON.stringify(event));
Ti.App.fireEvent('registro', event);
resolve({
respuesta: event
});
},
error: function (event) {
Ti.API.info("Push registration error: " + JSON.stringify(event));
globales.toastNotify("Error en Notificaciones.\n"+JSON.stringify(event)+"\nNo fué posible registrarse al canal de notificaciones.\nSin esta funcionalidad la aplicación nó funcionará.\nVerifique por favor:\nEstado de conectividad (wifi, datos),\ny que tenga saldo en su plan de datos\nDespués de verificar esto, por favor reinicie Guepardos\n para validar que sí sea posible registrarse al canal de notificaciones.");
reject({
error: event
});
},
callback: function (event) {
if(undefined !== event.data && undefined !== event.data.event)
Ti.App.fireEvent(event.data.event, event);
}
})
});
}
// Close register to pub/sub with registrationId
exports.unregister = function (){
gcm.unregister();
}
// Return registrationId FCS
exports.getRegistrationId = function (){
return gcm.getRegistrationId();
}
// Return the last notification received, very useful if the app are closed.
exports.getLastData = function (){
var lastData = gcm.getLastData();
if (lastData) {
// Ti.API.info("Last notification received " + JSON.stringify(lastData));
Ti.App.fireEvent('last_data', lastData);
gcm.clearLastData();
}
}
// Clear LastData cache.
exports.clearLastData = function(){
gcm.clearLastData();
}
/////////////////////////////////////////////
// HELPERS
/////////////////////////////////////////////
/*
CURL Commands to test:
// Direct Message.
curl --header "Authorization: key=XXXXXXXXXX" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{ "data": { "event": "Ti-App-Event-To-Fire", "obj": { "tipo": "alert", "titulo": "Servicio Asignado", "mensaje": "El servicio:\n te ha sido asignado" } }, "to": "REGISTRATIONID", "time_to_live": 0, "priority": "high", "notification": { "body": "Servicio Asignado", "title": "Tienes un servicio asignado", "icon": "gpds" } }'
// Message to topic.
curl --header "Authorization: key=XXXXXXXXXX" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{ "data": { "event": "Ti-App-Event-To-Fire", "obj": { "tipo": "alert", "titulo": "Servicio Asignado", "mensaje": "El servicio:\n te ha sido asignado" } }, "to": "/topics/topicname", "time_to_live": 0, "priority": "high", "notification": { "body": "Servicio Asignado", "title": "Tienes un servicio asignado", "icon": "gpds" } }'
// Message to group of devices (limit 1.000)
replace "to" with "registration_ids" : [REG1, REG2, REGN.., REG1000]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment