Bear with me. I've spent a month just PHRASING this question: I've been using Firebase Database and Firebase functions for about a year. I've gotten it to work... but only if I sent the text of the message as a STRING. The problem is that now I wish to receive an OBJECT instead but I'm unsure of how to do this in FireBaseMessage.
My previous structure:
messages
T9Vh5cvUcbqC8IEZowBpJC3
ZWfn7876876ZGJeSNBbCpPmkm1
message
"messages": {
".read": true,
"$receiverUid": {
"$senderUid": {
"$message": {
".read": true,
".write": "auth.uid === $senderUid"
And my function for the listener was this:
exports.sendMessage = functions.database.ref('/messages/{receiverUid}/{senderUid}/{message}')
This is problematic... for a variety of reasons. Namely if the old message was "Hey" and then that same person just writes "Hey" again... then the original gets overwritten.
So my NEW structure is more like this:
messages
-LkVcYqJoEroWpkXZnqr
body: "genius grant"
createdat: 1563915599253
name: "hatemustdie"
receiverUid: "TW8289372984KJjkhdsjkhad"
senderUid: "yBNbs9823789KJkjahsdjkas"
Which is written as:
mDatabase.child("messages").push().setValue(message);
...and I'm just unsure about how to write out that function.
I mean... IDEALLY... it would be something like:
exports.sendMessage = functions.database.ref('/messages/{receiverUid}/{senderUid}/{msgID}/{msgOBJECT}')
...but I'm just not sure how Firebase functions is reading this new structure.
Now I'm pushing to the database like so:
mDatabase.child("messages").child(guid).child(user_Id).push().setValue(msgObject).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(#NonNull Void T) {
Log.d("MessageActivity", "Message Sent");
Basically I would just like to receive the message object... with everything in it... when it arrives from the notification... and be able to easily parse the body, date, userids, etc.
Can someone explain the correct way to go about this?
UPATE By request here's the complete cloud function:
exports.sendMessage = functions.database.ref('/messages/{receiverUid}/{senderUid}/{msgId}/{message}')
.onWrite(async (change, context) => {
const message = context.params.message;
// const messageId = context.params.messageId;
const receiverUid = context.params.receiverUid;
const senderUid = context.params.senderUid;
// If un-follow we exit the function.
if (!change.after.val()) {
return console.log('Sender ', senderUid, 'receiver ', receiverUid, 'message ', message);
}
console.log('We have a new message: ', message, 'for: ', receiverUid);
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database()
.ref(`/users/${receiverUid}/notificationTokens`).once('value');
// Get the follower profile.
const getSenderProfilePromise = admin.auth().getUser(senderUid);
// The snapshot to the user's tokens.
let tokensSnapshot;
// The array containing all the user's tokens.
let tokens;
const results = await Promise.all([getDeviceTokensPromise, getSenderProfilePromise]);
tokensSnapshot = results[0];
const sender = results[1];
// Check if there are any device tokens.
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.');
console.log('Fetched sender profile', sender);
// console.log('David you're looking for the following UID:', followerUid);
// Notification details.
const payload = {
notification: {
title: `${sender.displayName} sent you a message.`,
body: message,
tag: senderUid
},
// 'data': { 'fuid': followerUid }
data: {
type: 'message',
name: sender.displayName
}
};
console.log('David you are looking for the following message:', message);
// Listing all tokens as an array.
tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
Since you now store the sender and receiver's UIDs inside the message, the declaration of your Cloud Function will need to change.
Instead of this:
exports.sendMessage = functions.database.ref('/messages/{receiverUid}/{senderUid}/{msgId}/{message}').onWrite(async (change, context) => {
You'll need to trigger on:
exports.sendMessage = functions.database.ref('/messages/{messageId}').onWrite(async (change, context) => {
So with this change your code will trigger on each message that is written /messages.
Now you "just" need to get the sender and receiver's UID. And since you no longer can get them from the context, you will instead get them from the change. Specifically change.after contains the data snapshot as it exists in the database after the write has completed. So (as long as you're not deleting the data), you can get the UIDs with:
const receiverUid = change.after.val().receiverUid;
const senderUid = change.after.val().senderUid;
And you'll also get the actual message from there of course:
const message = change.after.val().message;
And just in case you need the message ID (the -L... key that it was written under in the database):
const messageId = change.after.val().messageId;
You need a trigger on just the messageId:
exports.sendMessage = functions.database.ref('/messages/{messageId}').onWrite((change, context) => {
const changedData = change.after.val(); // This will have the complete changed data
const message = change.after.val().message; // This will contain the message value
......
});
Elaborating on Frank's answer:
You can't get the data from context like const message = context.params.message;because those parameters don't exists anymore on the context.
Related
I'm creating a chat application and i want to use fcm to send notification if the person has a new message, but i don't know how to proceed. All the tutorials i found use to send the message from firebase. But i want to send it automatically when there is a new message for the person
A possible workaround if you use firebase should be like this:
You need to store each firebase FCM token for a specific user (need to take in account here that a user can log in at the same time on his account from multiple devices) so you can store the userId and his deviceUniqueId on flutter you can get it from device_info https://pub.dev/packages/device_info:
String identifier;
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
try {
if (Platform.isAndroid) {
var build = await deviceInfoPlugin.androidInfo;
identifier = build.id.toString();
} else if (Platform.isIOS) {
var data = await deviceInfoPlugin.iosInfo;
identifier = data.identifierForVendor;//UUID for iOS
}
} on PlatformException {
print('Failed to get platform version');
}
and after that to get the unique CFM token that Firebase provide for each device, you can get it using Firebase firebase_messaging plugin (https://pub.dev/packages/firebase_messaging) getToken() and insert the token to firestore (or an other database you want to store it)
FirebaseMessaging firebaseMessaging = new FirebaseMessaging();
firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(sound: true, badge: true, alert: true));
firebaseMessaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
firebaseMessaging.getToken().then((token){
print('--- Firebase toke here ---');
Firestore.instance.collection(constant.userID).document(identifier).setData({ 'token': token});
print(token);
});
After that you can insert one or more FCM token connected to multiple device for one user. 1 user ... n devices , 1 device ... 1 unique token to get push notifications from Firebase.
send it automatically when there is a new message for the person : now you need to call the Firestore API(is very fast indeed but need to be careful about the plan limit that you are using here) or another API call if you store the token to another db, in order to get the token/tokens for each user and send the push notifications.
To send the push notification from flutter you can use a Future async function.
P.s: I'm passing as argument a List here in order to use "registration_ids" instead of "to" and send the push notification to multiple tokens if the user has been logged in on multiple devices.
Future<bool> callOnFcmApiSendPushNotifications(List <String> userToken) async {
final postUrl = 'https://fcm.googleapis.com/fcm/send';
final data = {
"registration_ids" : userToken,
"collapse_key" : "type_a",
"notification" : {
"title": 'NewTextTitle',
"body" : 'NewTextBody',
}
};
final headers = {
'content-type': 'application/json',
'Authorization': constant.firebaseTokenAPIFCM // 'key=YOUR_SERVER_KEY'
};
final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);
if (response.statusCode == 200) {
// on success do sth
print('test ok push CFM');
return true;
} else {
print(' CFM error');
// on failure do sth
return false;
}
}
You can also check the post call from postman in order to make some tests. POST request
On Headers add the:
key Authorization with value key=AAAAO........ // Project Overview -> Cloud Messaging -> Server Key
key Content-Type with value application/json
And on the body add
{
"registration_ids" :[ "userUniqueToken1", "userUniqueToken2",... ],
"collapse_key" : "type_a",
"notification" : {
"body" : "Test post",
"title": "Push notifications E"
}
}
"registration_ids" to send it to multiple tokens (same user logged in to more than on device at the same time)
"to" in order to send it to a single token (one device per user / or update always the user token that is connected with his device and have 1 token ... 1 user)
I'm making an edit to the response, in order to add that is very important to add the FCM Server Key on a trusted environment or server!
I'll list here a few related questions which I have participated with answers. I guess you'll find a lot of relevant info on using firebase cloud messaging (FCM) in a chat app.
Is FCM the only way to build a chat app ?
Suggested approach to use FCM in a chat app
Is using topics a better solution then using the fcmToken in a chat app?
Problems with FCM onMessage while app is in background
Problem: after logoff, user continues to receive notifications
Good luck!
//Notification Sending Side Using Dio flutter Library to make http post request
static Future<void> sendNotification(receiver,msg)async{
var token = await getToken(receiver);
print('token : $token');
final data = {
"notification": {"body": "Accept Ride Request", "title": "This is Ride Request"},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done"
},
"to": "$token"
};
final headers = {
'content-type': 'application/json',
'Authorization': 'key=AAAAY2mZqb4:APA91bH38d3b4mgc4YpVJ0eBgDez1jxEzCNTq1Re6sJQNZ2OJvyvlZJYx7ZASIrAj1DnSfVJL-29qsyPX6u8MyakmzlY-MRZeXOodkIdYoWgwvPVhNhJmfrTC6ZC2wG7lcmgXElA6E09'
};
BaseOptions options = new BaseOptions(
connectTimeout: 5000,
receiveTimeout: 3000,
headers: headers,
);
try {
final response = await Dio(options).post(postUrl,
data: data);
if (response.statusCode == 200) {
Fluttertoast.showToast(msg: 'Request Sent To Driver');
} else {
print('notification sending failed');
// on failure do sth
}
}
catch(e){
print('exception $e');
}
}
static Future<String> getToken(userId)async{
final Firestore _db = Firestore.instance;
var token;
await _db.collection('users')
.document(userId)
.collection('tokens').getDocuments().then((snapshot){
snapshot.documents.forEach((doc){
token = doc.documentID;
});
});
return token;
}
//Now Receiving End
class _LoginPageState extends State<LoginPage>
with SingleTickerProviderStateMixin {
final Firestore _db = Firestore.instance;
final FirebaseMessaging _fcm = FirebaseMessaging();
StreamSubscription iosSubscription;
//this code will go inside intiState function
if (Platform.isIOS) {
iosSubscription = _fcm.onIosSettingsRegistered.listen((data) {
// save the token OR subscribe to a topic here
});
_fcm.requestNotificationPermissions(IosNotificationSettings());
}
_fcm.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
showDialog(
context: context,
builder: (context) => AlertDialog(
content: ListTile(
title: Text(message['notification']['title']),
subtitle: Text(message['notification']['body']),
),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
// TODO optional
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
// TODO optional
},
);
//saving token while signing in or signing up
_saveDeviceToken(uid) async {
// FirebaseUser user = await _auth.currentUser();
// Get the token for this device
String fcmToken = await _fcm.getToken();
// Save it to Firestore
if (fcmToken != null) {
var tokens = _db
.collection('users')
.document(uid)
.collection('tokens')
.document(fcmToken);
await tokens.setData({
'token': fcmToken,
'createdAt': FieldValue.serverTimestamp(), // optional
'platform': Platform.operatingSystem // optional
});
}
}
In my android app when user enters wrong PASSWORD more times then i want send email to user using firebase functions with download link of picture captured so i created function below.
So i push email and download link to firebase and when data gets added following function gets triggered but whenever im trying to deploy this function cli giving me error that mailtransport is unexpected..
exports.sendMails = functions.database.ref('/failedAttemps/{email2}/{attemptsid}')
.onWrite((data, context) =>
{
const email2 = context.params.email2;
const attemptsid = context.params.attemptsid;
//const sender_id = context.params.sender_id;
//const mees = context.params.message_not;
// contentss = mees;
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: "******#gmail.com",
pass: "****#****",
},
});
const email = admin.database().ref(`/Notification/${email2}/${attemptsid}/email`);
email.once("value", function(snapshot){
emails = snapshot.val();
});
const naam = admin.database().ref(`/Notification/${email2}/${attemptsid}/dlink`);
naam.once("value", function(snapshot){
dlinks = snapshot.val();
});
// console.log('message :' , contentss);
const mailOptions = {
from: '"LetsTalk" <noreply#firebase.com>',
to: emails,
};
// Building Email message.
mailOptions.subject = 'Someone tried to login to you account';
mailOptions.text = `${dlink}Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.`;
try {
await mailTransport.sendMail(mailOptions);
// console.log(`New ${subscribed ? '' : 'un'}subscription confirmation email sent to:`, val.email);
} catch(error) {
console.error('There was an error while sending the email:', error);
}
return null;
});
Every time i try to deploy function on firebase.This error pops upenter image description here
The problem seems to be you are using await without first indicating it is an async function.
Try replacing your first lines with:
exports.sendMails = functions.database.ref('/failedAttemps/{email2}/{attemptsid}')
.onWrite(async (data, context) =>
{
I'm working with Firebase notifications using node.js.
After compile, when I'm sending request to other user of app (request makes notification), firebase log shows error:
TypeError: Cannot read property 'receiver_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:12:36)
at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Index.js code:
'use strict'
const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite(event =>
{
const receiver_id = event.params.receiver_id;
const notification_id = event.params.notification_id;
console.log('We have a notification to send to :', receiver_id);
if(!event.data.val())
{
return console.log('A notification has been deleted from the database: ', notification_id);
}
const deviceToken = admin.database().ref(`/Users/${receiver_id}/device_token`).once('value');
return deviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "Friend Request",
body: "you have received a new friend request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.log('This was the notification feature.');
});
});
});
I have read about new APIs on site:
https://firebase.google.com/docs/functions/beta-v1-diff
I think I must change event to context, but I don't know how.
Is anybody know what's the issue?
Thank's for any Help :)
The Firebase documentation on the new data and context shows where the params now live:
The context parameter provides information about the function's execution. Identical across asynchronous functions types, context contains the fields eventId, timestamp, eventType, resource, and params.
So to get rid of that error, you'll need to change the first bit of your function to:
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_id = context.params.receiver_id;
const notification_id = context.params.notification_id;
...
There are more, similar changes that you'll need to make. If you're having a hard time making those yourself, I recommend you check back in with where you got the code from.
I'm deploying a mobile application (for Android and iOS) through which the admin can send alert to users registered to a specific topic. To do that I'm using Realtime Database to store alerts and cloud functions to send notifications to topic.
I've the following cloud function deployed:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNewAlertNotification = functions.database.ref('/alerts').onWrite(event => {
const getValuePromise = admin.database()
.ref('alerts')
.orderByKey()
.limitToLast(1)
.once('value');
return getValuePromise.then(snapshot => {
const { text, topics, author } = snapshotToArray(snapshot)[0];
const payload = {
data: {
title: 'Avviso',
body: text,
icon: 'ic_stat_notify',
sound: 'default',
color: '#F3E03B',
tag: 'alerts',
ticker: 'Nuovo avviso',
subtitle: 'Avvisi',
author: JSON.stringify(author)
}
};
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24 * 2, // 48 hours
collapseKey: 'it.bmsoftware.caliup'
// contentAvailable: true
};
if (topics.length > 1) {
let condition = '';
topics.forEach((topic, index) => {
condition += `'${topic}' in topics`
if (index < topics.length - 1) {
condition += ' || '
}
});
console.log(`Sending alert to condition '${condition}' -> ${JSON.stringify(payload)}`);
return admin.messaging().sendToCondition(condition, payload, options);
} else if (topics.length === 1) {
let topic = topics[0];
console.log(`Sending alert to topic '${topic}' -> ${JSON.stringify(payload)}`);
return admin.messaging().sendToTopic(topic, payload, options);
} else {
console.log(`No topics found`);
}
});
});
const snapshotToArray = (snapshot) => {
let result = []
if (!snapshot || !snapshot.val())
return result
snapshot.forEach((childSnapshot) => {
let item = childSnapshot.val()
item.key = childSnapshot.key
result.push(item)
})
return result
}
When I insert a new message on the realtime database, the above function fetch that message correctly and in the log section (on the firebase console) I see the correct custom log and a log that says status 'ok'.
Despite this, no notification arrives on devices. If I test the same topic from firebase console directly it works fine so devices are properly registered.
Is there something wrong with the cloud function that I'm missing?
I believe that you should uncomment // contentAvailable: true if you are sending only data payload, at least for iOS. That way you'll be able to show and trigger the notification yourself on the app code. If you want the notification to pop up without having to process the data payload, you should pass a notification object on payload.
Notification is limited to these fields tho: https://firebase.google.com/docs/reference/admin/node/admin.messaging.NotificationMessagePayload
I am trying to make a cloud function that sends a push notification to a given user.
The user makes some changes and the data is added/updated under a node in firebase database (The node represents an user id). Here i want to trigger a function that sends a push notification to the user.
I have the following structure for the users in DB.
Users
- UID
- - email
- - token
- UID
- - email
- - token
Until now i have this function:
exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{
const uuid = event.params.uid;
console.log('User to send notification', uuid);
var ref = admin.database().ref('Users/{uuid}');
ref.on("value", function(snapshot){
console.log("Val = " + snapshot.val());
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
When i get the callback, the snapshot.val() returns null. Any idea how to solve this? And maybe how to send the push notification afterwards?
I managed to make this work. Here is the code that sends a notification using Cloud Functions that worked for me.
exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{
const uuid = event.params.uid;
console.log('User to send notification', uuid);
var ref = admin.database().ref(`Users/${uuid}/token`);
return ref.once("value", function(snapshot){
const payload = {
notification: {
title: 'You have been invited to a trip.',
body: 'Tap here to check it out!'
}
};
admin.messaging().sendToDevice(snapshot.val(), payload)
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
})
Just answering the question from Jerin A Mathews...
Send message using Topics:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//Now we're going to create a function that listens to when a 'Notifications' node changes and send a notificcation
//to all devices subscribed to a topic
exports.sendNotification = functions.database.ref("Notifications/{uid}")
.onWrite(event => {
//This will be the notification model that we push to firebase
var request = event.data.val();
var payload = {
data:{
username: request.username,
imageUrl: request.imageUrl,
email: request.email,
uid: request.uid,
text: request.text
}
};
//The topic variable can be anything from a username, to a uid
//I find this approach much better than using the refresh token
//as you can subscribe to someone's phone number, username, or some other unique identifier
//to communicate between
//Now let's move onto the code, but before that, let's push this to firebase
admin.messaging().sendToTopic(request.topic, payload)
.then((response) => {
console.log("Successfully sent message: ", response);
return true;
})
.catch((error) => {
console.log("Error sending message: ", error);
return false;
})
})
//And this is it for building notifications to multiple devices from or to one.
Return this function call.
return ref.on("value", function(snapshot){
console.log("Val = " + snapshot.val());
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
This will keep the cloud function alive until the request is complete. Learn more about returning promises form the link give by Doug in the comment.
Send Notification for a Topic In Cloud function
Topics a basically groups you can send notification for the selected group
var topic = 'NOTIFICATION_TOPIC';
const payload = {
notification: {
title: 'Send through Topic',
body: 'Tap here to check it out!'
}
};
admin.messaging().sendToTopic(topic,payload);
You can register the device for any new or existing topic from mobile side
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotificationToTopic =
functions.firestore.document('Users/{uuid}').onWrite(async (event) => {
//let title = event.after.get('item_name');
//let content = event.after.get('cust_name');
var message = {
notification: {
title: "TGC - New Order Recieved",
body: "A New Order Recieved on TGC App",
},
topic: 'orders_comming',
};
let response = await admin.messaging().send(message);
console.log(response);
});
For sending notifications to a topic, The above code works well for me, if you have any doubt, let me know.