我有一个简单的聊天网络应用程序,两个人可以互相交谈。我希望他们收到新消息时能收到通知。到目前为止,我设法获得了用户的许可,并获得了令牌:
const messaging = firebase.messaging();
function InitializeFirebaseMessaging(){
messaging.requestPermission().then(function(){
console.log("Notification permission");
return messaging.getToken();
}).then(function(token){
console.log("Token: "+token);
}).catch(function (reason){
console.log(reason);
});
}
messaging.onMessage(function (payload){
console.log(payload);
});
messaging.onTokenRefresh(function () {
messaging.getToken()
.then(function (newtoken) {
console.log("New Token : "+ newtoken);
})
.catch(function (reason) {
console.log(reason);
})
});
在Firestore中我有一个"配对"集合,其中我将用户配对(因此只有成对才能相互发送消息),并且每个用户都有一个集合,其中包含他们发送和接收的消息。
当我登录到Firebase时,转到Engage/Cloud Messaging,我可以使用令牌从Firebase向该用户发送消息。我怎样才能为每条传入消息自动向另一个人发送通知?
如果希望自动发送消息,则需要为每次聊天的新消息设置云函数侦听器。当写新消息时,使用该云功能向接收消息的用户发送FCM消息。
下面是一个例子,我如何在我的一个应用程序中使用RTDB监听器:
import * as functions from 'firebase-functions'
import admin from 'firebase-admin'
export default functions
.region('europe-west1')
.database.ref('/user_chat_messages/{senderUid}/{receiverUid}/{messageUid}')
.onCreate(async (eventSnapshot, context) => {
const { timestamp, params } = context
const { senderUid, receiverUid, messageUid } = params
if (context.authType === 'ADMIN') {
return null
}
const snapValues = eventSnapshot.val()
const {
message = '',
link,
image,
location,
audio,
authorUid,
created,
authorPhotoUrl,
} = snapValues
let lastMessage = message
const senderRef = admin.database().ref(`/users/${senderUid}`).once('value')
const senderSnap = await admin
.database()
.ref(`/users/${senderUid}`)
.once('value')
const receiverSnap = await admin
.database()
.ref(`/users/${receiverUid}`)
.once('value')
const {
displayName: senderName = null,
photoURL: senderPhoto = null,
} = senderSnap.val()
const {
displayName: receiverName = null,
photoURL: receiverPhoto = null,
} = receiverSnap.val()
if (!message) {
if (link) {
lastMessage = 'Link'
}
if (image) {
lastMessage = 'Photo'
}
if (location) {
lastMessage = 'Position'
}
if (audio) {
lastMessage = 'Audio'
}
}
// receiver chat message
await admin
.database()
.ref(`/user_chat_messages/${receiverUid}/${senderUid}/${messageUid}`)
.update(snapValues)
// sender chat message
await admin
.database()
.ref(`/user_chat_messages/${senderUid}/${receiverUid}/${messageUid}`)
.update({
isSend: timestamp,
})
// sender chat
await admin
.database()
.ref(`/user_chats/${senderUid}/${receiverUid}`)
.update({
unread: 0,
displayName: receiverName,
photoURL: receiverPhoto,
lastMessage: lastMessage,
authorUid: senderUid,
lastCreated: created,
isSend: timestamp,
isRead: null,
})
// receiver chat
await admin
.database()
.ref(`/user_chats/${receiverUid}/${senderUid}`)
.update({
displayName: senderName,
photoURL: senderPhoto,
authorUid: senderUid,
lastMessage: lastMessage,
lastCreated: created,
isRead: null,
})
// update unread
await admin
.database()
.ref(`/user_chats/${receiverUid}/${senderUid}/unread`)
.transaction((number) => {
return (number || 0) + 1
})
if (authorUid !== receiverUid) {
const messages = []
const payload = {
notification: {
title: `${snapValues.authorName}`,
body: lastMessage,
},
webpush: {
notification: {
title: `${snapValues.authorName}`,
body: lastMessage,
icon: authorPhotoUrl ? authorPhotoUrl : '/apple-touch-icon.png',
image,
click_action: `https://www.react-most-wanted.com/chats/${senderUid}`,
},
},
data: {
test: 'test',
},
}
const tokensSnap = await admin
.database()
.ref(`notification_tokens/${receiverUid}`)
.once('value')
if (tokensSnap.exists()) {
tokensSnap.forEach((t) => {
messages.push({ token: t.key, ...payload })
})
}
await admin.messaging().sendAll(messages)
}
})