Debian Codegraph @

push_notifications/conf/app.py

raw
1 from django.core.exceptions import ImproperlyConfigured
2 from django.utils.six import string_types
3 from .base import BaseConfig, check_apns_certificate
4 from ..settings import PUSH_NOTIFICATIONS_SETTINGS as SETTINGS
5
6 SETTING_MISMATCH = (
7 "Application '{application_id}' ({platform}) does not support the setting '{setting}'."
8 )
9
10
11 # code can be "missing" or "invalid"
12 BAD_PLATFORM = (
13 "PUSH_NOTIFICATIONS_SETTINGS.APPLICATIONS['{application_id}']['PLATFORM']"
14 " is {code}. Must be one of: {platforms}."
15 )
16
17 UNKNOWN_PLATFORM = (
18 "Unknown Platform: {platform}. Must be one of: {platforms}."
19 )
20
21 MISSING_SETTING = (
22 "PUSH_NOTIFICATIONS_SETTINGS.APPLICATIONS['{application_id}']['{setting}'] is missing."
23 )
24
25 PLATFORMS = [
26 "APNS",
27 "FCM",
28 "GCM",
29 "WNS",
30 "WP"
31 ]
32
33 # Settings that all applications must have
34 REQUIRED_SETTINGS = [
35 "PLATFORM",
36 ]
37
38 # Settings that an application may have to enable optional features
39 # these settings are stubs for registry support and have no effect on the operation
40 # of the application at this time.
41 OPTIONAL_SETTINGS = [
42 "APPLICATION_GROUP",
43 "APPLICATION_SECRET",
44 ]
45
46 APNS_REQUIRED_SETTINGS = ["CERTIFICATE"]
47
48 APNS_OPTIONAL_SETTINGS = [
49 "USE_SANDBOX", "USE_ALTERNATIVE_PORT", "TOPIC"
50 ]
51
52 FCM_REQUIRED_SETTINGS = GCM_REQUIRED_SETTINGS = ["API_KEY"]
53 FCM_OPTIONAL_SETTINGS = GCM_OPTIONAL_SETTINGS = [
54 "POST_URL", "MAX_RECIPIENTS", "ERROR_TIMEOUT"
55 ]
56
57 WNS_REQUIRED_SETTINGS = ["PACKAGE_SECURITY_ID", "SECRET_KEY"]
58
59 WNS_OPTIONAL_SETTINGS = ["WNS_ACCESS_URL"]
60
61 WP_REQUIRED_SETTINGS = ["PRIVATE_KEY", "CLAIMS"]
62
63 WP_OPTIONAL_SETTINGS = ["ERROR_TIMEOUT", "POST_URL"]
64
65
66 class AppConfig(BaseConfig):
67 """Supports any number of push notification enabled applications."""
68
69 def __init__(self, settings=None):
70 # supports overriding the settings to be loaded. Will load from ..settings by default.
71 self._settings = settings or SETTINGS
72
73 # initialize APPLICATIONS to an empty collection
74 self._settings.setdefault("APPLICATIONS", {})
75
76 # validate application configurations
77 self._validate_applications(self._settings["APPLICATIONS"])
78
79 def _validate_applications(self, apps):
80 """Validate the application collection"""
81 for application_id, application_config in apps.items():
82 self._validate_config(application_id, application_config)
83
84 application_config["APPLICATION_ID"] = application_id
85
86 def _validate_config(self, application_id, application_config):
87 platform = application_config.get("PLATFORM", None)
88
89 # platform is not present
90 if platform is None:
91 raise ImproperlyConfigured(
92 BAD_PLATFORM.format(
93 application_id=application_id,
94 code="required",
95 platforms=", ".join(PLATFORMS)
96 )
97 )
98
99 # platform is not a valid choice from PLATFORMS
100 if platform not in PLATFORMS:
101 raise ImproperlyConfigured(
102 BAD_PLATFORM.format(
103 application_id=application_id,
104 code="invalid",
105 platforms=", ".join(PLATFORMS)
106 )
107 )
108
109 validate_fn = "_validate_{platform}_config".format(platform=platform).lower()
110
111 if hasattr(self, validate_fn):
112 getattr(self, validate_fn)(application_id, application_config)
113 else:
114 raise ImproperlyConfigured(
115 UNKNOWN_PLATFORM.format(
116 platform=platform,
117 platforms=", ".join(PLATFORMS)
118 )
119 )
120
121 def _validate_apns_config(self, application_id, application_config):
122 allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + APNS_REQUIRED_SETTINGS + \
123 APNS_OPTIONAL_SETTINGS
124
125 self._validate_allowed_settings(application_id, application_config, allowed)
126 self._validate_required_settings(
127 application_id, application_config, APNS_REQUIRED_SETTINGS
128 )
129
130 # determine/set optional values
131 application_config.setdefault("USE_SANDBOX", False)
132 application_config.setdefault("USE_ALTERNATIVE_PORT", False)
133 application_config.setdefault("TOPIC", None)
134
135 self._validate_apns_certificate(application_config["CERTIFICATE"])
136
137 def _validate_apns_certificate(self, certfile):
138 """Validate the APNS certificate at startup."""
139
140 try:
141 with open(certfile, "r") as f:
142 content = f.read()
143 check_apns_certificate(content)
144 except Exception as e:
145 msg = "The APNS certificate file at %r is not readable: %s" % (certfile, e)
146 raise ImproperlyConfigured(msg)
147
148 def _validate_fcm_config(self, application_id, application_config):
149 allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + FCM_REQUIRED_SETTINGS + \
150 FCM_OPTIONAL_SETTINGS
151
152 self._validate_allowed_settings(application_id, application_config, allowed)
153 self._validate_required_settings(
154 application_id, application_config, FCM_REQUIRED_SETTINGS
155 )
156
157 application_config.setdefault("POST_URL", "https://fcm.googleapis.com/fcm/send")
158 application_config.setdefault("MAX_RECIPIENTS", 1000)
159 application_config.setdefault("ERROR_TIMEOUT", None)
160
161 def _validate_gcm_config(self, application_id, application_config):
162 allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + GCM_REQUIRED_SETTINGS + \
163 GCM_OPTIONAL_SETTINGS
164
165 self._validate_allowed_settings(application_id, application_config, allowed)
166 self._validate_required_settings(
167 application_id, application_config, GCM_REQUIRED_SETTINGS
168 )
169
170 application_config.setdefault("POST_URL", "https://android.googleapis.com/gcm/send")
171 application_config.setdefault("MAX_RECIPIENTS", 1000)
172 application_config.setdefault("ERROR_TIMEOUT", None)
173
174 def _validate_wns_config(self, application_id, application_config):
175 allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WNS_REQUIRED_SETTINGS + \
176 WNS_OPTIONAL_SETTINGS
177
178 self._validate_allowed_settings(application_id, application_config, allowed)
179 self._validate_required_settings(
180 application_id, application_config, WNS_REQUIRED_SETTINGS
181 )
182
183 application_config.setdefault("WNS_ACCESS_URL", "https://login.live.com/accesstoken.srf")
184
185 def _validate_wp_config(self, application_id, application_config):
186 allowed = REQUIRED_SETTINGS + OPTIONAL_SETTINGS + WP_REQUIRED_SETTINGS + \
187 WP_OPTIONAL_SETTINGS
188
189 self._validate_allowed_settings(application_id, application_config, allowed)
190 self._validate_required_settings(
191 application_id, application_config, WP_REQUIRED_SETTINGS
192 )
193 application_config.setdefault("POST_URL", {
194 "CHROME": 'https://fcm.googleapis.com/fcm/send',
195 "OPERA": 'https://fcm.googleapis.com/fcm/send',
196 "FIREFOX": 'https://updates.push.services.mozilla.com/wpush/v2'
197 })
198
199
200 def _validate_allowed_settings(self, application_id, application_config, allowed_settings):
201 """Confirm only allowed settings are present."""
202
203 for setting_key in application_config.keys():
204 if setting_key not in allowed_settings:
205 raise ImproperlyConfigured(
206 "Platform {}, app {} does not support the setting: {}.".format(
207 application_config["PLATFORM"], application_id, setting_key
208 )
209 )
210
211 def _validate_required_settings(
212 self, application_id, application_config, required_settings
213 ):
214 """All required keys must be present"""
215
216 for setting_key in required_settings:
217 if setting_key not in application_config.keys():
218 raise ImproperlyConfigured(
219 MISSING_SETTING.format(
220 application_id=application_id, setting=setting_key
221 )
222 )
223
224 def _get_application_settings(self, application_id, platform, settings_key):
225 """Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting
226 value or dies trying"""
227
228 if not application_id:
229 conf_cls = "push_notifications.conf.AppConfig"
230 raise ImproperlyConfigured(
231 "{} requires the application_id be specified at all times.".format(conf_cls)
232 )
233
234 # verify that the application config exists
235 app_config = self._settings.get("APPLICATIONS").get(application_id, None)
236 if app_config is None:
237 raise ImproperlyConfigured(
238 "No application configured with application_id: {}.".format(application_id)
239 )
240
241 # fetch a setting for the incorrect type of platform
242 if app_config.get("PLATFORM") != platform:
243 raise ImproperlyConfigured(
244 SETTING_MISMATCH.format(
245 application_id=application_id,
246 platform=app_config.get("PLATFORM"),
247 setting=settings_key
248 )
249 )
250
251 # finally, try to fetch the setting
252 if settings_key not in app_config:
253 raise ImproperlyConfigured(
254 MISSING_SETTING.format(
255 application_id=application_id, setting=settings_key
256 )
257 )
258
259 return app_config.get(settings_key)
260
261 def get_gcm_api_key(self, application_id=None):
262 return self._get_application_settings(application_id, "GCM", "API_KEY")
263
264 def get_fcm_api_key(self, application_id=None):
265 return self._get_application_settings(application_id, "FCM", "API_KEY")
266
267 def get_post_url(self, cloud_type, application_id=None):
268 return self._get_application_settings(application_id, cloud_type, "POST_URL")
269
270 def get_error_timeout(self, cloud_type, application_id=None):
271 return self._get_application_settings(application_id, cloud_type, "ERROR_TIMEOUT")
272
273 def get_max_recipients(self, cloud_type, application_id=None):
274 return self._get_application_settings(application_id, cloud_type, "MAX_RECIPIENTS")
275
276 def get_apns_certificate(self, application_id=None):
277 r = self._get_application_settings(application_id, "APNS", "CERTIFICATE")
278 if not isinstance(r, string_types):
279 # probably the (Django) file, and file path should be got
280 if hasattr(r, "path"):
281 return r.path
282 elif (hasattr(r, "has_key") or hasattr(r, "__contains__")) and "path" in r:
283 return r["path"]
284 else:
285 raise ImproperlyConfigured(
286 "The APNS certificate settings value should be a string, or "
287 "should have a 'path' attribute or key"
288 )
289 return r
290
291 def get_apns_use_sandbox(self, application_id=None):
292 return self._get_application_settings(application_id, "APNS", "USE_SANDBOX")
293
294 def get_apns_use_alternative_port(self, application_id=None):
295 return self._get_application_settings(application_id, "APNS", "USE_ALTERNATIVE_PORT")
296
297 def get_apns_topic(self, application_id=None):
298 return self._get_application_settings(application_id, "APNS", "TOPIC")
299
300 def get_wns_package_security_id(self, application_id=None):
301 return self._get_application_settings(application_id, "WNS", "PACKAGE_SECURITY_ID")
302
303 def get_wns_secret_key(self, application_id=None):
304 return self._get_application_settings(application_id, "WNS", "SECRET_KEY")
305
306 def get_wp_post_url(self, application_id, browser):
307 return self._get_application_settings(application_id, "WP", "POST_URL")[browser]
308
309 def get_wp_private_key(self, application_id=None):
310 return self._get_application_settings(application_id, "WP", "PRIVATE_KEY")
311
312 def get_wp_claims(self, application_id=None):
313 return self._get_application_settings(application_id, "WP", "CLAIMS")