forked from enthusiastmartin/flask-pyfcm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask_pyfcm.py
97 lines (80 loc) · 2.93 KB
/
flask_pyfcm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from flask import current_app
from pyfcm import FCMNotification
# Find the stack on which we want to store PyFCM client.
# Starting with Flask 0.9, the _app_ctx_stack is the correct one,
# before that we need to use the _request_ctx_stack.
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
class NotificationBuilder(object):
def __init__(self):
pass
def build(self):
pass
def message_title(self, title):
pass
def message_body(self, body):
pass
def message_icon(self, icon):
pass
def message_sound(self, sound):
pass
class FCM(object):
FCM_INVALID_ID_ERRORS = [
'InvalidRegistration',
'NotRegistered',
'MismatchSenderId'
]
def __init__(self, app=None):
self.app = app
self._failure_handler = None
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault("FCM_API_KEY", "")
app.config.setdefault("FCM_PROXY_DICT", None)
@property
def push_service(self):
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'fcm_service'):
ctx.fcm_service = FCMNotification(
api_key=current_app.config['FCM_API_KEY'],
proxy_dict=current_app.config['FCM_PROXY_DICT']
)
return ctx.fcm_service
def notify_single_device(self, registration_id, *args, **kwargs):
return self.notify_multiple_devices([registration_id], **kwargs)
def notify_multiple_devices(self, registration_ids, **kwargs):
response = self.push_service.notify_multiple_devices(registration_ids,
**kwargs)
self.check_for_failures(registration_ids, response)
return response
def check_for_failures(self, registration_ids, response):
try:
if len(response) > 0:
id_and_responses = zip(registration_ids,
response.get('results'))
filtered = filter(
lambda x: x[1].get('error') in self.FCM_INVALID_ID_ERRORS,
id_and_responses
)
invalid_messages = dict(filtered)
invalid_ids = list(invalid_messages.keys())
if self._failure_handler:
self._failure_handler(invalid_ids, invalid_messages)
except:
pass
def failure_handler(self, f):
"""Register a handler for getting bad ids.
fcm = FcM()
fcm.push_service.
This decorator is not required::
@fcm.failure_handler
def handle_bad_ids(ids, *args):
for device in Device.query.filter(id.in(ids)):
device.mark_as_inactive()
"""
self._failure_handler = f
return f