Debian Codegraph @

push_notifications/gcm.py

raw
1 """
2 Firebase Cloud Messaging
3 Previously known as GCM / C2DM
4 Documentation is available on the Firebase Developer website:
5 https://firebase.google.com/docs/cloud-messaging/
6 """
7
8 import json
9
10 try:
11 from urllib.request import Request, urlopen
12 except ImportError:
13 # Python 2 support
14 from urllib2 import Request, urlopen
15
16 from django.core.exceptions import ImproperlyConfigured
17 from . import NotificationError
18 from .conf import get_manager
19 from .models import GCMDevice
20
21
22 # Valid keys for FCM messages. Reference:
23 # https://firebase.google.com/docs/cloud-messaging/http-server-ref
24 FCM_TARGETS_KEYS = [
25 "to", "condition", "notification_key"
26 ]
27 FCM_OPTIONS_KEYS = [
28 "collapse_key", "priority", "content_available", "delay_while_idle", "time_to_live",
29 "restricted_package_name", "dry_run"
30 ]
31 FCM_NOTIFICATIONS_PAYLOAD_KEYS = [
32 "title", "body", "icon", "sound", "badge", "color", "tag", "click_action",
33 "body_loc_key", "body_loc_args", "title_loc_key", "title_loc_args"
34 ]
35
36
37 class GCMError(NotificationError):
38 pass
39
40
41 def _chunks(l, n):
42 """
43 Yield successive chunks from list \a l with a minimum size \a n
44 """
45 for i in range(0, len(l), n):
46 yield l[i:i + n]
47
48
49 def _gcm_send(data, content_type, application_id):
50 key = get_manager().get_gcm_api_key(application_id)
51
52 headers = {
53 "Content-Type": content_type,
54 "Authorization": "key=%s" % (key),
55 "Content-Length": str(len(data)),
56 }
57 request = Request(get_manager().get_post_url("GCM", application_id), data, headers)
58 return urlopen(
59 request, timeout=get_manager().get_error_timeout("GCM", application_id)
60 ).read().decode("utf-8")
61
62
63 def _fcm_send(data, content_type, application_id):
64 key = get_manager().get_fcm_api_key(application_id)
65
66 headers = {
67 "Content-Type": content_type,
68 "Authorization": "key=%s" % (key),
69 "Content-Length": str(len(data)),
70 }
71 request = Request(get_manager().get_post_url("FCM", application_id), data, headers)
72 return urlopen(
73 request, timeout=get_manager().get_error_timeout("FCM", application_id)
74 ).read().decode("utf-8")
75
76
77 def _cm_handle_response(registration_ids, response_data, cloud_type, application_id=None):
78 response = response_data
79 if response.get("failure") or response.get("canonical_ids"):
80 ids_to_remove, old_new_ids = [], []
81 throw_error = False
82 for index, result in enumerate(response["results"]):
83 error = result.get("error")
84 if error:
85 # https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
86 # If error is NotRegistered or InvalidRegistration, then we will deactivate devices
87 # because this registration ID is no more valid and can't be used to send messages,
88 # otherwise raise error
89 if error in ("NotRegistered", "InvalidRegistration"):
90 ids_to_remove.append(registration_ids[index])
91 else:
92 throw_error = True
93 result["original_registration_id"] = registration_ids[index]
94 # If registration_id is set, replace the original ID with the new value (canonical ID)
95 # in your server database. Note that the original ID is not part of the result, you need
96 # to obtain it from the list of registration_ids in the request (using the same index).
97 new_id = result.get("registration_id")
98 if new_id:
99 old_new_ids.append((registration_ids[index], new_id))
100
101 if ids_to_remove:
102 removed = GCMDevice.objects.filter(
103 registration_id__in=ids_to_remove, cloud_message_type=cloud_type
104 )
105 removed.update(active=0)
106
107 for old_id, new_id in old_new_ids:
108 _cm_handle_canonical_id(new_id, old_id, cloud_type)
109
110 if throw_error:
111 raise GCMError(response)
112 return response
113
114
115 def _cm_send_request(
116 registration_ids, data, cloud_type="GCM", application_id=None,
117 use_fcm_notifications=True, **kwargs
118 ):
119 """
120 Sends a FCM or GCM notification to one or more registration_ids as json data.
121 The registration_ids needs to be a list.
122 """
123
124 payload = {"registration_ids": registration_ids} if registration_ids else {}
125
126 # If using FCM, optionnally autodiscovers notification related keys
127 # https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
128 if cloud_type == "FCM" and use_fcm_notifications:
129 notification_payload = {}
130 if "message" in data:
131 notification_payload["body"] = data.pop("message", None)
132
133 for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS:
134 value_from_extra = data.pop(key, None)
135 if value_from_extra:
136 notification_payload[key] = value_from_extra
137 value_from_kwargs = kwargs.pop(key, None)
138 if value_from_kwargs:
139 notification_payload[key] = value_from_kwargs
140 if notification_payload:
141 payload["notification"] = notification_payload
142
143 if data:
144 payload["data"] = data
145
146 # Attach any additional non falsy keyword args (targets, options)
147 # See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
148 payload.update({
149 k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS)
150 })
151
152 # Sort the keys for deterministic output (useful for tests)
153 json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
154
155 # Sends requests and handles the response
156 if cloud_type == "GCM":
157 response = json.loads(_gcm_send(
158 json_payload, "application/json", application_id=application_id
159 ))
160 elif cloud_type == "FCM":
161 response = json.loads(_fcm_send(
162 json_payload, "application/json", application_id=application_id
163 ))
164 else:
165 raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
166 return _cm_handle_response(registration_ids, response, cloud_type, application_id)
167
168
169 def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
170 """
171 Handle situation when FCM server response contains canonical ID
172 """
173 devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
174 if devices.filter(registration_id=canonical_id, active=True).exists():
175 devices.filter(registration_id=current_id).update(active=False)
176 else:
177 devices.filter(registration_id=current_id).update(registration_id=canonical_id)
178
179
180 def send_message(registration_ids, data, cloud_type, application_id=None, **kwargs):
181 """
182 Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids
183 can be a list or a single string. This will send the notification as json data.
184
185 A reference of extra keyword arguments sent to the server is available here:
186 https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
187 """
188 if cloud_type == "FCM":
189 max_recipients = get_manager().get_max_recipients(cloud_type, application_id)
190 elif cloud_type == "GCM":
191 max_recipients = get_manager().get_max_recipients(cloud_type, application_id)
192 else:
193 raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
194
195 # Checks for valid recipient
196 if registration_ids is None and "/topics/" not in kwargs.get("to", ""):
197 return
198
199 # Bundles the registration_ids in an list if only one is sent
200 if not isinstance(registration_ids, list):
201 registration_ids = [registration_ids] if registration_ids else None
202
203 # FCM only allows up to 1000 reg ids per bulk message
204 # https://firebase.google.com/docs/cloud-messaging/server#http-request
205 if registration_ids:
206 ret = []
207 for chunk in _chunks(registration_ids, max_recipients):
208 ret.append(_cm_send_request(
209 chunk, data, cloud_type=cloud_type, application_id=application_id, **kwargs
210 ))
211 return ret[0] if len(ret) == 1 else ret
212 else:
213 return _cm_send_request(None, data, cloud_type=cloud_type, **kwargs)
214
215
216 send_bulk_message = send_message