I am using node-xmpp to connect to google gcm ccs servers. I followed the from gcm google groups to connect. Now i need to send a downstream message whenever i receive a message from my redis subscriber(i subscribed to a redis channel redis node package). My code is as follows
var gearmanode = require('gearmanode');
var redis = require("redis");
var xmpp = require('node-xmpp');
var gearJob;
var redisSubChan = 'test_channel';
var gearmanJobName = 'reverse';
var jobPayload;
var redisClient;
var xmppClient;
var gearClient;
gearClient = gearmanode.client();
var options = {
type: 'client',
jid: 'myid#gcm.googleapis.com',
password: 'myserverkey',
port: 5235,
host: 'gcm.googleapis.com',
legacySSL: true,
preferredSaslMechanism: 'PLAIN'
};
console.log('creating xmpp app');
xmppClient = new xmpp.Client(options);
xmppClient.connection.socket.setTimeout(0)
xmppClient.connection.socket.setKeepAlive(true, 10000)
redisClient = redis.createClient();
redisClient.subscribe(redisSubChan);
redisClient.on("message", function(channel, message) {
console.log('received message');
console.log(message);
message = JSON.parse(message);
//send the messages to google ccs server via xmpp
var payload = {
"to": message.to,
"message_id": message.message_id,
"data": message.data,
"time_to_live": message.time_to_live,
"delay_while_idle": message.delay_while_idle
};
var jsonPayload = JSON.stringify(payload);
console.log(jsonPayload);
var ackToDevice = new xmpp.Element('message', {'id': ''}).c('gcm', {xmlns: 'google:mobile:data'}).t(jsonPayload);
console.log('prepared message');
console.log(ackToDevice.root().toString());
xmppClient.send(ackToDevice);
console.log('sent!!!');
});
xmppClient.on('online', function() {
console.log("online");
});
xmppClient.on('connection', function() {
console.log('online');
});
xmppClient.on('stanza',
function(stanza) {
if (stanza.is('message') && stanza.attrs.type !== 'error') {
// Best to ignore an error
console.log("Message received");
//Message format as per here: https://developer.android.com/google/gcm/ccs.html#upstream
var messageData = JSON.parse(stanza.getChildText("gcm"));
if (messageData && messageData.message_type != "ack" && messageData.message_type != "nack") {
var ackMsg = new xmpp.Element('message', {'id': ''}).c('gcm', {xmlns: 'google:mobile:data'}).t(JSON.stringify({
"to": messageData.from,
"message_id": messageData.message_id,
"message_type": "ack"
}));
//send back the ack.
xmppClient.send(ackMsg);
console.log("Sent ack");
//receive messages from ccs and give it to PHP workers
gearClient.submitJob(gearmanJobName, JSON.stringify(messageData), {background: true});
} else {
//Need to do something more here for a nack.
console.log("message was an ack or nack...discarding");
}
} else {
console.log("error");
console.log(stanza);
}
});
xmppClient.on('authenticate', function(opts, cb) {
console.log('AUTH' + opts.jid + ' -> ' + opts.password);
cb(null);
});
xmppClient.on('error', function(e) {
console.log("Error occured:");
console.error(e);
console.error(e.children);
});
I am able to receive the messages from ccs server but can not send the downstream message from redis on message callback.
I get the following error
error
{ name: 'message',
parent: null,
attrs:
{ id: '',
type: 'error',
to: '1026645507924#gcm.googleapis.com/8DF23ED7',
'xmlns:stream': 'http://etherx.jabber.org/streams' },
children:
[ { name: 'gcm',
parent: [Circular],
attrs: [Object],
children: [Object] },
{ name: 'error',
parent: [Circular],
attrs: [Object],
children: [Object] } ] }
I tried to print(followed node xmpp) the xmpp stanza before sending and its same
//log of my message
<message id=""><gcm xmlns="google:mobile:data">{"to":"APA91bHIGZcbePZ-f1jSyWQkBAJMHorHJiwgtN1GWITzcHf6uyVOZ3k7AasUiB-vBix32ucSypin3xDTYmoxqSc_ZmTDTuKjuDQ8BPQLpC41SqYRimm-hn34ZjSAF4uQO0OP1LSbqUxjh2WF0K5n4KyD3-Vn8ghASQ","message_id":84,"data":{"test":"sample data to send"},"time_to_live":0,"delay_while_idle":false}</gcm></message>
as they mentioned in documentation(Request format). What is wrong with my code ?
I had the same issue. It nearly drove me crazy but in the end it was just an Invalid JSON format error.
I suppose messageData.from or messageData.message_id wasn't converted to correct JSON format. In my case I passed a scalar and JSON.stringify() didn't converted it to a string. Hence the result was --> "message_id": 1234 and not "message_id": "1234"
The quick answer is you can not use CCS (XMPP) without having your project whitelisted. If you try using smack library instead, you will get an error saying that your project is not whitelisted.
Related
In my project, I need to send a notification from server to client. I am able to send notifications from FCM console but when I send a notification from server to client, remoteMessage.getNotification() always return null. While data is received correctly. When I send both data and notification only data is a non-null while the notification is null.
I already checked this question. But the solution isn't working for me.
Below is a snippet of client and server side code along with a screenshot while debugging client app.
Client App:(onMessageReceived)
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
Log.e(TAG, "From: " + remoteMessage?.from)
// Check if message contains a data payload.
if ((remoteMessage?.data?.size ?: 0) > 0) {
Log.e(TAG, "Message data payload: ${remoteMessage?.data}")
}
val a = remoteMessage?.notification
if (a != null) {
Log.e(TAG, "Message Notification Body: " + remoteMessage.notification?.body)
}
}
server side code(node.js)
var request = require('request');
// Set the headers
var headers = {
'Content-Type':'application/json',
'Authorization': 'key=AIzaSyAzMLMp....'
}
// Configure the request
var options = {
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: headers,
form: {
"to": "eZoeSIRba6g:AP...",
"notification" : { "body" : "my body"} }
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
console.log(body + " error : " + error)
})
while if I use following part then the code works fine.
form: {
"to": "eZoeSIRba6g:APA91bEYrP...",
"data" : { "body" : "my body"} }
Screenshot while debugging the app.(Check value of variable 'a')
If someone has any idea of how to resolve this issue then please help me.
Thank you in advance.
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
"key_1" : "Data for key one",
"key_2" : "Hellowww"
}
}
Use a JSON like this , then your onMessageReceived will be called.
I am looking for to send a notification from a Nodejs server, but I am getting some errors that I don't know how solve it. Could someone help me? I found this possible solution on Internet --> URL
This is my code in nodejs
var FCM = require('fcm-push');
function sendNotification (){
var serverKey = 'AAAAJnK3Ing:AP-(more caracters)AwAlBL_CvXIkFM2UufYZHYkvhC7FP3Tu16mlI';
var fcm = new FCM(serverKey);
var message = {
to: 'd2b2v(more caracters token)DUmAXqU-uHptJJLRPXukl',
/*data: {
your_custom_data_key: 'your_custom_data_value'
},*/
notification: {
title: 'notification',
body: 'This is a notification from node'
}
};
//callback style
fcm.send(message, function(err, response){
if (err) {
console.log("****************************************************")
console.log(message)
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});
//promise style
fcm.send(message)
.then(function(response){
console.log("Successfully sent with response: ", response);
})
.catch(function(err){
console.log("----------------------------------------------------")
console.log("Something has gone wrong!");
console.error(err);
})
}
module.exports = {
sendNotification
}
I am getting this error
Try to check if your firewall allow to connect on 443 port. It seems like it can't create the connection.
I am using node-xcs module to create XMPP CCS server in NodeJs, But in that module there is no method to send ACK message which is required to send back to FCM.
do you use fcm-node package for get FCM token . using that we can register device look at my full coding i have use it for send notification to mobile
var FCM = require('fcm-node');
exports.SendNotification = function(msg,title,type,id,user_id,api_token)
{
var fcm = new FCM(constants.serverKey);
var message = {
registration_ids : api_token,
notification: {
title: title,
body:msg
},
data: {
type: type,
id:id,
user_id:user_id
}
};
fcm.send(message, function(err, response){
if (err)
{
console.log("Error for Send Notification",err);
return;
}
else
{
console.log("Successfully sent Notification", response);
return;
}
});
}
and than call this function like this
msg='new notification for you'
title='Hello'
id='34'
user_id='34'
result='api_token'//save this token in database and retrive using user_id
SendNotification(msg,title,'START_APPOINTMENT',id,user_id,result);
push: function (tokens, message) {
var privateKey = 'xxx';
var appId = 'xxx';
var auth = btoa(privateKey + ':');
var req = {
method: 'POST',
url: 'https://push.ionic.io/api/v1/push',
headers: {
'Content-Type': 'application/json',
'X-Ionic-Application-Id': appId,
'Authorization': 'basic ' + auth
},
data: {
"tokens": tokens,
"notification": {
"alert": message
}
}
};
// Make the API call
$http(req).success(function (resp) {
// Handle success
console.log(tokens);
console.log(resp);
}).error(function (error) {
// Handle error
console.log("Ionic Push: Push error...");
});
}
I am using the above code to push notifications. It gets into the
success handler and prints the token used and message id, to the console. But when i check the status with the message id, its saying Push Error Code 101.
When i use the same token using Ionic.io website for one time notification screen, it works !
How can i make this working using angular code ?
Thanks !
I need to push GCM from node, I am using node-gcm, but I am getting ENOTFOUND error
var gcm = require('node-gcm');
var gcmMessage = new gcm.Message({
collapseKey: 'notify',
delayWhileIdle: false,
timeToLive: 3600,
data: {
title: "Hai",
message: "Message",
}
});
var gcmIds = ['<myid>'];
var sender = new gcm.Sender('<mysender id>',{'proxy':'<proxyip>:8080'});
sender.send(gcmMessage, gcmIds, 4, function(err, ret){
console.log('>>> sendGcm: ', err, ret);
});
I am getting error
sendGcm: { [Error: tunneling socket could not be established, cause=getaddr
info ENOTFOUND] code: 'ECONNRESET' } null