Я занимаюсь разработкой приложения для чата, поэтому мне нужно отправлять уведомления о получении новых сообщений. Для этого я использую Firebase Functions . Я использую функцию sendToDevice , для которой требуется токен для отправки уведомления. Проблема в том, что я не могу получить токен пользователя, который отправил сообщение. Это мой . js код:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref("/chats/{id}/messages/{messageId}/content")
.onWrite((change,context) => {
var content = change.after.val();
var payload = {
data:{
title: "Stranger has sent you a message",
text: content
}
};
// Here I need to the ID of the person who sent the message
// And then compare this Id with the two Ids of the to users that are in the conversation
// If the two Ids are different, then save the other Id as the token
// So that I can send a notification to the other user.
const senderId = database.ref("/chats/{id}/messages/{id}/sender/{senderId}");
admin.messaging().sendToDevice(senderId, payload)
.then(function(response){
console.log("Successfully sent message: ", response);
return null;
})
.catch(function(error){
console.log("Error sending message: ", error);
})
});
Как видите, я проверяю любые изменения в messages / content child. Это как содержание моего уведомления.
Затем я пытаюсь получить идентификатор отправителя сообщения , чтобы я мог знать, кто отправил сообщение, и получить другой идентификатор пользователя для уведомления. ему .
Это может немного сбивать с толку, так что вот моя База данных Firebase в реальном времени :
![enter image description here](https://i.stack.imgur.com/NETbm.jpg)
Что я делаю не так, чтобы этот кусок кода работал как надо? Это действие, которое я выполняю в android для получения сообщения:
class MyFirebaseInstanceId : FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
if(p0.data.size > 0){
val payload :Map<String, String> = p0.data
sendNotification(payload)
}
}
private fun sendNotification(payload: Map<String, String>) {
val builder = NotificationCompat.Builder(this)
builder.setSmallIcon(R.drawable.common_google_signin_btn_icon_disabled)
builder.setContentTitle(payload.get("username"))
builder.setContentText(payload.get("email"))
val intent = Intent(this, MainActivity::class.java)
val stackBuilder = TaskStackBuilder.create(this)
stackBuilder.addNextIntent(intent)
val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(resultPendingIntent)
val notificationManager = (getSystemService(Context.NOTIFICATION_SERVICE)) as NotificationManager
notificationManager.notify(0, builder.build())
}
}