diff --git a/config.ini b/config.ini index cd075ef..dcd9ed2 100644 --- a/config.ini +++ b/config.ini @@ -17,8 +17,7 @@ apns_batch_size = 500 apns_topic = apns_certificate_path = -gcm_access_key = - +google_application_credentials = # for future use apns_sandbox = false connection_error_retries = 3 @@ -38,8 +37,8 @@ request_processor_num_threads = 10 sender_queue_limit = 50000 enabled_senders = - pushkin.sender.senders.ApnNotificationSender {"workers": 50} - pushkin.sender.senders.GcmNotificationSender {"workers": 50} + pushkin.sender.senders.ApnNotificationSender {"workers": 50} + pushkin.sender.senders.FcmNotificationSender {"workers": 50} [Log] # log configuration diff --git a/pushkin/sender/nordifier/apns2_push_sender.py b/pushkin/sender/nordifier/apns2_push_sender.py index cd90586..a4d193f 100644 --- a/pushkin/sender/nordifier/apns2_push_sender.py +++ b/pushkin/sender/nordifier/apns2_push_sender.py @@ -39,7 +39,7 @@ def pop_unregistered_devices(self): self.unregistered_devices = [] return items - def prepare_data(self, notification): + def create_message(self, notification): def to_timestamp(dt, epoch=datetime(1970, 1, 1)): # http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python td = dt - epoch @@ -66,28 +66,30 @@ def to_timestamp(dt, epoch=datetime(1970, 1, 1)): 'identifier': notification['sending_id'], 'expiry': expiry_utc_ts_seconds, 'priority': 10, + 'payload': Payload(alert=notification['content'], badge=1, sound='default', custom=custom) } - result['payload'] = Payload(alert=notification['content'], badge=1, sound='default', custom=custom) return result - def send(self, notification): - data = self.prepare_data(notification) + data = self.create_message(notification) if data is not None: for i in xrange(self.connection_error_retries): try: - self.apn.send_notification(data['token'], data['payload'], expiration=data['expiry'], topic=self.topic) + self.apn.send_notification(data['token'], + data['payload'], + expiration=data['expiry'], + topic=self.topic) notification['status'] = const.NOTIFICATION_SUCCESS - break #We did it, time to break free! + break # We did it, time to break free! except APNsException as e: if isinstance(e, Unregistered): notification['status'] = const.NOTIFICATION_APNS_DEVICE_UNREGISTERED unregistered_data = { - 'login_id': notification['login_id'], - 'device_token': notification['receiver_id'], - } + 'login_id': notification['login_id'], + 'device_token': notification['receiver_id'], + } self.unregistered_devices.append(unregistered_data) else: self.log.warning('APN got exception {}'.format(type(e).__name__)) @@ -95,4 +97,3 @@ def send(self, notification): def send_batch(self): while len(self.queue): self.send(self.queue.pop()) - diff --git a/pushkin/sender/nordifier/apns_push_sender.py b/pushkin/sender/nordifier/apns_push_sender.py index cef4948..570271d 100644 --- a/pushkin/sender/nordifier/apns_push_sender.py +++ b/pushkin/sender/nordifier/apns_push_sender.py @@ -55,11 +55,9 @@ def process_failed_notification(self, notification_ids_list): notif = self.sent_queue[id] notif['status'] = const.NOTIFICATION_CONNECTION_ERROR - def prepare_data(self, notification): + def create_message(self, notification): def totimestamp(dt, epoch=datetime(1970, 1, 1)): - # http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python td = dt - epoch - # return td.total_seconds() # Python 2.7 return (td.microseconds + (td.seconds + td.days * 86400) * 10 ** 6) / 10 ** 6 expiry_seconds = (notification['time_to_live_ts_bigint'] - int(round(time.time() * 1000))) / 1000 @@ -82,8 +80,8 @@ def totimestamp(dt, epoch=datetime(1970, 1, 1)): 'identifier': notification['sending_id'], 'expiry': expiry_utc_ts_seconds, 'priority': 10, + 'payload': Payload(alert=notification['content'], badge=1, sound='default', custom=custom) } - result['payload'] = Payload(alert=notification['content'], badge=1, sound='default', custom=custom) return result @@ -91,7 +89,7 @@ def send(self, notification): notification['status'] = const.NOTIFICATION_SUCCESS self.sent_queue[notification['sending_id']] = notification - data = self.prepare_data(notification) + data = self.create_message(notification) if data: self.apns.gateway_server.send_notification( token_hex=data['token'], @@ -110,7 +108,7 @@ def send_batch(self): notification['status'] = const.NOTIFICATION_SUCCESS self.sent_queue[notification['sending_id']] = notification - data = self.prepare_data(notification) + data = self.create_message(notification) if data: frame.add_item( token_hex=data['token'], @@ -122,4 +120,3 @@ def send_batch(self): # batch (frame) prepared, send it self.apns.gateway_server.send_notification_multiple(frame) - diff --git a/pushkin/sender/nordifier/fcm.py b/pushkin/sender/nordifier/fcm.py new file mode 100644 index 0000000..f29c8e9 --- /dev/null +++ b/pushkin/sender/nordifier/fcm.py @@ -0,0 +1,56 @@ +''' +The MIT License (MIT) + +Copyright (c) 2012 Minh Nam Ngo. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +''' +import firebase_admin +from firebase_admin import credentials, messaging + +FCM_URL = 'https://fcm.googleapis.com/fcm/send' + + +class FCMException(Exception): + pass + + +class FCMInvalidMessageException(FCMException): + pass + + +class FCMTooManyRegIdsException(FCMException): + pass + + +def generate_fcm_app(service_account_file): + cred = credentials.Certificate(service_account_file) + default_app = firebase_admin.initialize_app(cred) + return default_app + + +class FCM(object): + def __init__(self, app): + """ app : FCM app + """ + self.app = app + + def send(self, data, dry_run=False): + try: + response = messaging.send(data, dry_run=dry_run, app=self.app) + except messaging.ApiCallError as e: + raise FCMException(e) + except Exception as e: + raise FCMInvalidMessageException(e) + return response + + def send_batch(self, data, dry_run=False): + response = messaging.send_all(data, dry_run=dry_run, app=self.app) + if response.failure_count > 0: + raise FCMTooManyRegIdsException("Many reg id is failed %s", + ",".join(response.responses["failed_registration_ids"])) + return response diff --git a/pushkin/sender/nordifier/fcm_push_sender.py b/pushkin/sender/nordifier/fcm_push_sender.py new file mode 100644 index 0000000..a15ff96 --- /dev/null +++ b/pushkin/sender/nordifier/fcm_push_sender.py @@ -0,0 +1,78 @@ +''' +The MIT License (MIT) +Copyright (c) 2016 Nordeus LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +''' +import time +from sender import Sender +import constants as const +from fcm import FCM, generate_fcm_app +from firebase_admin import messaging + + +class FCMPushSender(Sender): + """ + FCM Push Sender uses python-FCM module: https://github.com/geeknam/python-FCM + FCM documentation: https://developer.android.com/google/FCM/FCM.html + """ + + def __init__(self, config, log): + Sender.__init__(self, config, log) + self.base_deeplink_url = config.get('Messenger', 'base_deeplink_url') + app = generate_fcm_app(config.get('Messenger', 'google_application_credentials')) + self.FCM = FCM(app) + self.canonical_ids = [] + self.unregistered_devices = [] + + def pop_canonical_ids(self): + items = self.canonical_ids + self.canonical_ids = [] + return items + + def pop_unregistered_devices(self): + items = self.unregistered_devices + self.unregistered_devices = [] + return items + + def create_message(self, notification): + expiry_seconds = (notification['time_to_live_ts_bigint'] - int(round(time.time() * 1000))) / 1000 + if expiry_seconds < 0: + self.log.warning( + 'FCM: expired notification with sending_id: {0}; expiry_seconds: {1}'.format(notification['sending_id'], + expiry_seconds)) + notification['status'] = const.NOTIFICATION_EXPIRED + return + + utm_source = 'pushnotification' + utm_campaign = str(notification['campaign_id']) + utm_medium = str(notification['message_id']) + data = { + 'title': notification['title'], + 'message': notification['content'], + 'url': self.base_deeplink_url + '://' + notification['screen'] + + '?utm_source=' + utm_source + '&utm_campaign=' + utm_campaign + '&utm_medium=' + utm_medium, + 'notifid': notification['campaign_id'], + } + msg = messaging.Message( + data=data, + token=notification['receiver_id'], + ) + return msg + + def send(self, notification): + dry_run = 'dry_run' in notification and notification['dry_run'] == True + message = self.create_message(notification) + response = self.FCM.send(message, dry_run) + + return response + + def send_batch(self): + messages = [] + while len(self.queue): + messages.append(self.create_message(self.queue.pop())) + return self.FCM.send_batch(messages) diff --git a/pushkin/sender/nordifier/sender.py b/pushkin/sender/nordifier/sender.py index a2f1ff8..bb46c61 100644 --- a/pushkin/sender/nordifier/sender.py +++ b/pushkin/sender/nordifier/sender.py @@ -8,7 +8,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' -import time class Sender: @@ -33,4 +32,7 @@ def send(self, notification): raise Exception('Not implemented') def send_batch(self): - raise Exception('Not implemented') \ No newline at end of file + raise Exception('Not implemented') + + def create_message(self, notification): + raise Exception('Not implemented') diff --git a/pushkin/sender/senders.py b/pushkin/sender/senders.py index 6c4afda..b97228f 100644 --- a/pushkin/sender/senders.py +++ b/pushkin/sender/senders.py @@ -8,16 +8,14 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' -from Queue import Empty from threading import Thread -import time import logging import multiprocessing from pushkin.database import database -from pushkin.sender.nordifier.apns_push_sender import APNsPushSender from pushkin.sender.nordifier.gcm_push_sender import GCMPushSender from pushkin.sender.nordifier.apns2_push_sender import APNS2PushSender +from pushkin.sender.nordifier.fcm_push_sender import FCMPushSender from pushkin.util.pool import ProcessPool from pushkin import config, context from pushkin.sender.nordifier import constants @@ -25,7 +23,6 @@ class NotificationSender(ProcessPool): - NUM_WORKERS_DEFAULT = 50 def __init__(self, **kwargs): @@ -51,12 +48,15 @@ def log_notifications(self, notifications): except: main_logger.exception("Error while logging notification to csv log!") + class NotificationOperation(): - '''Represents operation which should be executed outside of process pool''' + """Represents operation which should be executed outside of process pool""" + def __init__(self, operation, data): self.operation = operation self.data = data + class NotificationPostProcessor(Thread): UPDATE_CANONICALS = 1 UPDATE_UNREGISTERED_DEVICES = 2 @@ -84,11 +84,13 @@ def run(self): elif record.operation == NotificationPostProcessor.UPDATE_UNREGISTERED_DEVICES: self.update_unregistered_devices(record.data) else: - context.main_logger.error("NotificationPostProcessor - unknown operation: {operation}".format(operation=record.operation)) + context.main_logger.error( + "NotificationPostProcessor - unknown operation: {operation}".format(operation=record.operation)) except: context.main_logger.exception("Exception while post processing notification.") pass + class NotificationStatistics: def __init__(self, name, logger, last_averages=100, log_time_seconds=30): self.name = name @@ -108,13 +110,12 @@ def stop(self): self.running_average += elapsed / self.last_averages elapsed_since_log = timeit.default_timer() - self.last_time_logged if elapsed_since_log > self.log_time_seconds: - self.logger.info('Average time for sending push for {name} is {avg}'.format(name=self.name, avg=self.running_average)) + self.logger.info( + 'Average time for sending push for {name} is {avg}'.format(name=self.name, avg=self.running_average)) self.last_time_logged = timeit.default_timer() - class ApnNotificationSender(NotificationSender): - PLATFORMS = (constants.PLATFORM_IPHONE, constants.PLATFORM_IPAD) @@ -129,7 +130,9 @@ def process(self): statistics.stop() unregistered_devices = sender.pop_unregistered_devices() if len(unregistered_devices) > 0: - NotificationPostProcessor.OPERATION_QUEUE.put(NotificationOperation(NotificationPostProcessor.UPDATE_UNREGISTERED_DEVICES, unregistered_devices)) + NotificationPostProcessor.OPERATION_QUEUE.put( + NotificationOperation(NotificationPostProcessor.UPDATE_UNREGISTERED_DEVICES, + unregistered_devices)) except Exception: context.main_logger.exception("ApnNotificationProcessor failed to send notifications") finally: @@ -137,7 +140,6 @@ def process(self): class GcmNotificationSender(NotificationSender): - PLATFORMS = (constants.PLATFORM_ANDROID, constants.PLATFORM_ANDROID_TABLET) @@ -152,10 +154,43 @@ def process(self): statistics.stop() canonical_ids = sender.pop_canonical_ids() if len(canonical_ids) > 0: - NotificationPostProcessor.OPERATION_QUEUE.put(NotificationOperation(NotificationPostProcessor.UPDATE_CANONICALS, canonical_ids)) + NotificationPostProcessor.OPERATION_QUEUE.put( + NotificationOperation(NotificationPostProcessor.UPDATE_CANONICALS, canonical_ids)) + unregistered_devices = sender.pop_unregistered_devices() + if len(unregistered_devices) > 0: + NotificationPostProcessor.OPERATION_QUEUE.put( + NotificationOperation(NotificationPostProcessor.UPDATE_UNREGISTERED_DEVICES, + unregistered_devices)) + except Exception: + context.main_logger.exception("GcmNotificationProcessor failed to send notifications") + finally: + self.log_notifications([notification]) + + +class FcmNotificationSender(NotificationSender): + PLATFORMS = (constants.PLATFORM_ANDROID, + constants.PLATFORM_ANDROID_TABLET, + constants.PLATFORM_IPAD, + constants.PLATFORM_IPHONE) + + def process(self): + sender = FCMPushSender(config.config, context.main_logger) + statistics = NotificationStatistics('FCM', context.main_logger) + while True: + notification = self.task_queue.get() + try: + statistics.start() + sender.send_in_batch(notification) + statistics.stop() + canonical_ids = sender.pop_canonical_ids() + if len(canonical_ids) > 0: + NotificationPostProcessor.OPERATION_QUEUE.put( + NotificationOperation(NotificationPostProcessor.UPDATE_CANONICALS, canonical_ids)) unregistered_devices = sender.pop_unregistered_devices() if len(unregistered_devices) > 0: - NotificationPostProcessor.OPERATION_QUEUE.put(NotificationOperation(NotificationPostProcessor.UPDATE_UNREGISTERED_DEVICES, unregistered_devices)) + NotificationPostProcessor.OPERATION_QUEUE.put( + NotificationOperation(NotificationPostProcessor.UPDATE_UNREGISTERED_DEVICES, + unregistered_devices)) except Exception: context.main_logger.exception("GcmNotificationProcessor failed to send notifications") finally: