Debian Codegraph @

push_notifications/wns.py

raw
1 """
2 Windows Notification Service
3
4 Documentation is available on the Windows Dev Center:
5 https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-windows-push-notification-services--wns--overview
6 """
7
8 import json
9 import xml.etree.ElementTree as ET
10
11 try:
12 from urllib.error import HTTPError
13 from urllib.parse import urlencode
14 from urllib.request import Request, urlopen
15 except ImportError:
16 # Python 2 support
17 from urllib2 import HTTPError, Request, urlopen
18 from urllib import urlencode
19
20 from django.core.exceptions import ImproperlyConfigured
21 from . import NotificationError
22 from .conf import get_manager
23 from .settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
24
25
26 class WNSError(NotificationError):
27 pass
28
29
30 class WNSAuthenticationError(WNSError):
31 pass
32
33
34 class WNSNotificationResponseError(WNSError):
35 pass
36
37
38 def _wns_authenticate(scope="notify.windows.com", application_id=None):
39 """
40 Requests an Access token for WNS communication.
41
42 :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
43 """
44 client_id = get_manager().get_wns_package_security_id(application_id)
45 client_secret = get_manager().get_wns_secret_key(application_id)
46 if not client_id:
47 raise ImproperlyConfigured(
48 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.'
49 )
50
51 if not client_secret:
52 raise ImproperlyConfigured(
53 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.'
54 )
55
56 headers = {
57 "Content-Type": "application/x-www-form-urlencoded",
58 }
59 params = {
60 "grant_type": "client_credentials",
61 "client_id": client_id,
62 "client_secret": client_secret,
63 "scope": scope,
64 }
65 data = urlencode(params).encode("utf-8")
66
67 request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers)
68 try:
69 response = urlopen(request)
70 except HTTPError as err:
71 if err.code == 400:
72 # One of your settings is probably jacked up.
73 # https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245
74 raise WNSAuthenticationError("Authentication failed, check your WNS settings.")
75 raise err
76
77 oauth_data = response.read().decode("utf-8")
78 try:
79 oauth_data = json.loads(oauth_data)
80 except Exception:
81 # Upstream WNS issue
82 raise WNSAuthenticationError("Received invalid JSON data from WNS.")
83
84 access_token = oauth_data.get("access_token")
85 if not access_token:
86 # Upstream WNS issue
87 raise WNSAuthenticationError("Access token missing from WNS response.")
88
89 return access_token
90
91
92 def _wns_send(uri, data, wns_type="wns/toast", application_id=None):
93 """
94 Sends a notification data and authentication to WNS.
95
96 :param uri: str: The device's unique notification URI
97 :param data: dict: The notification data to be sent.
98 :return:
99 """
100 access_token = _wns_authenticate(application_id=application_id)
101
102 content_type = "text/xml"
103 if wns_type == "wns/raw":
104 content_type = "application/octet-stream"
105
106 headers = {
107 # content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw)
108 "Content-Type": content_type,
109 "Authorization": "Bearer %s" % (access_token),
110 "X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw
111 }
112
113 if type(data) is str:
114 data = data.encode("utf-8")
115
116 request = Request(uri, data, headers)
117
118 # A lot of things can happen, let them know which one.
119 try:
120 response = urlopen(request)
121 except HTTPError as err:
122 if err.code == 400:
123 msg = "One or more headers were specified incorrectly or conflict with another header."
124 elif err.code == 401:
125 msg = "The cloud service did not present a valid authentication ticket."
126 elif err.code == 403:
127 msg = "The cloud service is not authorized to send a notification to this URI."
128 elif err.code == 404:
129 msg = "The channel URI is not valid or is not recognized by WNS."
130 elif err.code == 405:
131 msg = "Invalid method. Only POST or DELETE is allowed."
132 elif err.code == 406:
133 msg = "The cloud service exceeded its throttle limit"
134 elif err.code == 410:
135 msg = "The channel expired."
136 elif err.code == 413:
137 msg = "The notification payload exceeds the 500 byte limit."
138 elif err.code == 500:
139 msg = "An internal failure caused notification delivery to fail."
140 elif err.code == 503:
141 msg = "The server is currently unavailable."
142 else:
143 raise err
144 raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg))
145
146 return response.read().decode("utf-8")
147
148
149 def _wns_prepare_toast(data, **kwargs):
150 """
151 Creates the xml tree for a `toast` notification
152
153 :param data: dict: The notification data to be converted to an xml tree.
154
155 {
156 "text": ["Title text", "Message Text", "Another message!"],
157 "image": ["src1", "src2"],
158 }
159
160 :return: str
161 """
162 root = ET.Element("toast")
163 visual = ET.SubElement(root, "visual")
164 binding = ET.SubElement(visual, "binding")
165 binding.attrib["template"] = kwargs.pop("template", "ToastText01")
166 if "text" in data:
167 for count, item in enumerate(data["text"], start=1):
168 elem = ET.SubElement(binding, "text")
169 elem.text = item
170 elem.attrib["id"] = str(count)
171 if "image" in data:
172 for count, item in enumerate(data["image"], start=1):
173 elem = ET.SubElement(binding, "img")
174 elem.attrib["src"] = item
175 elem.attrib["id"] = str(count)
176 return ET.tostring(root)
177
178
179 def wns_send_message(
180 uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
181 ):
182 """
183 Sends a notification request to WNS.
184 There are four notification types that WNS can send: toast, tile, badge and raw.
185 Toast, tile, and badge can all be customized to use different
186 templates/icons/sounds/launch params/etc.
187 See docs for more information:
188 https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx
189
190 There are multiple ways to input notification data:
191
192 1. The simplest and least custom notification to send is to just pass a string
193 to `message`. This will create a toast notification with one text element. e.g.:
194 "This is my notification title"
195
196 2. You can also pass a dictionary to `message`: it can only contain one or both
197 keys: ["text", "image"]. The value of each key must be a list with the text and
198 src respectively. e.g.:
199 {
200 "text": ["text1", "text2"],
201 "image": ["src1", "src2"],
202 }
203
204 3. Passing a dictionary to `xml_data` will create one of three types of
205 notifications depending on the dictionary data (toast, tile, badge).
206 See `dict_to_xml_schema` docs for more information on dictionary formatting.
207
208 4. Passing a value to `raw_data` will create a `raw` notification and send the
209 input data as is.
210
211 :param uri: str: The device's unique notification uri.
212 :param message: str|dict: The notification data to be sent.
213 :param xml_data: dict: A dictionary containing data to be converted to an xml tree.
214 :param raw_data: str: Data to be sent via a `raw` notification.
215 """
216 # Create a simple toast notification
217 if message:
218 wns_type = "wns/toast"
219 if isinstance(message, str):
220 message = {
221 "text": [message, ],
222 }
223 prepared_data = _wns_prepare_toast(data=message, **kwargs)
224 # Create a toast/tile/badge notification from a dictionary
225 elif xml_data:
226 xml = dict_to_xml_schema(xml_data)
227 wns_type = "wns/%s" % xml.tag
228 prepared_data = ET.tostring(xml)
229 # Create a raw notification
230 elif raw_data:
231 wns_type = "wns/raw"
232 prepared_data = raw_data
233 else:
234 raise TypeError(
235 "At least one of the following parameters must be set:"
236 "`message`, `xml_data`, `raw_data`"
237 )
238
239 return _wns_send(
240 uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id
241 )
242
243
244 def wns_send_bulk_message(
245 uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
246 ):
247 """
248 WNS doesn't support bulk notification, so we loop through each uri.
249
250 :param uri_list: list: A list of uris the notification will be sent to.
251 :param message: str: The notification data to be sent.
252 :param xml_data: dict: A dictionary containing data to be converted to an xml tree.
253 :param raw_data: str: Data to be sent via a `raw` notification.
254 """
255 res = []
256 if uri_list:
257 for uri in uri_list:
258 r = wns_send_message(
259 uri=uri, message=message, xml_data=xml_data,
260 raw_data=raw_data, application_id=application_id, **kwargs
261 )
262 res.append(r)
263 return res
264
265
266 def dict_to_xml_schema(data):
267 """
268 Input a dictionary to be converted to xml. There should be only one key at
269 the top level. The value must be a dict with (required) `children` key and
270 (optional) `attrs` key. This will be called the `sub-element dictionary`.
271
272 The `attrs` value must be a dictionary; each value will be added to the
273 element's xml tag as attributes. e.g.:
274 {"example": {
275 "attrs": {
276 "key1": "value1",
277 ...
278 },
279 ...
280 }}
281
282 would result in:
283 <example key1="value1" key2="value2"></example>
284
285 If the value is a dict it must contain one or more keys which will be used
286 as the sub-element names. Each sub-element must have a value of a sub-element
287 dictionary(see above) or a list of sub-element dictionaries.
288 If the value is not a dict, it will be the value of the element.
289 If the value is a list, multiple elements of the same tag will be created
290 from each sub-element dict in the list.
291
292 :param data: dict: Used to create an XML tree. e.g.:
293 example_data = {
294 "toast": {
295 "attrs": {
296 "launch": "param",
297 "duration": "short",
298 },
299 "children": {
300 "visual": {
301 "children": {
302 "binding": {
303 "attrs": {"template": "ToastText01"},
304 "children": {
305 "text": [
306 {
307 "attrs": {"id": "1"},
308 "children": "text1",
309 },
310 {
311 "attrs": {"id": "2"},
312 "children": "text2",
313 },
314 ],
315 },
316 },
317 },
318 },
319 },
320 },
321 }
322 :return: ElementTree.Element
323 """
324 for key, value in data.items():
325 root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
326 children = value.get("children", None)
327 if isinstance(children, dict):
328 _add_sub_elements_from_dict(root, children)
329 return root
330
331
332 def _add_sub_elements_from_dict(parent, sub_dict):
333 """
334 Add SubElements to the parent element.
335
336 :param parent: ElementTree.Element: The parent element for the newly created SubElement.
337 :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
338 method docstring for more information. e.g.:
339 {"example": {
340 "attrs": {
341 "key1": "value1",
342 ...
343 },
344 ...
345 }}
346 """
347 for key, value in sub_dict.items():
348 if isinstance(value, list):
349 for repeated_element in value:
350 sub_element = ET.SubElement(parent, key)
351 _add_element_attrs(sub_element, repeated_element.get("attrs", {}))
352 children = repeated_element.get("children", None)
353 if isinstance(children, dict):
354 _add_sub_elements_from_dict(sub_element, children)
355 elif isinstance(children, str):
356 sub_element.text = children
357 else:
358 sub_element = ET.SubElement(parent, key)
359 _add_element_attrs(sub_element, value.get("attrs", {}))
360 children = value.get("children", None)
361 if isinstance(children, dict):
362 _add_sub_elements_from_dict(sub_element, children)
363 elif isinstance(children, str):
364 sub_element.text = children
365
366
367 def _add_element_attrs(elem, attrs):
368 """
369 Add attributes to the given element.
370
371 :param elem: ElementTree.Element: The element the attributes are being added to.
372 :param attrs: dict: A dictionary of attributes. e.g.:
373 {"attribute1": "value", "attribute2": "another"}
374 :return: ElementTree.Element
375 """
376 for attr, value in attrs.items():
377 elem.attrib[attr] = value
378 return elem