I followed this tutorial to send notifications between android devices. I used Google Cloud App Engine for the first time to run the Node process, and it works. I get notifications, but I get two notifications for each request instead of one for each. Can someone help me finding out why?
Some observations...
On the App Engine dashboard, I noticed that there are two instances. I tried deleting one, but it won't get deleted.
I confirmed that the problem is not in the firebase database. When creating notificationRequest, only one node is created as expected. But two notifications are sent out to the device, probably by the node script.
Here is my Node script. I deployed this script by executing
gcloud app deploy
on terminal.
// [START app] 'use strict'; const express = require('express'); const app = express(); var firebase = require('firebase-admin'); var request = require('request'); // Your Firebase Cloud Messaging Server API key var API_KEY = [my_api_key]; // Fetch the service account key JSON file contents var serviceAccount = require(__dirname+"/serviceAccountKey.json"); // Initialize the app with a service account, granting admin privileges firebase.initializeApp({ credential: firebase.credential.cert(serviceAccount), databaseURL: [my_databaseURL] }); var ref = firebase.database().ref(); function listenForNotificationRequests() { var requests = ref.child('notificationRequests'); requests.on('child_added', function(requestSnapshot) { var request = requestSnapshot.val(); sendNotificationToUser( request.to_uid, request.from_username, request.message, function() { console.log("Successfully sent"); requestSnapshot.ref.remove(); } ); }, function(error) { console.error(error); }); }; function sendNotificationToUser(to_uid, from_username, message, onSuccess) { console.log("sending message `"+message+"`..."); request({ url: 'https://fcm.googleapis.com/fcm/send', method: 'POST', headers: { 'Content-Type' :' application/json', 'Authorization': 'key='+API_KEY }, body: JSON.stringify({ notification: { title: from_username, body: message }, to : '/topics/user_'+to_uid }) }, function(error, response, body) { if (error) { console.error(error); } else if (response.statusCode >= 400) { console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage); } else { onSuccess(); } }); } // start listening listenForNotificationRequests(); // Start the server const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); console.log('Press Ctrl+C to quit.'); }); // [END app]
Thank you!