Debian Codegraph @

push_notifications/apns.py

raw
1 """
2 Apple Push Notification Service
3 Documentation is available on the iOS Developer Library:
4 https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
5 """
6
7 import time
8
9 from apns2 import client as apns2_client
10 from apns2 import errors as apns2_errors
11 from apns2 import payload as apns2_payload
12
13 from . import models
14 from . import NotificationError
15 from .apns_errors import reason_for_exception_class
16 from .conf import get_manager
17
18
19 class APNSError(NotificationError):
20 pass
21
22
23 class APNSUnsupportedPriority(APNSError):
24 pass
25
26
27 class APNSServerError(APNSError):
28 def __init__(self, status):
29 super(APNSServerError, self).__init__(status)
30 self.status = status
31
32
33 def _apns_create_socket(certfile=None, application_id=None):
34 certfile = certfile or get_manager().get_apns_certificate(application_id)
35 client = apns2_client.APNsClient(
36 certfile,
37 use_sandbox=get_manager().get_apns_use_sandbox(application_id),
38 use_alternative_port=get_manager().get_apns_use_alternative_port(application_id)
39 )
40 client.connect()
41 return client
42
43
44 def _apns_prepare(
45 token, alert, application_id=None, badge=None, sound=None, category=None,
46 content_available=False, action_loc_key=None, loc_key=None, loc_args=[],
47 extra={}, mutable_content=False, thread_id=None, url_args=None):
48 if action_loc_key or loc_key or loc_args:
49 apns2_alert = apns2_payload.PayloadAlert(
50 body=alert if alert else {}, body_localized_key=loc_key,
51 body_localized_args=loc_args, action_localized_key=action_loc_key)
52 else:
53 apns2_alert = alert
54
55 if callable(badge):
56 badge = badge(token)
57
58 return apns2_payload.Payload(
59 apns2_alert, badge, sound, content_available, mutable_content, category,
60 url_args, custom=extra, thread_id=thread_id)
61
62
63 def _apns_send(
64 registration_id, alert, batch=False, application_id=None, certfile=None, **kwargs
65 ):
66 client = _apns_create_socket(certfile=certfile, application_id=application_id)
67
68 notification_kwargs = {}
69
70 # if expiration isn"t specified use 1 month from now
71 notification_kwargs["expiration"] = kwargs.pop("expiration", None)
72 if not notification_kwargs["expiration"]:
73 notification_kwargs["expiration"] = int(time.time()) + 2592000
74
75 priority = kwargs.pop("priority", None)
76 if priority:
77 try:
78 notification_kwargs["priority"] = apns2_client.NotificationPriority(str(priority))
79 except ValueError:
80 raise APNSUnsupportedPriority("Unsupported priority %d" % (priority))
81
82 if batch:
83 data = [apns2_client.Notification(
84 token=rid, payload=_apns_prepare(rid, alert, **kwargs)) for rid in registration_id]
85 return client.send_notification_batch(
86 data, get_manager().get_apns_topic(application_id=application_id),
87 **notification_kwargs
88 )
89
90 data = _apns_prepare(registration_id, alert, **kwargs)
91 client.send_notification(
92 registration_id, data,
93 get_manager().get_apns_topic(application_id=application_id),
94 **notification_kwargs
95 )
96
97
98 def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs):
99 """
100 Sends an APNS notification to a single registration_id.
101 This will send the notification as form data.
102 If sending multiple notifications, it is more efficient to use
103 apns_send_bulk_message()
104
105 Note that if set alert should always be a string. If it is not set,
106 it won"t be included in the notification. You will need to pass None
107 to this for silent notifications.
108 """
109
110 try:
111 _apns_send(
112 registration_id, alert, application_id=application_id,
113 certfile=certfile, **kwargs
114 )
115 except apns2_errors.APNsException as apns2_exception:
116 if isinstance(apns2_exception, apns2_errors.Unregistered):
117 device = models.APNSDevice.objects.get(registration_id=registration_id)
118 device.active = False
119 device.save()
120 raise APNSServerError(status=reason_for_exception_class(apns2_exception.__class__))
121
122
123 def apns_send_bulk_message(
124 registration_ids, alert, application_id=None, certfile=None, **kwargs
125 ):
126 """
127 Sends an APNS notification to one or more registration_ids.
128 The registration_ids argument needs to be a list.
129
130 Note that if set alert should always be a string. If it is not set,
131 it won"t be included in the notification. You will need to pass None
132 to this for silent notifications.
133 """
134
135 results = _apns_send(
136 registration_ids, alert, batch=True, application_id=application_id,
137 certfile=certfile, **kwargs
138 )
139 inactive_tokens = [token for token, result in results.items() if result == "Unregistered"]
140 models.APNSDevice.objects.filter(registration_id__in=inactive_tokens).update(active=False)
141 return results