Firebase notification for Flutter application suddenly stopped

Viewed 593

I am trying to integrate FCM in my flutter application. I have done all the connections setting for both android and iOS. When I send notification with the help of Cloud messaging test notification feature, the notifications are properly received in the device.

I have written a function script which automatically sends the notification at a given time. When I deployed the feature around 2 weeks back, it worked almost as expected. Most of the clients were receiving notification as they should. However, past few days the notification has completely stopped reaching the client.

My function log in firebase console suggest that the notifications were sent, but the report shows that non of my users are receiving the notification.

I am certain that there is something wrong with the the way I wrote the payload.

Here is my code

exports.sendFollowerNotification = functions.database.ref('/notifications/{notificationID}')
.onCreate(async (snapshot, context) => {
  const notificationID = context.params.notificationID;
  const notificationData = snapshot.val();

  const getDeviceTokensPromise = admin.database()
    .ref('/DeviceTokens').orderByChild("subscribed").equalTo("1").once('value');


  //list all tokens in a array
  let tokensSnapshot;
  let tokens;

  const results = await Promise.all([getDeviceTokensPromise]);
  tokensSnapshot = results[0];
  if (!tokensSnapshot.hasChildren()) {
    return console.log('There are no notification tokens to send to.');
  }
  console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');

  tokens = Object.keys(tokensSnapshot.val());

  const payload = {
    notification: {
      body: notificationData.body,
      title: notificationData.title,
      click_action: 'FLUTTER_NOTIFICATION_CLICK'
    },
    data: {
      id: '1', 
      status: 'done'
    },
  };

  //loop through each element in the /DeviceTokens node and get data for each entry with the 
 getTheTokens function.
  for (var tokenDetails in tokens) {
    getTheTokens(tokens[tokenDetails]);
  }

 //getTheTokens function
 function getTheTokens() {
    var refKey = admin.database().ref('/DeviceTokens').child(tokens[tokenDetails]);
    refKey.once('value', (snapshot) => {
      var theToken = snapshot.child('/device_token').val();
      try {
        const response = admin.messaging().sendToDevice(theToken, payload);

       // gives proper feedback to console.
       console.log('Notification sent successfully');
      } catch (err) {
        console.log(err);
      }
    });
 }
});

I am using RealTime Database where a device token is saved against any device that connects to the system. I have a document for that called DeviceTokens. I have another document notifications where the notifications are store. When a entry in generated in the notification, the function is supposed to identify that, then loop through all the device tokens and send that notification to all the devices that are subscribed to the notification.

My firebase console logs prints Notification sent successfully for the number of device token present in DeviceTokens. However it shows an error after the function is executed.

 sendFollowerNotification
 Error: Error while making request: Client network socket disconnected before secure TLS connection was established. 
 Error code: ECONNRESET at FirebaseAppError.FirebaseError [as constructor (/workspace/node_modules/firebase-admin/lib/utils/error.js:42:28) 
 at FirebaseAppError.PrefixedFirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:88:28) 
 at new FirebaseAppError (/workspace/node_modules/firebase-admin/lib/utils/error.js:123:28)
 at /workspace/node_modules/firebase-admin/lib/utils/api-request.js:209:19 
 at process._tickCallback (internal/process/next_tick.js:68:7) 

and

sendFollowerNotification
Error: Process exited with code 16
at process.on.code (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:271:38)
at process.emit (events.js:198:13)
at process.EventEmitter.emit (domain.js:448:20)
at process.exit (internal/process/per_thread.js:168:15)
at Object.logAndSendError (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/logger.js:37:9)
at process.on.err (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:268:22)
at process.emit (events.js:198:13)
at process.EventEmitter.emit (domain.js:448:20)
at emitPromiseRejectionWarnings (internal/process/promises.js:140:18)
at process._tickCallback (internal/process/next_tick.js:69:34) 

How can I solve this?

2 Answers

Try Checking your rules maybe they have expired. If that's fine as well I think the issue might be the new update, now you have to initialize Firebase app before doing any operations. You have to add firebase core to pubsec file and then before any firebase operation just import firebase core and initialize by

await Firebase.initializeApp();

Maybe this will work.

Related