Send massage to group devices in Firebase Cloud Messaging - firebase

I am building a chat and I want to send message in FCM to 1000 clients in a group. The message would sent from client to group of 1000 clients (the message not pass through server). I can use the topic method, but if I want to remove a client by the group admin it's not possible. Anyone can propose a solution?
Help me please.

Topics are indeed public: you (as the developer/administrator of the app) cannot prevent your app's users from subscribing to a topic.
If you want to control the devices that do (and don't) receive your messages, you'll have to send the message to those specific devices. You do this by tracking the instance ID tokens for those devices in a database and then targeting the list of tokens when you send the downstream message.
There is an example of how to manage device tokens and send messages in the Cloud Messaging for Firebase documentation.

If you simply want to remove (unsubscribe) some specific members, you can make use of the InstanceID API, specifically batchRemove.
Manage relationship maps for multiple app instances
Using the Instance ID service's batch methods, you can perform batch management of app instances. For example, you can perform bulk addition or removal of app instances to an FCM or GCM topic. To manage app instances, call the Instance ID service at this endpoint, providing the app instance tokens in the JSON body:
https://iid.googleapis.com/iid/v1:batchAdd
https://iid.googleapis.com/iid/v1:batchRemove
Parameters
Authorization: key=YOUR_API_KEY. Set this parameter in the header.
to : The topic name.
registration_tokens : The array of IID tokens for the app instances you want to add or remove.
Results
On success the call returns HTTP status 200. Empty results indicate successful subscription for the token. For failed subscriptions, the result contains one of these error codes:
NOT_FOUND — The registration token has been deleted or the app has been uninstalled.
INVALID_ARGUMENT — The registration token provided is not valid for the Sender ID.
INTERNAL — The backend server failed for unknown reasons. Retry the request.
TOO_MANY_TOPICS — Excessive number of topics per app instance.
Example POST request
https://iid.googleapis.com/iid/v1:batchAdd
Content-Type:application/json
Authorization:key=API_KEY
{
"to": "/topics/movies",
"registration_tokens": ["nKctODamlM4:CKrh_PC8kIb7O...", "1uoasi24:9jsjwuw...", "798aywu:cba420..."],
}
Example result
HTTP 200 OK
{
"results":[
{},
{"error":"NOT_FOUND"},
{},
]
}

Related

SignalR push notification when users are not online

I need to implement push notifications for my asp.net core project.For a news service
it needs to work in such a manner that if the user is not online while a message is being sent out, then the message will arrive at the client when they are online thenext time.
All the articles I can find about this, are all slightly vague about this case, and just emphasises the "real-time" communication.
So would it be possible to have push notifications that could that wiht signalr?
it needs to work in such a manner that if the user is not online while a message is being sent out, then the message will arrive at the client when they are online thenext time.
To achieve your above requirement, you can try:
mapping user to the connection id(s) and persist that mapping, which would help find/get new connection id(s) based on user name or email etc readable info after user connect/reconnect to hub, then you can send unread message/data to specific user by specifying connection id(s).
Note: you can also send a message to a specific user by passing the user identifier to the User function in a hub method, please refer to this doc: https://learn.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-5.0#users-in-signalr
for unread messages, as #SamiKuhmonen mentioned, you can store/persist those messages in somewhere, and if you want to persist information after restarts or you would host hub on multi-servers/instances, in-memory store is not a good approach. You can try to store messages in database etc permanent, external storage.
define and use a flag to indicates if the message has been seen by user. After client received a message, then invoke a hub method to update that flag or delete that message from the store.

Retrieve FCM canonical_id in v1 API

I'm migrating to the FCM v1 API (https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages) from the legacy API (https://firebase.google.com/docs/cloud-messaging/http-server-ref) to send push notifications.
I want to know if is there some way to retrieve the canonical_id related to the token (registration_id) just like in the legacy API.
I have found nothing about it in the docs, only that the result is a Message object, and if an error occurs it returns a FcmError Object.
If I can't retrieve the canonical_id I think I would end up receiving errors of invalid / not registered token after some time (or am I wrong?), and would have to invalidate them in my database, if the user doesn't use the app during a reasonable amount of time.
AFAICT, canonical_ids haven't been used since the legacy api. See my answer here.
Registration tokens don't get invalidated on a regular basis, just on a few scenarios, where onTokenRefresh() is actually called and thus must be handled on the client side (resend the new token towards your server).

Send Firebase Cloud Messaging notification to users by user property

I'm trying to send out an FCM message to a specific set of users (or really, a single user) based on a specific user property but looking through the FCM HTTP API I can't seem to find a way to do that. I can send to users via topics, registration tokens, and device group notification keys, but I don't have any of that infrastructure set up in the near term. I know this functionality exists as you can send such a message via the UI, but I'm not seeing how to do it in the API documentation as yet.
There is currently no parameter that you could use to specify a user property (or even for user segments) that will serve as a target for the FCM API to send the message to.
As you've already searched, the only targets possible are single/multiple registration tokens (to and registration_ids), topics, conditions, and device groups (notification_key).
The option you're looking for is currently only available when using the Notifications Console.

Firebase Cloud Messaging - Managing Registration Tokens

I'm looking at implementing messaging between mobile and browser apps using Firebase cloud messaging and i have a few questions, that the docs don't seem to answer.
For being able to receive messages, you need a Registration Token (RT).
Messages can be send to a RT, to a topic or to a device group notification_key.The RT can also be used:
directly
to subscribe to a topic
to add to a device group
The RT can also expire/change.
In my app, I'm maintaining a list of RT per user. Now, when the RT changes:
Do I have to unsubscribe the old token and subscribe the new token to topics?
Do I have to remove the old token and add the new token to device groups?
Is it possible to get information about device groups/topics for a token?
Can I add a token to a device group more than once?
Can I subscribe a token to a topic more than once?
Will multiple subscriptions/additions of the same token result in receiving duplicate messages
Sorry, that's a lot of questions, but I guess, for somebody who has gone through this, it should be pie ;)
Do I have to unsubscribe the old token and subscribe the new token to topics?
AFAIK, you don't have to unsubscribe the old token, since it will be discarded by FCM itself. For the new token, yes, you'll have to subscribe it to the topic you need. The usual thing is done (in Android) by having subscribeToTopic() in onTokenRefreshed().
Do I have to remove the old token and add the new token to device groups?
Yes. You have to handle the mapping/relationships for Device Group Messaging. See my answer here. This is different from topics. The token will be invalidated, but will be kept as part of the list of registration tokens for the corresponding registration key.
It's why there's a possibility to receive a NotRegistred error on one of the tokens if you send to Device Group. :)
Is it possible to get information about device groups/topics for a token?
For Device Group Messaging (same with #2), the developer (you) have to manage these details yourself. For topics, you can use the InstanceID API. Specifically, set details parameter to true:
[optional] boolean details: set this query parameter to true to get available IID token details, including connection information and FCM or GCM topic subscription information (if any) for the device associated with this token. When not specified, defaults to false.
Can I add a token to a device group more than once?
Ahmm. Yes. Do you mean the same token? If so, I haven't tried it yet. Might as well do some checking on the client side before adding.
Can I subscribe a token to a topic more than once?
If you mean re-subscribing, then yes. If you mean duplicate request to subscribe, I think the result would still be a success. No changes in behavior though.
Will multiple subscriptions/additions of the same token result in receiving duplicate messages?
Tested it out. You won't receive duplicate messages for both duplicate topic subscriptions and adding the same token to a device group. It seems that FCM ignores the request to subscribe/add a Registration token if it's already subscribed/added to a device group.

Push Notifications through Firebase

Yesterday Google has announced a new set of tools for Firebase, one of them was Notifications the ability to send notifications from server to devices which are using my app.
But can we now notify users when they receive a new message?
And if not, is there a way around to achieve this?
Looking at the documentation, this doesn't seem currently possible automatically. Here is a possible way to accomplish it "manually" with another server:
Subscribe a user to it's own user ID
In android
FirebaseMessaging.getInstance().subscribeToTopic("InsertUserIDHere");
In IOS
[[FIRMessaging messaging] subscribeToTopic:#"/topics/InsertUserIDHere"];
Setup an outside server that checks every sent messages. When a message is sent, the server should create a notification that includes the recipient's user ID as the topic.
Look here for more info.
You can send messages to group of users (targeting a specific "topic") or to a single device (targeting a Firebase Cloud Messaging token).
To subscribe a device to a topic use:
FirebaseMessaging.getInstance().subscribeToTopic("topicName");
To obtain the device token use (*1) :
FirebaseInstanceId.getInstance().getToken();
Then you can use the Firebase Notificaitons web console, or the FCM server API if you want to send messages from your server.
See: https://firebase.google.com/docs/cloud-messaging/downstream#sending_topic_messages_from_the_server
Notes:
[1] getToken() can return null if the token is not yet available.
You can use the callback onTokenRefresh() to be notified when the token is available and when the token is rotated.
See: https://firebase.google.com/docs/cloud-messaging/android/client#sample-register

Resources