GithubHelp home page GithubHelp logo

jlcvp / fcm-node Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nandarustam/fcm-push

125.0 125.0 48.0 558 KB

A Node.JS simple interface to Google's Firebase Cloud Messaging (FCM) for Android & iOS & Web Notification and data push

License: MIT License

JavaScript 100.00%

fcm-node's People

Contributors

buu700 avatar cesardmoro avatar crackjack avatar endast avatar jlcvp avatar mihristov avatar nandarustam avatar nigelzor avatar nswbmw avatar snyk-bot avatar sofiapm 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  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  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

fcm-node's Issues

I had a solution for a bug (app was already initialized)

Hi, when you send two or more requests by using fcm-node in a .js script there is an error that says that the app already exists.

In the node_modules/fcm-node there is a file called fcm.js

My solution is to edit this file, like this (I had already done this and it works):

else{ //accountkey object passed, new SDK 'de-promisefy' use <--- STAYS THE SAME
if(firebaseadmin.apps[0]){
firebaseadmin.apps[0].delete()
}
firebaseadmin.initializeApp({
credential: firebaseadmin.credential.cert(accountKey)
});
this.send = function(payload, _callback){ <--- STAYS THE SAME

it is not working

A very bad library actually. lack of information and lack of guide to send messages to topics.
priority and content_available are not working and throw error.

Send fcm synchronous call available ?

Hi,

I'm facing following issue,

 var isSent =false

for(let token of tokens){ 
 isSent = await fcm.send(message, async (err, response)=> {
          if (err) {
                        console.log("Something has gone wrong!");
                        return false;
                    } else {
                        console.log("Successfully sent with response: ", response);
                        return true;
                    }
                });
}

Here isSent is always undefined , Is there is any synchronous call to send FCM messages ?

fcm.send's callback is called twice

fcm.send's callback is called twice.
please help!

fcm.send(message, function(err, response){
if(err) {
console.log("Something has gone wrong!")
} else {
console.log("Successfully sent with response: ", response) << called twice!
}
})

Buffer.js Error Unknown Encoding

It successfully send push notification but then it crash in buffer.js as follows :

Successfully sent with response:  {"multicast_id":4628760918450252159,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1476179380585829%1243539d1243539d"}]}
buffer.js:618
          throw new TypeError('Unknown encoding: ' + encoding);
          ^

TypeError: Unknown encoding: {"multicast_id":4628760918450252159,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1476179380585829%1243539d1243539d"}]}
    at Buffer.write (buffer.js:618:17)
    at fromString (buffer.js:113:26)
    at new Buffer (buffer.js:58:12)
    at createWriteReq (net.js:719:38)
    at Socket._writeGeneric (net.js:671:11)
    at Socket._write (net.js:694:8)
    at doWrite (_stream_writable.js:292:12)
    at clearBuffer (_stream_writable.js:396:7)
    at Socket.Writable.uncork (_stream_writable.js:230:7)
    at ServerResponse.OutgoingMessage.end (_http_outgoing.js:586:21)
[nodemon] app crashed - waiting for file changes before starting...

I tried it on Mac OSX El Capitan if that helps.
Thanks

Turn on display on notification

this is not really an issue because the library is excellent... anyway i'm wondering if there is a fast way to force the screen on (when the device is locked) with a notification.
Is there any parameter or setting that we can use to do this? Thank you

Invalid Firebase app name "null" provided. App name must be a non-empty string.

After updating to 1.5 I get this error.

I'm using this method:

const FCM = require('fcm-node');
const serverKey = require('../private/firebase-adminsdk.json');
const fcm = new FCM(serverKey);

Any Idea what could cause this?

Error: Invalid Firebase app name "null" provided. App name must be a non-empty string.
at FirebaseAppError.FirebaseError [as constructor] (/home/waggldaggl/WebstormProjects/beercoin-backend-nodejs/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/home/waggldaggl/WebstormProjects/beercoin-backend-nodejs/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseAppError (/home/waggldaggl/WebstormProjects/beercoin-backend-nodejs/node_modules/firebase-admin/lib/utils/error.js:122:28)
at FirebaseNamespaceInternals.initializeApp (/home/waggldaggl/WebstormProjects/beercoin-backend-nodejs/node_modules/firebase-admin/lib/firebase-namespace.js:64:19)
at FirebaseNamespace.initializeApp (/home/waggldaggl/WebstormProjects/beercoin-backend-nodejs/node_modules/firebase-admin/lib/firebase-namespace.js:392:30)
at new FCM (/home/waggldaggl/WebstormProjects/beercoin-backend-nodejs/node_modules/fcm-node/lib/fcm.js:159:23)
at Object.<anonymous> (/home/waggldaggl/WebstormProjects/beercoin-backend-nodejs/utils/firebase_helper.js:5:13)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)

Getting InvalidRegistration error

I have added changes as you had suggested.
Even after adding the FCM key and the device token. I'm getting this error and failure to send the notification.

Please help me out. Thank you!

{"error":"InvalidRegistration"}

Error : socket hang up ( it working fine but suddenly stop from yesterday.)

Hi it was working fine since last month but suddenly stop from yesterday and following error.

Error: socket hang up
at createHangUpError (_http_client.js:302:15)
at Socket.socketCloseListener (_http_client.js:334:23)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at TCP._handle.close [as _onclose] (net.js:511:12) code: 'ECONNRESET' }

it might due to content length please go through the below link.
https://stackoverflow.com/questions/18692580/node-js-post-causes-error-socket-hang-up-code-econnreset

the error code:TopicsMessageRateExceeded response

Recently got an error response “TOPICS_MESSAGE_RATE_EXCEEDED” which I never got in the past.
It happened from 2016/8/25 until now.
My node server is simply sending 10 messages to my client with “topics/global” in loop.
It has been running well since year ago. But recently it became sending error but only succeed for 2 messages in 10 messages.
image

Could not find a declaration file for module 'fcm-node'.

I am using a cordova based hybrid mobile app. My app is built using [email protected]. I need to integrate fcm push-notifications to my app, I'm using [email protected].

I added the package into my package.json.
By doing yarn add fcm-node.
Then I imported it in my controller file, by writing code like =>
import FCM from 'fcm-node';, /
import * as FCM from 'fcm-node';/
also tried var FCM = require('fcm-node');

When I install the app or try to run it on browser, i get an error:

    Error: Could not find module `fcm-node` imported from `stock/controllers/notifications`
    at missingModule (vendor.js:252)
    at findModule (vendor.js:263)
    at Module.findDeps (vendor.js:173)
    at findModule (vendor.js:267)
    at requireModule (vendor.js:29)
    at Class._extractDefaultExport (vendor.js:133203)
    at Class.resolveOther (vendor.js:132900)
    at Class.superWrapper [as resolveOther] (vendor.js:60493)
    at Class.resolveController (vendor.js:27961)
    at Class.resolve (vendor.js:27811)

And even in my vs-code its highlighted with error
Screen Shot 2019-05-27 at 1 03 48 PM

Same issue with the require statement too.

I even tried installing by npm install @types/fcm-node. But still no luck.

Could you please help me resolve this ?

Working iOS-Example?

Hey,

I have the following behaviour: iOS-Users receive messages send through the firebase-console BUT not send via the script. Android-Users receive both.

I tried it with single-device-targeting, topic-targeting and with/without priorities.

Is there anything else to be aware of? Are pushes send from the HTTP-API using the dev-cert instead of the prod-cert?

I really would appreciate a working example.. Here is my test-script:

var process = require('process');
var winston = require('winston');

process.title = 'fanradio.streamstatus';

var firebase = require('firebase');

winston.info('Logging in...');

firebase.initializeApp({
  serviceAccount: './service.json',
  databaseURL: 'MYURL',
});

winston.info('Authenticated via Firebase.');

var FCM = require('fcm-node');
var fcm = new FCM('MYKEY');

var topic = 'MYSINGLEDEVICETARGET';
// topic = '/topics/test';
var push = { text: 'foo' };

fcm.send({
  to: topic,
  notification: { priority: 'high', body: push.text },
}, function (error, response) {
  if (error) {
    winston.warn('A pushmessage could not be send', { error });
    return;
  }

  winston.info('Push was send', response);
});

firebase-admin version

Hello,
Would you please upgrade your package.json to use newer version of firebase-admin, now npm shouts:

Step #1: npm WARN deprecated [email protected]: This version is no longer maintained. Please upgrade to the latest version.
Step #1: npm WARN deprecated [email protected]: This version is no longer maintained. Please upgrade to the latest version.
Step #1: npm WARN deprecated [email protected]: This version is no longer maintained. Please upgrade to the latest version.

How to initialize many apps?

Hello.

I develop FCM to send 3 apps using this library.
but showing follow error messages.
How to set this case?

  • code
    const serverKey_10001 = require('../config/pushkey/b.json');
    const serverKey_10002 = require('../config/pushkey/a.json');
    const fcm_zeroshop = new FCM(serverKey_10001, undefined, 'zeroshop');
    const fcm_hidoc = new FCM(serverKey_10002, undefined, 'hidoc');

fcm_zeroshop.send(message, (err, response) => {
});

-error message
The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.

Successfully with response but client doesn't get notification

Successfully sent with response: {"multicast_id":5979505685602066267,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1479724040861830%0000000000000000"}]}
I put my own server key and message token
and client app is implemented with FirebaseMessagingService and FirebaseInstanceIDService.
When I run the server, it returns success response like above message. However, client app doesn't get any notification. what am I missed?

what is registration token, collapse key, and data?

var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
    to: 'registration_token', 
    collapse_key: 'your_collapse_key',

    notification: {
        title: 'Title of your push notification', 
        body: 'Body of your push notification' 
    },

    data: {  //you can send only notification or only data(or include both)
        my_key: 'my value',
        my_another_key: 'my another value'
    }
};

I am ok to create a working example code though, I am not finding what should I put on the above mentioned field for registration token, collapse key and the data keys.

Successfully with response but client doesn't get notifications

Successfully sent message: { results: [ { messageId: '0:1511508709940437%6f2857526f285752' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 5428886452395349000 }

i put own server details.when i try to send notification using firebase console it successfully send notification but i am unable to send notification using fcm-node.

Multiple recipients, same message, different data payloads

Hi there, I've been using fcm-node in my nodejs app for a while now and it's been great. But there are some cases where I have my doubts on how to proceed:
I have some cases where I need to send a certain type of notification with user-specific payloads but with the same push notification message. The approach I've been using nowadays is, IMHO inefficient and I'd like to share it with you and ask if there is a way of doing this in a better way.

I'm currently creating separate notifications and sending each one with the same message, but different payloads (aka ids of one of my classes, so that the client knows how to react to the notifications when they open it). So if I have lotsof this messages, my server ends up iterating them all, which I find mostly inefficient.

I work as well with mandril-api and they have a great approach to send bulk emails with the same template, but different payloads and that's what I've been searching to do with fcm-node, to no success. Can someone help me with the reason why there is no such feature, or if there is, which feature I can use to send bulk notifications with the same message, but different data payloads?

Thanks in advance!

Did fire the callback?

image
I don't know whether is me wrote the code wrote or something, it just can't fire up the callback function?

InvalidServerResponse

Since last two days, InvalidServerResponse error gets displayed every single time.
No code changes and this thing was working before.

How to use rich text notification, i want to send image that display event if app is in background.

How to use rich text notification, i want to send image that display event if app is in background.

so i want to add "mutable_content": true,

my current code is as below.

var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
                                            to: existToken.device_token, 
                                        // collapse_key: 'your_collapse_key',
                                            
                                            notification: {
                                                title: 'title', 
                                                body: 'New Promotion.' 
                                            },
                                            
                                            data: {  //you can send only notification or only data(or include both)
                                                title: post.title,
                                                image: 'image_url'
                                            }
                                        };
                                        
                                        fcm.send(message, function(err, response){
                                            if (err) {
                                                console.log("Something has gone wrong!");
                                            } else {
                                                console.log("Successfully sent with response: ", response);
                                            }
                                        });

Migrating guide from fcm-node to firebase-admin

As per the warning on Readme, it is advisable to use firebase-admin instead of fcm-node. I followed the link to documentation but am not sure how to implement it.

It would be better to have a wiki conveying how to migrate from fcm-node to firebase-admin. Something like what exactly I need to change if I have implemented fcm-node and want to replace it with firebase-admin.

Any help would be appreciated. Thanks.

No way to set Priority for data messages

Hi,
I've tried adding options to the message payload, but I always get an error like this:

{ code: 'messaging/invalid-payload',
message:
'Messaging payload contains an invalid "options" property. Valid properties are "data" and "notification".' },
codePrefix: 'messaging'
}

Please let me know if there is a way to set priority

FCM Failed registration id

fcm.send(message, function(err, response) { if (err) { let errorData = JSON.parse(err); let statusData = { 'success' : errorData.success, 'failure' : errorData.failure } updateStatus(pushId, statusData.success, statusData.failure); logger.error = 'Notification Not Sent To Few Users'; res.status(400).json(statusData); } else { let resData = JSON.parse(response); let statusData = { 'success' : resData.success, 'failure' : resData.failure } updateStatus(pushId, statusData.success, statusData.failure); logger.info(response); res.status(200).json(response); } });
Is there any way to find out the list of registration_id's for which the notification is failed!

Sending notifications in parallel gives incorrect response

Hey,

I'm having an issue where if I send two notifications in parallel, one to an ID of a device I know exists and one to a dummy ID, I get an 'InvalidRegistration' error from both .send() functions. The device does receive the 1st notification.

This causes an issue because when I get an error I want to remove that particular device token from the users tokens on the server. Currently it removes both the invalid token and the valid one resulting in the user having zero tokens and not receiving any future notifications.

Here's a gist of the script to cause this error:
https://gist.github.com/alexfoxy/1e8cdb7c3f127e6594e8e963e39224e6

You should get an output of:

FCM.send
FCM.send
{"multicast_id":8969037943863178607,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
{"multicast_id":8969037943863178607,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

If you send them in series it works correctly [ i.e. by moving send2() into the callback of send1() ] - output:

FCM.send
{"multicast_id":7502545296558413858,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1470046298701173%108c2029108c2029"}]}
FCM.send
{"multicast_id":8933073754773609814,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

This might be a bug in Firebase itself so I'm also raising this as an issue with them.

A

ReferenceError: serverKey is not defined

I just pulled the latest code but found the runtime error below

ReferenceError: serverKey is not defined
at new FCM (/node_modules/fcm-node/lib/fcm.js:13:26)

It seems from the last checkin that uses the variable serverKey no longer exist

not working in nodejs v 4.7.0

TypeError: Cannot read property 'navigator' of undefined
/fcm-node/node_modules/firebase-admin/lib/database/database.js:39:492

NotAuthorizedError

// Method to generate manager with Q promises
function getFcmManager () {
  var serverKey = API_KEY;
  var fcm = new FCM(serverKey);
  // Manager
  var fcmManager = {
    // Send to device holding token
    send: function (token) {
      return Q.Promise(function (resolve, reject) {
        // Message payload
        var message = {
          "notification":{
            "title": "Notification title",  //Any value
            "body": "Notification body",  //Any value
            "sound": "default", //If you want notification sound
            "click_action": "FCM_PLUGIN_ACTIVITY",  //Must be present for Android
            "icon": "fcm_push_icon"  //White icon Android resource
          },
          "data":{
            "param1": "value1",  //Any data to be retrieved in the notification callback
            "param2": "value2"
          },
            "to": token, //Topic or single device
            "priority": "high", //If not set, notification won't be delivered on completely closed iOS app
            "restricted_package_name": "" //Optional. Set for application filtering
        };
        // Push
        fcm.send(message, function(err, response){
          if (err) {
            console.log("FCM: Something has gone wrong!", err);
            reject();
          } else {
            console.log("FCM: Successfully sent with response: ", response);
            resolve();
          }
        });
      });
    }
  }
  // Return
  return fcmManager;
}

Restore MIT license?

Hey there, I'd love to use this fork, but it looks like you changed the project from MIT to GPL when you forked it. Any particular reason you decided to do that? Any chance you could re-release it as MIT again?

Thanks!

tag field?

I'm new to push notifications. It seems like what I really want is collapse_key, where the user's notification tray combines or overwrites a notification. but, it only works when the receiving device is offline?

how do I get that functionality also when it's online? some documentation online mentions FCM supporting a tag key, but it's not apparent if I can use it with fcm-node

what are my options? thanks!

Send function always logs an error

The following code always logs an error.

fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});

Printing err to console shows a JSON object of the format
{
"multicast_id": 78797070,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:nsgjkndklg"
}
]
}

Suggestion:
fcm.send(message, function(jsonResponse){
var response = JSON.parse(jsonResponse);
if (response["failure"] > 0) {
console.log("Something has gone wrong!");
}
else {
console.log("Successfully sent");
}
});

[iOS] notification not received although it's successfully sent ("success":1)

I have installed my new app on my iPhone 5s using Xcode, and the FCM registration token is successfully given to me when I start the app.
When I use this token in the Firebase console (console.firebase.google.com), it works!
But when I send it with fcm-node, it doesn't :/
Note that my config is working for Android.
This is my test code:

const to = '<FCM registration token of my device goes here>'

const notification = {
  title: 'test 4',
  body: 'test 4',
}

const payload = {
  to,
  notification,
  priority: 'high',
  content_available: true, // tried without too
}

console.log('Sending to', to)

fcm.send(payload, (error, response) => {
  if (error) {
    console.error('Notification error:', error)
  } else {
    console.log('Notification sent:', response)
  }
})

And I get:

Sending to <token>
Notification sent: {"multicast_id":8677751413683945576,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1475855513649189%f587d512f587d512"}]}

But nothing arrives on the phone! (I have tried with the app in the background as well as killed)
Again, I do receive the ones sent through the Firebase console, so my setup is correct imo...

Multiple instances of FCM

Hi. I have two mobile apps managed by a nodejs server which is responsible for sending notifications to both apps. Since each mobile app has it's own Firebase account, my nodejs server needs to keep two instances of FCM simultaneously.
Current behavior:
Version: "fcm-node": "1.4.1"
When I start the nodejs server I get the following message:

Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.
at FirebaseAppError.FirebaseError [as constructor] (/usr/src/app/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/usr/src/app/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseAppError (/usr/src/app/node_modules/firebase-admin/lib/utils/error.js:122:28)
at FirebaseNamespaceInternals.initializeApp (/usr/src/app/node_modules/firebase-admin/lib/firebase-namespace.js:68:23)
at FirebaseNamespace.initializeApp (/usr/src/app/node_modules/firebase-admin/lib/firebase-namespace.js:392:30)
at new FCM (/usr/src/app/node_modules/fcm-node/lib/fcm.js:159:23)

Can I request a change (a second parameter to the FCM constructor) so that I can start using the lib?
Reference:
https://firebase.google.com/docs/reference/admin/node/admin#.initializeApp

fcm.send always called more than one time.

Following is my code

var push = function (req, res) {
    console.log('1');
    var id = req.body.id || 0;
    var FCM = require('fcm-node');
    var database = req.app.get('database');
    var output = {};
    var client_token;
    var ct = parseInt(Date.now());
    if (database) {
        var al3 = { s: 'ss' };
        database.TkModel.find({ id: id }, function (err, results) {
            if (err) {
                console.log('TkModel.find err');
                output.status = 401;
                res.send(output);
                return;
            }
            if (results.length > 0) {
                client_token = results[0]._doc.ptk;
                var serverKey = 'AAAAMZQpZhw:AP************************************************-';
                var push_data = {
                    to: client_token,
                    notification: {
                        title: "title",
                        body: "body.",
                        sound: "default",
                        icon: "fcm_push_icon"
                    },
                    priority: "high",
                    restricted_package_name: "com.app.metacoin",
                    data: al3
                };
                var fcm = new FCM(serverKey);
                console.log('444');
                fcm.send(push_data, function (err, response) {
                    console.log('55');
                    if (err) {
                        output.status = 700;
                        res.send(output);
                        return;
                    }
                    console.log('2222');
                    output.status = 100;
                    // res.send(output);
                    return;
                    console.log('3');
                });
            } else {
                console.log('TkModel.find: results.length==0 -->err');
                output.status = 411;
                res.send(output);
            }
        });
    } else {
        console.log('push1: no database');
        output.status = 410;
        res.send(output);
    }
};
module.exports.push = push;```

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.