-
Notifications
You must be signed in to change notification settings - Fork 207
/
fcm.py
576 lines (541 loc) · 31.1 KB
/
fcm.py
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
from .baseapi import BaseAPI
from .errors import InvalidDataError
class FCMNotification(BaseAPI):
def notify_single_device(self,
registration_id,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
click_action=None,
badge=None,
color=None,
tag=None,
body_loc_key=None,
body_loc_args=None,
title_loc_key=None,
title_loc_args=None,
content_available=None,
android_channel_id=None,
timeout=120,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Send push notification to a single device
Args:
registration_id (list, optional): FCM device registration ID
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to display in the notification tray
message_icon (str, optional): Icon that apperas next to the notification
sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
click_action (str, optional): Action associated with a user click on the notification
badge (str, optional): Badge of notification
color (str, optional): Color of the icon
tag (str, optional): Group notification by tag
body_loc_key (str, optional): Indicates the key to the body string for localization
body_loc_args (list, optional): Indicates the string value to replace format
specifiers in body string for localization
title_loc_key (str, optional): Indicates the key to the title string for localization
title_loc_args (list, optional): Indicates the string value to replace format
specifiers in title string for localization
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: Mostly from changes in the response of FCM,
contact the project owner to resolve the issue
"""
# [registration_id] cos we're sending to a single device
payload = self.parse_payload(
registration_ids=[registration_id],
message_body=message_body,
message_title=message_title,
message_icon=message_icon,
sound=sound,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run, data_message=data_message, click_action=click_action,
badge=badge,
color=color,
tag=tag,
body_loc_key=body_loc_key,
body_loc_args=body_loc_args,
title_loc_key=title_loc_key,
title_loc_args=title_loc_args,
android_channel_id=android_channel_id,
content_available=content_available,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs
)
self.send_request([payload], timeout)
return self.parse_responses()
def single_device_data_message(self,
registration_id=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
content_available=None,
android_channel_id=None,
timeout=120,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Send push message to a single device
Args:
registration_id (list, optional): FCM device registration ID
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: Mostly from changes in the response of FCM,
contact the project owner to resolve the issue
"""
if registration_id is None:
raise InvalidDataError('Invalid registration ID')
# [registration_id] cos we're sending to a single device
payload = self.parse_payload(
registration_ids=[registration_id],
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run,
data_message=data_message,
content_available=content_available,
remove_notification=True,
android_channel_id=android_channel_id,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs
)
self.send_request([payload], timeout)
return self.parse_responses()
def notify_multiple_devices(self,
registration_ids,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
click_action=None,
badge=None,
color=None,
tag=None,
body_loc_key=None,
body_loc_args=None,
title_loc_key=None,
title_loc_args=None,
content_available=None,
android_channel_id=None,
timeout=120,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends push notification to multiple devices, can send to over 1000 devices
Args:
registration_ids (list, optional): FCM device registration IDs
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to display in the notification tray
message_icon (str, optional): Icon that apperas next to the notification
sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
click_action (str, optional): Action associated with a user click on the notification
badge (str, optional): Badge of notification
color (str, optional): Color of the icon
tag (str, optional): Group notification by tag
body_loc_key (str, optional): Indicates the key to the body string for localization
body_loc_args (list, optional): Indicates the string value to replace format
specifiers in body string for localization
title_loc_key (str, optional): Indicates the key to the title string for localization
title_loc_args (list, optional): Indicates the string value to replace format
specifiers in title string for localization
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM,
create a new github issue to resolve it.
"""
if not isinstance(registration_ids, list):
raise InvalidDataError('Invalid registration IDs (should be list)')
payloads = []
registration_id_chunks = self.registration_id_chunks(registration_ids)
for registration_ids in registration_id_chunks:
# appends a payload with a chunk of registration ids here
payloads.append(self.parse_payload(
registration_ids=registration_ids,
message_body=message_body,
message_title=message_title,
message_icon=message_icon,
sound=sound,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run, data_message=data_message,
click_action=click_action,
badge=badge,
color=color,
tag=tag,
body_loc_key=body_loc_key,
body_loc_args=body_loc_args,
title_loc_key=title_loc_key,
title_loc_args=title_loc_args,
content_available=content_available,
android_channel_id=android_channel_id,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs
))
self.send_request(payloads, timeout)
return self.parse_responses()
def multiple_devices_data_message(self,
registration_ids=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
content_available=None,
timeout=120,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends push message to multiple devices, can send to over 1000 devices
Args:
registration_ids (list, optional): FCM device registration IDs
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
content_available (bool, optional): Inactive client app is awoken
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM,
create a new github issue to resolve it.
"""
if not isinstance(registration_ids, list):
raise InvalidDataError('Invalid registration IDs (should be list)')
payloads = []
registration_id_chunks = self.registration_id_chunks(registration_ids)
for registration_ids in registration_id_chunks:
# appends a payload with a chunk of registration ids here
payloads.append(self.parse_payload(
registration_ids=registration_ids,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run,
data_message=data_message,
content_available=content_available,
remove_notification=True,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs)
)
self.send_request(payloads, timeout)
return self.parse_responses()
def notify_topic_subscribers(self,
topic_name=None,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
click_action=None,
badge=None,
color=None,
tag=None,
body_loc_key=None,
body_loc_args=None,
title_loc_key=None,
title_loc_args=None,
content_available=None,
android_channel_id=None,
timeout=120,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends push notification to multiple devices subscribed to a topic
Args:
topic_name (str, optional): Name of the topic to deliver messages to
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to display in the notification tray
message_icon (str, optional): Icon that apperas next to the notification
sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
click_action (str, optional): Action associated with a user click on the notification
badge (str, optional): Badge of notification
color (str, optional): Color of the icon
tag (str, optional): Group notification by tag
body_loc_key (str, optional): Indicates the key to the body string for localization
body_loc_args (list, optional): Indicates the string value to replace format
specifiers in body string for localization
title_loc_key (str, optional): Indicates the key to the title string for localization
title_loc_args (list, optional): Indicates the string value to replace format
specifiers in title string for localization
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM,
create a new github issue to resolve it.
"""
payload = self.parse_payload(
topic_name=topic_name,
condition=condition,
message_body=message_body,
message_title=message_title,
message_icon=message_icon,
sound=sound,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run, data_message=data_message, click_action=click_action,
badge=badge,
color=color,
tag=tag,
body_loc_key=body_loc_key,
body_loc_args=body_loc_args,
title_loc_key=title_loc_key,
title_loc_args=title_loc_args,
content_available=content_available,
android_channel_id=android_channel_id,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs
)
self.send_request([payload], timeout)
return self.parse_responses()
def topic_subscribers_data_message(self,
topic_name=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
content_available=None,
timeout=120,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends data notification to multiple devices subscribed to a topic
Args:
topic_name (topic_name): Name of the topic to deliver messages to
condition (condition): Topic condition to deliver messages to
A topic name is a string that can be formed with any character in [a-zA-Z0-9-_.~%]
data_message (dict): Data message payload to send alone or with the notification message
Keyword Args:
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to ``None``.
delay_while_idle (bool, optional): If ``True`` indicates that the
message should not be sent until the device becomes active.
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to ``None``
which uses the FCM default of 4 weeks.
low_priority (boolean, optional): Whether to send notification with
the low priority flag. Defaults to ``False``.
restricted_package_name (str, optional): Package name of the
application where the registration IDs must match in order to
receive the message. Defaults to ``None``.
dry_run (bool, optional): If ``True`` no message will be sent but
request will be tested.
Returns:
:tuple:`multicast_id(long), success(int), failure(int), canonical_ids(int), results(list)`:
Response from FCM server.
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM, create a new github issue to resolve it.
"""
if extra_kwargs is None:
extra_kwargs = {}
payload = self.parse_payload(topic_name=topic_name,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run,
data_message=data_message,
content_available=content_available,
remove_notification=True,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs)
self.send_request([payload], timeout)
return self.parse_responses()
def async_notify_multiple_devices(self,params_list=[],timeout=5):
"""
Sends push notification to multiple devices with personalized templates
Args:
params_list (list): list of parameters ( the sames as notify_multiple_devices)
timeout (int, optional): set time limit for the request
"""
payloads = [ self.parse_payload(params) for params in params_list ]
return self.send_async_request(payloads=payloads,timeout=timeout)