-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathFirebaseMessaging.java
More file actions
688 lines (628 loc) · 30.3 KB
/
FirebaseMessaging.java
File metadata and controls
688 lines (628 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.messaging;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.firebase.ErrorCode;
import com.google.firebase.FirebaseApp;
import com.google.firebase.ImplFirebaseTrampolines;
import com.google.firebase.internal.CallableOperation;
import com.google.firebase.internal.FirebaseService;
import com.google.firebase.internal.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* This class is the entry point for all server-side Firebase Cloud Messaging actions.
*
* <p>You can get an instance of FirebaseMessaging via {@link #getInstance(FirebaseApp)}, and
* then use it to send messages or manage FCM topic subscriptions.
*/
public class FirebaseMessaging {
private final FirebaseApp app;
private final Supplier<? extends FirebaseMessagingClient> messagingClient;
private final Supplier<? extends InstanceIdClient> instanceIdClient;
private FirebaseMessaging(Builder builder) {
this.app = checkNotNull(builder.firebaseApp);
this.messagingClient = Suppliers.memoize(builder.messagingClient);
this.instanceIdClient = Suppliers.memoize(builder.instanceIdClient);
}
/**
* Gets the {@link FirebaseMessaging} instance for the default {@link FirebaseApp}.
*
* @return The {@link FirebaseMessaging} instance for the default {@link FirebaseApp}.
*/
public static FirebaseMessaging getInstance() {
return getInstance(FirebaseApp.getInstance());
}
/**
* Gets the {@link FirebaseMessaging} instance for the specified {@link FirebaseApp}.
*
* @return The {@link FirebaseMessaging} instance for the specified {@link FirebaseApp}.
*/
public static synchronized FirebaseMessaging getInstance(FirebaseApp app) {
FirebaseMessagingService service = ImplFirebaseTrampolines.getService(app, SERVICE_ID,
FirebaseMessagingService.class);
if (service == null) {
service = ImplFirebaseTrampolines.addService(app, new FirebaseMessagingService(app));
}
return service.getInstance();
}
/**
* Sends the given {@link Message} via Firebase Cloud Messaging.
*
* @param message A non-null {@link Message} to be sent.
* @return A message ID string.
* @throws FirebaseMessagingException If an error occurs while handing the message off to FCM for
* delivery.
*/
public String send(@NonNull Message message) throws FirebaseMessagingException {
return send(message, false);
}
/**
* Sends the given {@link Message} via Firebase Cloud Messaging.
*
* <p>If the {@code dryRun} option is set to true, the message will not be actually sent. Instead
* FCM performs all the necessary validations and emulates the send operation. The {@code dryRun}
* option is useful for determining whether an FCM registration has been deleted. However, it
* cannot be used to validate APNs tokens.
*
* @param message A non-null {@link Message} to be sent.
* @param dryRun a boolean indicating whether to perform a dry run (validation only) of the send.
* @return A message ID string.
* @throws FirebaseMessagingException If an error occurs while handing the message off to FCM for
* delivery.
*/
public String send(@NonNull Message message, boolean dryRun) throws FirebaseMessagingException {
return sendOp(message, dryRun).call();
}
/**
* Similar to {@link #send(Message)} but performs the operation asynchronously.
*
* @param message A non-null {@link Message} to be sent.
* @return An {@code ApiFuture} that will complete with a message ID string when the message
* has been sent.
*/
public ApiFuture<String> sendAsync(@NonNull Message message) {
return sendAsync(message, false);
}
/**
* Similar to {@link #send(Message, boolean)} but performs the operation asynchronously.
*
* @param message A non-null {@link Message} to be sent.
* @param dryRun a boolean indicating whether to perform a dry run (validation only) of the send.
* @return An {@code ApiFuture} that will complete with a message ID string when the message
* has been sent, or when the emulation has finished.
*/
public ApiFuture<String> sendAsync(@NonNull Message message, boolean dryRun) {
return sendOp(message, dryRun).callAsync(app);
}
private CallableOperation<String, FirebaseMessagingException> sendOp(
final Message message, final boolean dryRun) {
checkNotNull(message, "message must not be null");
final FirebaseMessagingClient messagingClient = getMessagingClient();
return new CallableOperation<String, FirebaseMessagingException>() {
@Override
protected String execute() throws FirebaseMessagingException {
return messagingClient.send(message, dryRun);
}
};
}
/**
* Sends each message in the given list via Firebase Cloud Messaging.
* Unlike {@link #sendAll(List)}, this method makes an HTTP call for each message in the
* given array.
*
* <p>The list of responses obtained by calling {@link BatchResponse#getResponses()} on the return
* value is in the same order as the input list.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here or a {@link BatchResponse} with all failures indicates a total
* failure, meaning that none of the messages in the list could be sent. Partial failures or
* no failures are only indicated by a {@link BatchResponse}.
*/
public BatchResponse sendEach(@NonNull List<Message> messages) throws FirebaseMessagingException {
return sendEach(messages, false);
}
/**
* Sends each message in the given list via Firebase Cloud Messaging.
* Unlike {@link #sendAll(List)}, this method makes an HTTP call for each message in the
* given array.
*
* <p>If the {@code dryRun} option is set to true, the message will not be actually sent. Instead
* FCM performs all the necessary validations, and emulates the send operation. The {@code dryRun}
* option is useful for determining whether an FCM registration has been deleted. But it cannot be
* used to validate APNs tokens.
*
* <p>The list of responses obtained by calling {@link BatchResponse#getResponses()} on the return
* value is in the same order as the input list.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here or a {@link BatchResponse} with all failures indicates a total
* failure, meaning that none of the messages in the list could be sent. Partial failures or
* no failures are only indicated by a {@link BatchResponse}.
*/
public BatchResponse sendEach(
@NonNull List<Message> messages, boolean dryRun) throws FirebaseMessagingException {
try {
return sendEachOpAsync(messages, dryRun).get();
} catch (InterruptedException | ExecutionException e) {
throw new FirebaseMessagingException(ErrorCode.CANCELLED, SERVICE_ID);
}
}
/**
* Similar to {@link #sendEach(List)} but performs the operation asynchronously.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent.
*/
public ApiFuture<BatchResponse> sendEachAsync(@NonNull List<Message> messages) {
return sendEachOpAsync(messages, false);
}
/**
* Similar to {@link #sendEach(List, boolean)} but performs the operation asynchronously.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent.
*/
public ApiFuture<BatchResponse> sendEachAsync(@NonNull List<Message> messages, boolean dryRun) {
return sendEachOpAsync(messages, dryRun);
}
// Returns an ApiFuture directly since this function is non-blocking. Individual child send
// requests are still called async and run in background threads.
private ApiFuture<BatchResponse> sendEachOpAsync(
final List<Message> messages, final boolean dryRun) {
final List<Message> immutableMessages = ImmutableList.copyOf(messages);
checkArgument(!immutableMessages.isEmpty(), "messages list must not be empty");
checkArgument(immutableMessages.size() <= 500,
"messages list must not contain more than 500 elements");
List<ApiFuture<SendResponse>> list = new ArrayList<>();
for (Message message : immutableMessages) {
// Make async send calls per message
ApiFuture<SendResponse> messageId = sendOpForSendResponse(message, dryRun).callAsync(app);
list.add(messageId);
}
// Gather all futures and combine into a list
ApiFuture<List<SendResponse>> responsesFuture = ApiFutures.allAsList(list);
// Chain this future to wrap the eventual responses in a BatchResponse without blocking
// the main thread. This uses the current thread to execute, but since the transformation
// function is non-blocking the transformation itself is also non-blocking.
return ApiFutures.transform(
responsesFuture,
(responses) -> {
return new BatchResponseImpl(responses);
},
MoreExecutors.directExecutor());
}
private CallableOperation<SendResponse, FirebaseMessagingException> sendOpForSendResponse(
final Message message, final boolean dryRun) {
checkNotNull(message, "message must not be null");
final FirebaseMessagingClient messagingClient = getMessagingClient();
return new CallableOperation<SendResponse, FirebaseMessagingException>() {
@Override
protected SendResponse execute() {
try {
String messageId = messagingClient.send(message, dryRun);
return SendResponse.fromMessageId(messageId);
} catch (FirebaseMessagingException e) {
return SendResponse.fromException(e);
}
}
};
}
/**
* Sends the given multicast message to all the FCM registration tokens and/or FIDs
* specified in it.
*
* <p>This method uses the {@link #sendEach(List)} API under the hood to send the given
* message to all the target recipients. The list of responses obtained by calling
* {@link BatchResponse#getResponses()} on the return value is in the same order as the
* tokens and/or FIDs in the {@link MulticastMessage}. If both tokens and FIDs are
* provided, tokens are processed first, followed by FIDs.
*
* @param message A non-null {@link MulticastMessage}
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here or a {@link BatchResponse} with all failures indicates a total
* failure, meaning that none of the messages in the list could be sent. Partial failures or
* no failures are only indicated by a {@link BatchResponse}.
*/
public BatchResponse sendEachForMulticast(
@NonNull MulticastMessage message) throws FirebaseMessagingException {
return sendEachForMulticast(message, false);
}
/**
* Sends the given multicast message to all the FCM registration tokens and/or FIDs
* specified in it.
*
* <p>If the {@code dryRun} option is set to true, the message will not be actually sent.
* Instead FCM performs all the necessary validations, and emulates the send operation.
* The {@code dryRun} option is useful for determining whether an FCM registration has
* been deleted. But it cannot be used to validate APNs tokens.
*
* <p>This method uses the {@link #sendEach(List)} API under the hood to send the given
* message to all the target recipients. The list of responses obtained by calling
* {@link BatchResponse#getResponses()} on the return value is in the same order as the
* tokens and/or FIDs in the {@link MulticastMessage}. If both tokens and FIDs are
* provided, tokens are processed first, followed by FIDs.
*
* @param message A non-null {@link MulticastMessage}.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here or a {@link BatchResponse} with all failures indicates a total
* failure, meaning that none of the messages in the list could be sent. Partial failures or
* no failures are only indicated by a {@link BatchResponse}.
*/
public BatchResponse sendEachForMulticast(@NonNull MulticastMessage message, boolean dryRun)
throws FirebaseMessagingException {
checkNotNull(message, "multicast message must not be null");
return sendEach(message.getMessageList(), dryRun);
}
/**
* Similar to {@link #sendEachForMulticast(MulticastMessage)} but performs the operation
* asynchronously.
*
* @param message A non-null {@link MulticastMessage}.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent.
*/
public ApiFuture<BatchResponse> sendEachForMulticastAsync(@NonNull MulticastMessage message) {
return sendEachForMulticastAsync(message, false);
}
/**
* Similar to {@link #sendEachForMulticast(MulticastMessage, boolean)} but performs the operation
* asynchronously.
*
* @param message A non-null {@link MulticastMessage}.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent.
*/
public ApiFuture<BatchResponse> sendEachForMulticastAsync(
@NonNull MulticastMessage message, boolean dryRun) {
checkNotNull(message, "multicast message must not be null");
return sendEachAsync(message.getMessageList(), dryRun);
}
/**
* Sends all the messages in the given list via Firebase Cloud Messaging. Employs batching to
* send the entire list as a single RPC call. Compared to the {@link #send(Message)} method, this
* is a significantly more efficient way to send multiple messages.
*
* <p>The responses list obtained by calling {@link BatchResponse#getResponses()} on the return
* value corresponds to the order of input messages.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here indicates a total failure, meaning that none of the messages in
* the list could be sent. Partial failures are indicated by a {@link BatchResponse} return
* value.
* @deprecated Use {@link #sendEach(List)} instead.
*/
@Deprecated
public BatchResponse sendAll(
@NonNull List<Message> messages) throws FirebaseMessagingException {
return sendAll(messages, false);
}
/**
* Sends all the messages in the given list via Firebase Cloud Messaging. Employs batching to
* send the entire list as a single RPC call. Compared to the {@link #send(Message)} method, this
* is a significantly more efficient way to send multiple messages.
*
* <p>If the {@code dryRun} option is set to true, the message will not be actually sent. Instead
* FCM performs all the necessary validations, and emulates the send operation. The {@code dryRun}
* option is useful for determining whether an FCM registration has been deleted. But it cannot be
* used to validate APNs tokens.
*
* <p>The responses list obtained by calling {@link BatchResponse#getResponses()} on the return
* value corresponds to the order of input messages.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here indicates a total failure, meaning that none of the messages in
* the list could be sent. Partial failures are indicated by a {@link BatchResponse} return
* value.
* @deprecated Use {@link #sendEach(List, boolean)} instead.
*/
@Deprecated
public BatchResponse sendAll(
@NonNull List<Message> messages, boolean dryRun) throws FirebaseMessagingException {
return sendAllOp(messages, dryRun).call();
}
/**
* Similar to {@link #sendAll(List)} but performs the operation asynchronously.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent.
* @deprecated Use {@link #sendEachAsync(List)} instead.
*/
@Deprecated
public ApiFuture<BatchResponse> sendAllAsync(@NonNull List<Message> messages) {
return sendAllAsync(messages, false);
}
/**
* Similar to {@link #sendAll(List, boolean)} but performs the operation asynchronously.
*
* @param messages A non-null, non-empty list containing up to 500 messages.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent, or when the emulation has finished.
* @deprecated Use {@link #sendEachAsync(List, boolean)} instead.
*/
@Deprecated
public ApiFuture<BatchResponse> sendAllAsync(
@NonNull List<Message> messages, boolean dryRun) {
return sendAllOp(messages, dryRun).callAsync(app);
}
/**
* Sends the given multicast message to all the FCM registration tokens and/or FIDs
* specified in it.
*
* <p>This method uses the {@link #sendAll(List)} API under the hood to send the given
* message to all the target recipients. The responses list obtained by calling
* {@link BatchResponse#getResponses()} on the return value corresponds to the order of
* tokens and/or FIDs in the {@link MulticastMessage}. If both tokens and FIDs are
* provided, tokens are processed first, followed by FIDs.
*
* @param message A non-null {@link MulticastMessage}
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here indicates a total failure, meaning that the messages could not
* be delivered to any recipient. Partial failures are indicated by a {@link BatchResponse}
* return value.
* @deprecated Use {@link #sendEachForMulticast(MulticastMessage)} instead.
*/
@Deprecated
public BatchResponse sendMulticast(
@NonNull MulticastMessage message) throws FirebaseMessagingException {
return sendMulticast(message, false);
}
/**
* Sends the given multicast message to all the FCM registration tokens and/or FIDs
* specified in it.
*
* <p>If the {@code dryRun} option is set to true, the message will not be actually sent.
* Instead FCM performs all the necessary validations, and emulates the send operation.
* The {@code dryRun} option is useful for determining whether an FCM registration has
* been deleted. But it cannot be used to validate APNs tokens.
*
* <p>This method uses the {@link #sendAll(List)} API under the hood to send the given
* message to all the target recipients. The responses list obtained by calling
* {@link BatchResponse#getResponses()} on the return value corresponds to the order of
* tokens and/or FIDs in the {@link MulticastMessage}. If both tokens and FIDs are
* provided, tokens are processed first, followed by FIDs.
*
* @param message A non-null {@link MulticastMessage}.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return A {@link BatchResponse} indicating the result of the operation.
* @throws FirebaseMessagingException If an error occurs while handing the messages off to FCM for
* delivery. An exception here indicates a total failure, meaning that the messages could not
* be delivered to any recipient. Partial failures are indicated by a {@link BatchResponse}
* return value.
* @deprecated Use {@link #sendEachForMulticast(MulticastMessage, boolean)} instead.
*/
@Deprecated
public BatchResponse sendMulticast(
@NonNull MulticastMessage message, boolean dryRun) throws FirebaseMessagingException {
checkNotNull(message, "multicast message must not be null");
return sendAll(message.getMessageList(), dryRun);
}
/**
* Similar to {@link #sendMulticast(MulticastMessage)} but performs the operation
* asynchronously.
*
* @param message A non-null {@link MulticastMessage}.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent.
* @deprecated Use {@link #sendEachForMulticastAsync(MulticastMessage)} instead.
*/
@Deprecated
public ApiFuture<BatchResponse> sendMulticastAsync(@NonNull MulticastMessage message) {
return sendMulticastAsync(message, false);
}
/**
* Similar to {@link #sendMulticast(MulticastMessage, boolean)} but performs the operation
* asynchronously.
*
* @param message A non-null {@link MulticastMessage}.
* @param dryRun A boolean indicating whether to perform a dry run (validation only) of the send.
* @return An {@code ApiFuture} that will complete with a {@link BatchResponse} when
* the messages have been sent.
* @deprecated Use {@link #sendEachForMulticastAsync(MulticastMessage, boolean)} instead.
*/
@Deprecated
public ApiFuture<BatchResponse> sendMulticastAsync(
@NonNull MulticastMessage message, boolean dryRun) {
checkNotNull(message, "multicast message must not be null");
return sendAllAsync(message.getMessageList(), dryRun);
}
private CallableOperation<BatchResponse, FirebaseMessagingException> sendAllOp(
final List<Message> messages, final boolean dryRun) {
final List<Message> immutableMessages = ImmutableList.copyOf(messages);
checkArgument(!immutableMessages.isEmpty(), "messages list must not be empty");
checkArgument(immutableMessages.size() <= 500,
"messages list must not contain more than 500 elements");
final FirebaseMessagingClient messagingClient = getMessagingClient();
return new CallableOperation<BatchResponse,FirebaseMessagingException>() {
@Override
protected BatchResponse execute() throws FirebaseMessagingException {
return messagingClient.sendAll(messages, dryRun);
}
};
}
@VisibleForTesting
FirebaseMessagingClient getMessagingClient() {
return messagingClient.get();
}
/**
* Subscribes a list of registration tokens to a topic.
*
* @param registrationTokens A non-null, non-empty list of device registration tokens, with at
* most 1000 entries.
* @param topic Name of the topic to subscribe to. May contain the {@code /topics/} prefix.
* @return A {@link TopicManagementResponse}.
*/
public TopicManagementResponse subscribeToTopic(@NonNull List<String> registrationTokens,
@NonNull String topic) throws FirebaseMessagingException {
return subscribeOp(registrationTokens, topic).call();
}
/**
* Similar to {@link #subscribeToTopic(List, String)} but performs the operation asynchronously.
*
* @param registrationTokens A non-null, non-empty list of device registration tokens, with at
* most 1000 entries.
* @param topic Name of the topic to subscribe to. May contain the {@code /topics/} prefix.
* @return An {@code ApiFuture} that will complete with a {@link TopicManagementResponse}.
*/
public ApiFuture<TopicManagementResponse> subscribeToTopicAsync(
@NonNull List<String> registrationTokens, @NonNull String topic) {
return subscribeOp(registrationTokens, topic).callAsync(app);
}
private CallableOperation<TopicManagementResponse, FirebaseMessagingException> subscribeOp(
final List<String> registrationTokens, final String topic) {
checkRegistrationTokens(registrationTokens);
checkTopic(topic);
final InstanceIdClient instanceIdClient = getInstanceIdClient();
return new CallableOperation<TopicManagementResponse, FirebaseMessagingException>() {
@Override
protected TopicManagementResponse execute() throws FirebaseMessagingException {
return instanceIdClient.subscribeToTopic(topic, registrationTokens);
}
};
}
/**
* Unsubscribes a list of registration tokens from a topic.
*
* @param registrationTokens A non-null, non-empty list of device registration tokens, with at
* most 1000 entries.
* @param topic Name of the topic to unsubscribe from. May contain the {@code /topics/} prefix.
* @return A {@link TopicManagementResponse}.
*/
public TopicManagementResponse unsubscribeFromTopic(@NonNull List<String> registrationTokens,
@NonNull String topic) throws FirebaseMessagingException {
return unsubscribeOp(registrationTokens, topic).call();
}
/**
* Similar to {@link #unsubscribeFromTopic(List, String)} but performs the operation
* asynchronously.
*
* @param registrationTokens A non-null, non-empty list of device registration tokens, with at
* most 1000 entries.
* @param topic Name of the topic to unsubscribe from. May contain the {@code /topics/} prefix.
* @return An {@code ApiFuture} that will complete with a {@link TopicManagementResponse}.
*/
public ApiFuture<TopicManagementResponse> unsubscribeFromTopicAsync(
@NonNull List<String> registrationTokens, @NonNull String topic) {
return unsubscribeOp(registrationTokens, topic).callAsync(app);
}
private CallableOperation<TopicManagementResponse, FirebaseMessagingException> unsubscribeOp(
final List<String> registrationTokens, final String topic) {
checkRegistrationTokens(registrationTokens);
checkTopic(topic);
final InstanceIdClient instanceIdClient = getInstanceIdClient();
return new CallableOperation<TopicManagementResponse, FirebaseMessagingException>() {
@Override
protected TopicManagementResponse execute() throws FirebaseMessagingException {
return instanceIdClient.unsubscribeFromTopic(topic, registrationTokens);
}
};
}
@VisibleForTesting
InstanceIdClient getInstanceIdClient() {
return this.instanceIdClient.get();
}
private void checkRegistrationTokens(List<String> registrationTokens) {
checkArgument(registrationTokens != null && !registrationTokens.isEmpty(),
"registrationTokens list must not be null or empty");
checkArgument(registrationTokens.size() <= 1000,
"registrationTokens list must not contain more than 1000 elements");
for (String token : registrationTokens) {
checkArgument(!Strings.isNullOrEmpty(token),
"registration tokens list must not contain null or empty strings");
}
}
private void checkTopic(String topic) {
checkArgument(!Strings.isNullOrEmpty(topic), "topic must not be null or empty");
checkArgument(topic.matches("^(/topics/)?(private/)?[a-zA-Z0-9-_.~%]+$"), "invalid topic name");
}
private static final String SERVICE_ID = FirebaseMessaging.class.getName();
private static class FirebaseMessagingService extends FirebaseService<FirebaseMessaging> {
FirebaseMessagingService(FirebaseApp app) {
super(SERVICE_ID, FirebaseMessaging.fromApp(app));
}
}
private static FirebaseMessaging fromApp(final FirebaseApp app) {
return FirebaseMessaging.builder()
.setFirebaseApp(app)
.setMessagingClient(new Supplier<FirebaseMessagingClient>() {
@Override
public FirebaseMessagingClient get() {
return FirebaseMessagingClientImpl.fromApp(app);
}
})
.setInstanceIdClient(new Supplier<InstanceIdClient>() {
@Override
public InstanceIdClientImpl get() {
return InstanceIdClientImpl.fromApp(app);
}
})
.build();
}
static Builder builder() {
return new Builder();
}
static class Builder {
private FirebaseApp firebaseApp;
private Supplier<? extends FirebaseMessagingClient> messagingClient;
private Supplier<? extends InstanceIdClient> instanceIdClient;
private Builder() { }
Builder setFirebaseApp(FirebaseApp firebaseApp) {
this.firebaseApp = firebaseApp;
return this;
}
Builder setMessagingClient(Supplier<? extends FirebaseMessagingClient> messagingClient) {
this.messagingClient = messagingClient;
return this;
}
Builder setInstanceIdClient(Supplier<? extends InstanceIdClient> instanceIdClient) {
this.instanceIdClient = instanceIdClient;
return this;
}
FirebaseMessaging build() {
return new FirebaseMessaging(this);
}
}
}