Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[master] Add FCM - Google Firebase #55

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions config.ini
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ apns_batch_size = 500

apns_topic = <YOUR TOPIC HERE>
apns_certificate_path = <ABSOLUTE-PATH-TO-APN-CERTIFICATE-HERE>
gcm_access_key = <YOUR-GCM-KEY-HERE>

google_application_credentials = <PATH_FCM_APPLICATION_CREDENTIAL.JSON>
# for future use
apns_sandbox = false
connection_error_retries = 3
Expand All @@ -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
Expand Down
21 changes: 11 additions & 10 deletions pushkin/sender/nordifier/apns2_push_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -66,33 +66,34 @@ 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__))

def send_batch(self):
while len(self.queue):
self.send(self.queue.pop())

11 changes: 4 additions & 7 deletions pushkin/sender/nordifier/apns_push_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -82,16 +80,16 @@ 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

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'],
Expand All @@ -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'],
Expand All @@ -122,4 +120,3 @@ def send_batch(self):

# batch (frame) prepared, send it
self.apns.gateway_server.send_notification_multiple(frame)

56 changes: 56 additions & 0 deletions pushkin/sender/nordifier/fcm.py
Original file line number Diff line number Diff line change
@@ -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
78 changes: 78 additions & 0 deletions pushkin/sender/nordifier/fcm_push_sender.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 4 additions & 2 deletions pushkin/sender/nordifier/sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -33,4 +32,7 @@ def send(self, notification):
raise Exception('Not implemented')

def send_batch(self):
raise Exception('Not implemented')
raise Exception('Not implemented')

def create_message(self, notification):
raise Exception('Not implemented')
Loading