Firebase client doesnt recieve message - javascript

I have the following Node.js script:
var registrationToken = "Long Token";
var serviceAccount = require("./config/ServiceAccount.json");
var payload = {
data: {
score: "850",
time: "2:45"
}
};
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: fireBaseConfig.databaseURL
});
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
When running this I do get a success response:
Successfully sent message: { results: [ { messageId: '0:1502813815410638%e609af1cf9fd7ecd' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 5249778920849394000 }
Then i have my client:
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
console.log('I am in here');
return messaging.getToken()
.then(function (currentToken) {
console.log(currentToken);
})
.catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}).catch(function (err) {
console.log('Error');
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
Now first I (as my client) go to the website then I get the token in the console I then use that token in my backend (Node.js) and send a message (while the tap where the client is, is still open) However nothing happens.
Can anyone tell me what I've done wrong?

Related

Authentication Error when trying to retrieve Youtube Chanel Information

I am trying authenticate the user and then retrieve youtube channel list.
Below is the function to authenticate:
function authenticate() {
showNewLoader('show');
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function(response) {
console.log( response);
youtubeAuthResponse['token_details'] = response.tc;
youtubeAuthResponse['google_email'] = '';
youtubeAuthResponse['google_id'] = '';
showNewLoader('hide');
},
function(err) { console.error("Error signing in", err); showNewLoader('hide');});
}
Loading client:
function loadClient() {
showNewLoader('show');
gapi.client.setApiKey("XXXXXX");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { execute();},
function(err) { console.error("Error loading GAPI client for API", err);showNewLoader('hide');});
}
/*Make sure the client is loaded and sign-in is complete before calling this method.*/
function execute() {
return gapi.client.youtube.channels.list({
"part": [
"snippet",
"statistics"
],
"mine": true
})
.then(function(response) {
/*Handle the results here (response.result has the parsed body).*/
youtubeChannelResponse = response.result;
storeYoutubeData();
},
function(err) { console.error("Execute error", err); showNewLoader('hide') }).then(function(){
});
}
User logs in successfully but I am unable to get the channel info:
Any assistance on this issue is greatly appreciated. #DalmTo

Unable to broadcast multiple messages on socket io

I'm writing a program where I want to broadcast messages using socket IO. This is for a chat interface.
Here is my code
socket.on('send-chatMessage', message => {
var gotNewMsg = false;
sendChatMessage(message, chatMessagesJSON, function (resp, err) {
console.log('resp from send chat --->');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
gotNewMsg = true;
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
})
});
Here My first
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
is working fine but my second one
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
is not working as expected. I'm able to enter the if and also print the result. The only thing failing is broadcasting.
Here is my broadcast handlers.
socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`);
})
function appendMessage(message) {
const messageElement = document.createElement('div');
messageElement.innerText = message;
messageContainer.append(messageElement);
};
please let me know where am I going wrong.

Inconsistent results from Firestore Cloud Functions

I have a Cloud Function setup on Firebase that involved checking different parts of the Firestore Database and then sending a message via Cloud Messaging
Below is the JavaScript for the function in question:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().Firebase);
var db = admin.firestore();
exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
// get the user we want to send the message to
const newValue = snap.data();
const teamidno = context.params.teamId;
const useridno = newValue.userID;
//start retrieving Waitlist user's messaging token to send them a message
var tokenRef = db.collection('Users').doc(useridno);
tokenRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
const data = doc.data();
//get the messaging token
var token = data.messaging_token;
console.log("token: ", token);
//reference for the members collection
var memberRef = db.collection('Teams/'+teamidno+' /Members').doc(useridno);
memberRef.get()
.then(doc => {
if (!doc.exists){
console.log('user was not added to team. Informing them');
const negPayload = {
data: {
data_type:"team_rejection",
title:"Request denied",
message: "Your request to join the team has been denied",
}
};
return admin.messaging().sendToDevice(token, negPayload)
.then(function(response){
console.log("Successfully sent rejection message:", response);
return 0;
})
.catch(function(error){
console.log("Error sending rejection message: ", error);
});
} else {
console.log('user was added to the team. Informing them')
const payload = {
data: {
data_type: "team_accept",
title: "Request approved",
message: "You have been added to the team",
}
};
return admin.messaging().sendToDevice(token, payload)
.then(function(response){
console.log("Successfully sent accept message:", response);
return 0;
})
.catch(function(error){
console.log("Error sending accept message: ", error);
});
}
})
.catch(err => {
console.log('Error getting member', err);
});
}
return 0;
})
.catch(err => {
console.log('Error getting token', err);
});
return 0;
});
The issues I have with this are:
The code runs and only sometimes actually checks for the token or sends a message.
the logs show this error when the function runs: "Function returned undefined, expected Promise or value " but as per another Stack Oveflow posts, I have added return 0; everywhere a .then ends.
I am VERY new to node.js, javascript and Cloud Functions so I am unsure what is going wrong or if this is an issue on Firebase's end. Any help you can give will be greatly appreciated
As Doug said, you have to return a promise at each "step" and chain the steps:
the following code should work:
exports.newMemberNotification = functions.firestore
.document('Teams/{teamId}/Waitlist/{userId}').onDelete((snap, context) => {
// get the user we want to send the message to
const newValue = snap.data();
const teamidno = context.params.teamId;
const useridno = newValue.userID;
//start retrieving Waitlist user's messaging token to send them a message
var tokenRef = db.collection('Users').doc(useridno);
tokenRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
throw 'No such document!';
} else {
const data = doc.data();
//get the messaging token
var token = data.messaging_token;
console.log("token: ", token);
//reference for the members collection
var memberRef = db.collection('Teams/' + teamidno + '/Members').doc(useridno);
return memberRef.get()
}
})
.then(doc => {
let payload;
if (!doc.exists) {
console.log('user was not added to team. Informing them');
payload = {
data: {
data_type: "team_rejection",
title: "Request denied",
message: "Your request to join the team has been denied",
}
};
} else {
console.log('user was added to the team. Informing them')
payload = {
data: {
data_type: "team_accept",
title: "Request approved",
message: "You have been added to the team",
}
};
}
return admin.messaging().sendToDevice(token, payload);
})
.catch(err => {
console.log(err);
});
});

Chrome not receiving fcm messages, but firefox does

I am using FCM to facilitate push messages in a custom service worker. I followed the FCM getting started but am running into issues where the javascript client isn't receiving the sent messages on chrome, but firefox is working as intended.
The messages are being sent from a hosted server, and the messages are sent with no failures and message id's associated with each registered client.
Below is the page script and below that will be relevant service worker code.
page html
<script>
// Initialize Firebase
var config = {
<CONFIG SETTINGS>
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
</script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
messaging.useServiceWorker(registration);
resetUI();
}).catch(function (err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
const permissionDivId = 'permission_div';
messaging.onTokenRefresh(function () {
messaging.getToken()
.then(function (refreshedToken) {
console.log('Token refreshed.');
setTokenSentToServer(false);
sendTokenToServer(refreshedToken);
resetUI();
})
.catch(function (err) {
console.log('Unable to retrieve refreshed token ', err);
});
});
messaging.onMessage(function (payload) {
console.log("Message received. ", payload);
appendMessage(payload);
});
function resetUI() {
clearMessages();
messaging.getToken()
.then(function (currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
console.log('No Instance ID token available. Request permission to generate one.');
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
})
.catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
}
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...');
<TOKEN SENT TO SERVER AND STORED>
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again ' +
'unless it changes');
}
}
function isTokenSentToServer() {
if (window.localStorage.getItem('sentToServer') == 1) {
return true;
}
return false;
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
function showHideDiv(divId, show) {
const div = document.querySelector('#' + divId);
if (show) {
div.style = "display: visible";
} else {
div.style = "display: none";
}
}
function requestPermission() {
console.log('Requesting permission...');
messaging.requestPermission()
.then(function () {
console.log('Notification permission granted.');
resetUI();
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
});
}
function deleteToken() {
messaging.getToken()
.then(function (currentToken) {
messaging.deleteToken(currentToken)
.then(function () {
console.log('Token deleted.');
setTokenSentToServer(false);
resetUI();
})
.catch(function (err) {
console.log('Unable to delete token. ', err);
});
})
.catch(function (err) {
console.log('Error retrieving Instance ID token. ', err);
});
}
// Add a message to the messages element.
function appendMessage(payload) {
const messagesElement = document.querySelector('#messages');
const dataHeaderELement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style = 'overflow-x:hidden;'
dataHeaderELement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderELement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages');
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild);
}
}
function updateUIForPushEnabled(currentToken) {
showHideDiv(permissionDivId, false);
}
function updateUIForPushPermissionRequired() {
showHideDiv(permissionDivId, true);
}
</script>
sw.js
self.addEventListener('push', function (event) {
console.log('Service Worker recived a push message', event.data.text());
var notification = event.data.json().notification;
var title = notification.title;
event.waitUntil(
self.registration.showNotification(title, {
body: notification.body,
icon: notification.icon,
data: { url: notification.click_action }
}));
});
Thank you for any help you can give!

Why am I not receiving firebase messages?

I see my server is sending correctly the messages to firebase API since it returns a success: 1 response but my client is not receiving the messages, what is happening, my code is:
const messaging = firebase.messaging()
const that = this
messaging.requestPermission()
.then(function() {
return messaging.getToken()
})
.then(function(token) {
that.updateServerFirebaseToken(token)
})
.catch(function(err) {
console.log(err)
})
// Call to user
messaging.onMessage(function(payload) {
console.log('firebase', payload)
if(payload.data.status == 'calling') {
this.audio.play()
this.$store.commit(types.CALLING, JSON.decode(payload.data.order))
}
})
and my service worker firebase-messaging-sw.js
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function(payload) {
console.log('FIREBASE call', payload);
if(payload.data.status == 'calling') {
channel.postMessage(payload.data)
return self.registration.showNotification('Nuevo pedido', {body: "Llamada para transporte de un pedido"})
}
})

Categories

Resources