Giter VIP home page Giter VIP logo

node-xcs's Introduction

node-xcs

node-xcs is a NodeJS implementation of Google's Firebase Connection Server implemented using XMPP Protocol.

Build Status Join the chat at https://gitter.im/guness/node-xcs

Getting Started

Install:

npm install node-xcs

Import:

var Sender = require('node-xcs').Sender;
var Result = require('node-xcs').Result;
var Message = require('node-xcs').Message;
var Notification = require('node-xcs').Notification;

Initiate Sender:

var xcs = new Sender(SenderID, ServerKey);

Build Notification:

var notification = new Notification("ic_launcher")
    .title("Hello buddy!")
    .body("node-xcs is awesome.")
    .build();

Build Message:

var message = new Message("messageId_1046")
    .priority("high")
    .dryRun(false)
    .addData("node-xcs", true)
    .addData("anything_else", false)
    .addData("awesomeness", 100)
    .deliveryReceiptRequested(true)
    .notification(notification)
    .build();

Send Message:

xcs.sendNoRetry(message, to, function (result) {
    if (result.getError()) {
        console.error(result.getErrorDescription());
    } else {
        console.log("message sent: #" + result.getMessageId());
    }
});

Functions

Currently there are two functions to send message, however one of them has not been implemented yet.

Send Message

Use sendNoRetry to send a message.

xcs.sendNoRetry(message, to, [callback(result)]);
Argument Details
message Message to sent (with or without notification)
to A single user, or topic
callback (optional) function(result) Result

End Connection

xcs.end;

Events

Events are defined as below.

xcs.on('message', function(messageId, from,  data, category){}); // Messages received from client (excluding receipts)
xcs.on('receipt', function(messageId, from,  data, category){}); // Only fired for messages where options.delivery_receipt_requested = true

xcs.on('connected', console.log);
xcs.on('disconnected', console.log);
xcs.on('online', console.log);
xcs.on('error', console.log);
xcs.on('message-error', console.log);

Example

var Sender = require('node-xcs').Sender;
var Message = require('node-xcs').Message;
var Notification = require('node-xcs').Notification;
var Result = require('node-xcs').Result;

var xcs = new Sender(SenderID, ServerKey);

xcs.on('message', function(messageId, from, data, category) {
	console.log('received message', arguments);
}); 

xcs.on('receipt', function(messageId, from, data, category) {
	console.log('received receipt', arguments);
});

var notification = new Notification("ic_launcher")
    .title("Hello buddy!")
    .body("node-xcs is awesome.")
    .build();

var message = new Message("messageId_1046")
    .priority("high")
    .dryRun(false)
    .addData("node-xcs", true)
    .addData("anything_else", false)
    .addData("awesomeness", 100)
    .deliveryReceiptRequested(true)
    .notification(notification)
    .build();

xcs.sendNoRetry(message, to, function (result) {
    if (result.getError()) {
        console.error(result.getErrorDescription());
    } else {
        console.log("message sent: #" + result.getMessageId());
    }
});

Echo Client

xcs.on('message', function(_, from, data) {
	xcs.send(from, data);
});

Tests

There are several nice tests. In order to test locally just call:

npm install mocha
npm test

If you also want to test against google servers, you should export some environment variables before starting the test.

export FCM_SERVER_KEY='My_Super_awesome_api_key'
export FCM_SENDER_ID=007
export TRAVIS_PULL_REQUEST=false

Notes on XCS

  • The library still being working on it, so there may be serious problems, use it at your own risk.
  • No events are emitted from XCS or this library when a device new registers: you'll have to send a message from the device and process it yourself
  • Occasionally, FCM performs load balancing, so the connection is sometimes restarted. This library handles this transparently, and your messages will be queued in these situations.
  • This library auto sends acks for receipts of sent messages, however google side receipt reporting is not reliable.

Disclaimer

Based on a work at https://github.com/jacobp100/node-gcm-ccs

node-xcs's People

Contributors

chaitanya-bhagavan avatar dependabot[bot] avatar gitter-badger avatar guness avatar javamonn avatar longsight avatar redism avatar saharh avatar xiaohang0316 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-xcs's Issues

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'write' of null

When having network problems, I received this Warning, though when network had recovered the connection restored without problems.

image

on "line 362", I'm periodically sending testing messages to FCM just to check connection:

image

// проверка соединения с FCM:
setInterval(function () {
    let from = "111222333";
    let message = new Message(from + "_ack").priority("high").dryRun(true)
        .addData("messageId", from)
        .deliveryReceiptRequested(true)
        .build();

    logger.info('Check connection... ' + new Date());

    xcs.sendNoRetry(message, from, function (result) {
        if (result.getError()) {
            if (result.getError() === 'BAD_REGISTRATION')
                logger.info("Check connection ok");
            else
                logger.error("Check connection ERROR! " + result.getError());
        } else {
            logger.info(`Check connection ${senderXcs.name} message sent: #` + result.getMessageId());
        }
    }); // Messages received from client (excluding receipts)

}, 120000);

exception on xcs.start after updating to 0.1.8

windows 10, node 14.18.1

var xcs = new Sender(...)

xcs.start();

TypeError: this.client.socket.setTimeout is not a function
at Sender.start (C:...\FCM_XMPPServer\node_modules\node-xcs\google\Sender.js:146:24)
at Object. (C:...\FCM_XMPPServer\Index.js:424:7)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47

Consider updating docs to use senderId rather than projectId

I think it's worth considering updating at least the README to use senderId rather than projectId. I for one ran into an initial configuration issue by attempting to create a new sender with my GCP project ID instead of the GCM sender ID - didn't notice the discrepancy until I took a look at the GCM reference docs. Would you accept a quick PR for this?

Allow selection for FCM testing port 5236

Is it possible to add an argument to Sender object to specify the port 5236 for testing and development purposes instead of using port 5235 which should be only used for production.

Something like

// Production
fcm-xmpp.googleapis.com:5235

// Testing
fcm-xmpp.googleapis.com:5236

var xcs = new Sender(<server id>, <server key>, <boolean isProduction>);

Can not receive message

I would like to send message from device to the app server.

  1. I run the following command to send a message to Firebase and it is successful with a valid message id:
    curl -X POST --header "Authorization: key=" --header "Content-Type: application/json" ht-d "{"to":"/topics/foo-bar","notification":{"body": "HEY YO"}}"

{"message_id":5634438218616813911}

  1. But when I run the node code in server with the right configuration:

xcs.on('message', function(messageId, from, data, category) {
console.log('received message', data);
});

There is no message in the console.

Please advise what I am missing.

EventEmitter memory leak.

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at Client.addListener (events.js:160:15)
at Client.Session._addConnectionListeners (D:\nodeWorkspace\firstProject\nod e_modules\node-xmpp-client\lib\session.js:178:10)
at Client.Session._setupSocketConnection (D:\nodeWorkspace\firstProject\node _modules\node-xmpp-client\lib\session.js:49:8)
at Client.Session (D:\nodeWorkspace\firstProject\node_modules\node-xmpp-clie nt\lib\session.js:27:10) at Client._useStandardConnect (D:\nodeWorkspace\firstProject\node_modules\no de-xmpp-client\lib\Client.js:152:11)
at Client.connect (D:\nodeWorkspace\firstProject\node_modules\node-xmpp-clie nt\lib\Client.js:137:8) at Client. (D:\nodeWorkspace\firstProject\node_modules\node-xcs\g oogle\Sender.js:54:25)
at Client.emit (events.js:92:17)
at Connection.emit (events.js:92:17)
at Connection.onClose (D:\nodeWorkspace\firstProject\node_modules\node-xmpp- core\lib\Connection.js:424:10)
at CleartextStream.emit (events.js:117:20)
at tls.js:693:10
at process._tickCallback (node.js:419:13)

No option to set XMPP connection to reconnect

Hello,
I believe that there is one issue with the current implementation, related to the possibility to reconnect to the FCM server in case of lost of connection.
The xmpp-node library has an option to pass a parameter { reconnect: true} to attempt to reconnect the WebSocket, in case the connection is lost. This is very important for the reliability of the Push Notifications, in the case your server recover from a network loss.
The simple solution would be to add this to the parameter passed to Sender(), but I think the best solution, to be as generic as possible, is to change the Sender to accept a configuration object, where you can set the current values, plus some extra values, as for example the reconnect on the xmpp.Client.

XMPP authentication failure

When i run the example on my own pc I get 'XMPP authentication failure'.
I give my SenderID, ServerKey to 'Sender' but getting the exception.
Why I cant run it on my pc?
Do I need a NodeJS server with https? Thank you

Sender._send fails due to API change in node-xmpp-client v3.0.1

Hi,

I get an error thrown as soon as I receive an upstream message:

/Users/daniel/project-dir/node_modules/node-xcs/google/Sender.js:128
        var message = new xmpp.Stanza.Element('message').c('gcm', {xmlns: 'google:mobile:data'}).t(JSON.stringify(json));
                      ^

TypeError: xmpp.Stanza.Element is not a function
    at Sender._send (/Users/daniel/project-dir/node_modules/node-xcs/google/Sender.js:128:23)

Looked into this a bit and node-xmpp-client released version 3.0.1 about a week ago and gets installed by node-xcs due to the ^3.0.0 glob. When I pin the node-xmpp-client dep specifically at 3.0.0 I don't get this error.

Node upgrade (12) brokes connection start

Since I've upgraded to node 12.18.2 the xmpp connection doesn't start itself as the doc says.
I had to upgrade the library from 0.1.5 version to 0.1.7 and add xcs.start() just after the import.

No "xcs.start()" is present in README.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.