def route_poke(user_id_to): uid = request.headers.get("uid", None) user_from = User.objects(uid=uid).get_or_404() user_to = User.objects(id=user_id_to).get_or_404() alert = alerts_blueprint.create_alert( user_from, user_to, push_type="POKE", message="{nick_name} 님이 당신을 찔렀습니다.".format( nick_name=user_from.nick_name)) push_item = alert.records[-1] data: dict = alerts_blueprint.dictify_push_item(push_item) try: message = messaging.Message( data=data, token=user_to.r_token, apns=messaging.APNSConfig(), android=messaging.AndroidConfig(priority="high"), notification=messaging.Notification()) messaging.send(message) except Exception as e: logging.exception(e) return Response( user_to.to_json(), mimetype="application/json")
def send_notif_multiple(registration_tokens=[], data={}, title="Notification Order", body="hey you, you have some order "): if len(registration_tokens) == 0: return message = messaging.MulticastMessage( # for id user divice tokens=registration_tokens, # for data payload data=data, # notification body notification=messaging.Notification(title=title, body=body), # android notification android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), notification=messaging.AndroidNotification(title=title, body=body, color='#f45342')), # apns apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), ) response = messaging.send_multicast(message, app=firebase) # See the BatchResponse reference documentation # for the contents of response. return '{0} messages were sent successfully'.format(response.success_count)
def send(data: dict, device: str, controller: str, push_temp: float = None): app.logger.info( f'sending data {"with push" if push_temp else "without push"} to device: {device}' ) message = messaging.Message( data={'payload': json.dumps(data)}, token=device, ) if push_temp and not should_throttle_push(device, controller): # don't send another push to this device about this controller for num seconds. set_push_throttle(device, controller, seconds=30) # add push notification to message message.notification = messaging.Notification( title='MeatHeat', body=f'{push_temp}° is outside of the range!', ) message.apns = messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=1, sound='default'), ), ) try: message_id = messaging.send(message) app.logger.info(f'successfully sent {message_id} to device: {device}') except Exception as e: # TODO: should remove device token from redis if the exception is related to it being invalid. app.logger.error( f'error sending push to device: {device} with error: {e}')
def _build_apns_config(self, title_loc_key: str = ''): """ Data for the Apple Push Notification Service see https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging :param title_loc_key: :return: """ return messaging.APNSConfig( # headers={ # 'apns-priority': '10' # }, payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( # This is a localized key that iOS will search in # the safe iOS app to show as a default title title="New Activity", body="New Activity with your Safe", # title_loc_key=title_loc_key, ), # Means the content of the notification will be # modified by the safe app. # Depending on the 'type' custom field, # 'alert.title' and 'alert.body' above will be # different mutable_content=True, badge=1, sound='default', ), ), )
def route_update_registration_token(device_token: str): """Endpoint for updating user registration token.""" uid = request.headers.get("uid", None) user = User.objects.get_or_404(uid=uid) existing_device_token = user.device_token new_device_token = device_token is_update_required = existing_device_token != new_device_token if is_update_required: user.device_token = new_device_token user.save() if is_update_required and existing_device_token is not None: try: message = messaging.Message( data=dict(event=Alarm.Event.LOG_OUT), token=existing_device_token, apns=messaging.APNSConfig(), android=messaging.AndroidConfig(priority="high"), notification=messaging.Notification() ) messaging.send(message) except Exception as e: logging.exception(e) response = encode(user.to_mongo()) return Response(response, mimetype="application/json")
def test_aps_alert(self): msg = messaging.Message( topic='topic', apns=messaging.APNSConfig( payload=messaging.APNSPayload(aps=messaging.Aps( alert=messaging.ApsAlert(title='t', body='b', title_loc_key='tlk', title_loc_args=['t1', 't2'], loc_key='lk', loc_args=['l1', 'l2'], action_loc_key='alk', launch_image='li')), ))) expected = { 'topic': 'topic', 'apns': { 'payload': { 'aps': { 'alert': { 'title': 't', 'body': 'b', 'title-loc-key': 'tlk', 'title-loc-args': ['t1', 't2'], 'loc-key': 'lk', 'loc-args': ['l1', 'l2'], 'action-loc-key': 'alk', 'launch-image': 'li', }, }, } }, } check_encoding(msg, expected)
def send_notification_to_user(self, title, message, uid, data=None): title = pymysql.escape_string(bleach.clean(title)) message = pymysql.escape_string(bleach.clean(message)) #Connect to MySQL conn = pymysql.connect(self.host, self.username, self.password, self.database, cursorclass=pymysql.cursors.DictCursor, charset='utf8mb4') cursor = conn.cursor() cursor.execute("SELECT * FROM devices WHERE uid='{}';".format(uid)) devices = cursor.fetchall() conn.commit() conn.close() device_tokens = [device["device_id"] for device in devices] push_notification = messaging.MulticastMessage( device_tokens, notification=messaging.Notification(title=title, body=message), data=data, apns=messaging.APNSConfig( payload=messaging.APNSPayload(messaging.Aps(sound="default"))), android=messaging.AndroidConfig( notification=messaging.AndroidNotification( sound="default", click_action="OPEN_FROM_NOTIFICATION"))) response = messaging.send_multicast(push_notification)
def _check_aps(self, aps): with pytest.raises(ValueError) as excinfo: check_encoding( messaging.Message(topic='topic', apns=messaging.APNSConfig( payload=messaging.APNSPayload(aps=aps)))) return excinfo
def test_aps(self): msg = messaging.Message( topic='topic', apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert='alert text', badge=42, sound='s', content_available=True, category='c', thread_id='t'), ))) expected = { 'topic': 'topic', 'apns': { 'payload': { 'aps': { 'alert': 'alert text', 'badge': 42, 'sound': 's', 'content-available': 1, 'category': 'c', 'thread-id': 't', }, } }, } check_encoding(msg, expected)
def test_send(): msg = messaging.Message( topic='foo-bar', notification=messaging.Notification( 'test-title', 'test-body', 'https://images.unsplash.com/photo-1494438639946' '-1ebd1d20bf85?fit=crop&w=900&q=60'), android=messaging.AndroidConfig( restricted_package_name='com.google.firebase.demos', notification=messaging.AndroidNotification( title='android-title', body='android-body', image='https://images.unsplash.com/' 'photo-1494438639946-1ebd1d20bf85?fit=crop&w=900&q=60', event_timestamp=datetime.now(), priority='high', vibrate_timings_millis=[100, 200, 300, 400], visibility='public', sticky=True, local_only=False, default_vibrate_timings=False, default_sound=True, default_light_settings=False, light_settings=messaging.LightSettings( color='#aabbcc', light_off_duration_millis=200, light_on_duration_millis=300), notification_count=1)), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert(title='apns-title', body='apns-body'))))) msg_id = messaging.send(msg, dry_run=True) assert re.match('^projects/.*/messages/.*$', msg_id)
def send_notif_device(registration_token="", data={}, title="Notification Order", body="hey you, you have some order"): if registration_token == "": return message = messaging.Message( data=data, token=registration_token, # notification body notification=messaging.Notification(title=title, body=body), # android notification android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), notification=messaging.AndroidNotification(color='#f45342', title=title, body=body)), # apns apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), ) response = messaging.send(message, app=firebase) return response
async def send_fcm(to_user, action): if not firebase_admin._apps: cred = credentials.Certificate( '/var/www/static/fullfii-firebase-adminsdk-cn02h-2e2b2efd56.json') firebase_admin.initialize_app(cred) registration_token = to_user.device_token if not registration_token: return fcm_reducer_result = await fcm_reducer(to_user, action) if fcm_reducer_result is None: return try: badge_apns = messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=fcm_reducer_result['badge'] ))) if fcm_reducer_result['badge'] > 0 else None message = messaging.Message( notification=messaging.Notification( title=fcm_reducer_result['title'], body=fcm_reducer_result['body'], ), apns=badge_apns, token=registration_token, ) try: response = messaging.send(message) print('Successfully sent message:', response) except: traceback.print_exc() except: traceback.print_exc()
def test_fcm_message_platform_config_override(self): platform_config = PlatformConfig(priority=PlatformPriority.HIGH, collapse_key='collapse_key') apns_config = messaging.APNSConfig( headers={'apns-collapse-id': 'ios_collapse_key'}) request = FCMRequest(self._app, notification=MockNotification( platform_config=platform_config, apns_config=apns_config), topic='abc') message = request._fcm_message() self.assertIsNotNone(message) self.assertIsNotNone(message.data) self.assertIsNone(message.notification) self.assertTrue(isinstance(message.android, messaging.AndroidConfig)) self.assertTrue(isinstance(message.apns, messaging.APNSConfig)) self.assertEqual(message.apns.headers, {'apns-collapse-id': 'ios_collapse_key'}) self.assertTrue(isinstance(message.webpush, messaging.WebpushConfig)) self.assertEqual(message.webpush.headers, { 'Topic': 'collapse_key', 'Urgency': 'high' }) self.assertIsNone(message.token) self.assertEqual(message.topic, 'abc') self.assertIsNone(message.condition)
def send_push_message(self, token, message, subject, extra=None): default_app = self.default_app # All data key:values must be strings notify_data = { 'title': str(subject), 'body': str(message), 'sound': 'waytone' } try: message = messaging.Message( data=notify_data, token=token, notification=messaging.Notification( title=subject, body=message, ), android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='high', notification=messaging.AndroidNotification(sound='waytone', ), ), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(sound='waytone.caf'), ), ), ) # Send a message to the device corresponding to the provided # registration token. response = messaging.send(message, app=self.default_app) logger.info('Push Message sent to %s', token) except Exception as e: print 'Error while sending push message: %s', e.message logger.error('Error while sending push message: %s', e.message)
def test_invalid_payload(self, data): with pytest.raises(ValueError) as excinfo: check_encoding( messaging.Message(topic='topic', apns=messaging.APNSConfig(payload=data))) expected = 'APNSConfig.payload must be an instance of APNSPayload class.' assert str(excinfo.value) == expected
def test_message(self): # [START send_to_token] # This registration token comes from the client FCM SDKs. registration_token = 'd4KUpt5mSJ6ngrNytzwYsp:APA91bGru82_I4TshgwfWhTlq-B-hmqD31nWLr_-3VA_NeUrG3JneaQtuK7et7R_lQS4BGly8nkH7CWC3RIeU3fob46VnO_kq1giPV_EZIi-MOPXDkHpULtYEp2A8fcm12MOvJyNTU3s' # See documentation on defining a message payload. message = messaging.Message( notification=messaging.Notification( title='$GOOG up 1.43% on the day', body= '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.', ), android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( icon='stock_ticker_update', color='#f45342'), ), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), token=registration_token, ) # Send a message to the device corresponding to the provided # registration token. response = messaging.send(message) # Response is a message ID string. print('Successfully sent message:', response)
def test_str(self): fcm_notification = messaging.Notification(title='Title Here', body='Body here') data_payload = {'data': 'payload'} platform_config = PlatformConfig(priority=PlatformPriority.HIGH, collapse_key='general_collapse_key') apns_config = messaging.APNSConfig(headers={'apns-collapse-id': 'ios_collapse_key'}) notification = MockNotification(fcm_notification=fcm_notification, data_payload=data_payload, platform_config=platform_config, apns_config=apns_config) self.assertEqual(str(notification), 'MockNotification(data_payload={\'data\': \'payload\'} fcm_notification.title="Title Here" fcm_notification.body="Body here" platform_config=PlatformConfig(collapse_key="general_collapse_key" priority=1) apns_config={\'apns-collapse-id\': \'ios_collapse_key\'} webhook_message_data={\'data\': \'payload\'})')
def push(data=None, token=None): try: message = messaging.Message( data=data, token=token, apns=messaging.APNSConfig(), android=messaging.AndroidConfig(priority="high"), notification=messaging.Notification()) messaging.send(message) except Exception as e: logging.exception(e)
def test_send(): msg = messaging.Message( topic='foo-bar', notification=messaging.Notification('test-title', 'test-body'), android=messaging.AndroidConfig( restricted_package_name='com.google.firebase.demos', notification=messaging.AndroidNotification(title='android-title', body='android-body')), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert(title='apns-title', body='apns-body'))))) msg_id = messaging.send(msg, dry_run=True) assert re.match('^projects/.*/messages/.*$', msg_id)
def notify_user(user, title, body): # See documentation on defining a message payload. message = messaging.Message( notification=messaging.Notification( title=title, body=body, ), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(sound="default"))), token=user.fir_push_notif_token, ) _send(message, user)
def send_all(registration_token,title, body, data): # registration_token = 'YOUR_REGISTRATION_TOKEN' # [START send_all] # Create a list containing up to 500 messages. # notification=messaging.Notification(title, body,'https://drlinks.yte360.com/static/images/icon-thuoc.png'), messages = [ messaging.Message( notification=messaging.Notification(title, body,'https://drlinks.yte360.com/static/images/ic_launcher.png'), token=registration_token, data=data, android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( title=title, body=body, sound='bell.mp3', icon='https://drlinks.yte360.com/static/images/ic_launcher.png', # color='#f45342' ), ), apns=messaging.APNSConfig( headers={'apns-priority': '10'}, payload=messaging.APNSPayload( aps=messaging.Aps( alert=messaging.ApsAlert( title=title, body=body, ), badge=42, sound='bell.mp3' ), ), ) ), # ... # messaging.Message( # notification=messaging.Notification(title, body), # topic='readers-club', # ), ] response = messaging.send_all(messages) # See the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format(response.success_count))
def SendNotification(self, Topic, Title, Body): print("sending notif") NotifAmount = 1 message = messaging.Message( apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert( title=Title, body=Body, ), sound="default", badge=NotifAmount + 1), ), ), topic=Topic, ) messaging.send(message)
def build_single_message(token, msg): registration_token = token message = messaging.Message( data={'type': 'notification'}, notification=messaging.Notification('', msg), android=messaging.AndroidConfig( priority='high', notification=messaging.AndroidNotification( click_action='FLUTTER_NOTIFICATION_CLICK'), ), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), token=registration_token, ) return message
def test_apns_config(self): msg = messaging.Message( topic='topic', apns=messaging.APNSConfig(headers={'h1': 'v1', 'h2': 'v2'}) ) expected = { 'topic': 'topic', 'apns': { 'headers': { 'h1': 'v1', 'h2': 'v2', }, }, } check_encoding(msg, expected)
def _build_data_message(client_token: str, event: Event) -> Optional[messaging.Message]: data = _build_data_prop(event=event) if data is not None: android_config = messaging.AndroidConfig(priority="high") apns = messaging.APNSConfig( headers={"apns-push-type": "background", "apns-priority": "5"}, payload=messaging.APNSPayload(aps=messaging.Aps(content_available=True),), ) return messaging.Message( data=data, token=client_token, android=android_config, apns=apns ) return None
def send_notification_to_users(self, title, message, uids, setting, data=None): settings = [ 'users.notify_new_friend_req', 'users.notify_new_friend_acc', 'notify_new_feed_item', 'notify_new_like', 'notify_new_comment' ] title = pymysql.escape_string(bleach.clean(title)) message = pymysql.escape_string(bleach.clean(message)) #Connect to MySQL conn = pymysql.connect(self.host, self.username, self.password, self.database, cursorclass=pymysql.cursors.DictCursor, charset='utf8mb4') cursor = conn.cursor() cursor.execute("""SELECT device_id, devices.uid AS uid FROM users LEFT OUTER JOIN devices ON devices.uid = users.uid WHERE devices.uid IN ({}) AND {} = 1;""".format( ",".join(["'{}'".format(uid) for uid in uids]), settings[setting])) conn.commit() conn.close() devices = cursor.fetchall() device_tokens = [device["device_id"] for device in devices] push_notification = messaging.MulticastMessage( device_tokens, notification=messaging.Notification(title=title, body=message), data=data, apns=messaging.APNSConfig( payload=messaging.APNSPayload(messaging.Aps(sound="default"))), android=messaging.AndroidConfig( notification=messaging.AndroidNotification( sound="default", click_action="OPEN_FROM_NOTIFICATION"))) response = messaging.send_multicast(push_notification)
def silent_notification(): post_response = request.get_json() deviceToken = post_response.get('token') key = post_response.get('key') message = messaging.Message( data={"key": key}, token=deviceToken, apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(content_available=True)))) try: response = messaging.send(message) except: abort(400, {'message': 'could not send silent notification'}) return jsonify( {'message': 'silent notification successfully sent from customer'}), 200
def construct_multicast_message(self): self.data['click_action'] = 'FLUTTER_NOTIFICATION_CLICK' message = messaging.MulticastMessage( notification=messaging.Notification( title=self.message['title'], body=self.message['body'], ), android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', ), apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), data=self.data, tokens=self.tokens, ) return message
def send_message_notif(fir_push_notif_token, badge_number, title=None, body=None): """send message notif and update badge icon""" message = messaging.Message( token=fir_push_notif_token, apns=messaging.APNSConfig(payload=messaging.APNSPayload( aps=messaging.Aps(badge=badge_number)))) if title is not None and body is not None: message.notification = messaging.Notification( title=title, body=body, ) _send(message, user)
def send_message(chat_room_id=None, user_id=None, message=None, message_id=None, registration_tokens=None, created_at=None, failed_count=0): if not chat_room_id or not user_id or not message_id or not registration_tokens: raise ValueError( "Invalid arguments found: chat_room_id={chat_room_id}, user_id={user_id}, " "message_id={message_id}, token={token}".format( chat_room_id=chat_room_id, user_id=user_id, message_id=message_id, token=registration_tokens)) if failed_count > 3: return message = messaging.MulticastMessage( data=dict( type="MESSAGE", user_id=str(user_id), created_at=str(created_at), # the belows are for chatting only chat_room_id=str(chat_room_id), message_id=str(message_id), message=str(message)), tokens=registration_tokens, # android=messaging.AndroidConfig(priority="high"), apns=messaging.APNSConfig(), notification=messaging.Notification()) response = messaging.send_multicast(message) # cBdvpdzJSIyOVKZPsWNOGs:APA91bGNyQMxmWWgNVr3LJzM2PPnjmWtfADVaGoG0RHCiFJHFm7bd534EeoWm0REzxwxuzD5hbFbzhsQgP4557WN3m2YYOaJC3FeXCFEsmI9z8qj0Jlzm6SAaQypzCyxO4UHme0yNf5T if response.failure_count > 0: responses = response.responses failed_tokens = [] for idx, resp in enumerate(responses): if not resp.success: # The order of responses corresponds to the order of the registration tokens. failed_tokens.append(registration_tokens[idx]) logging.error('List of tokens that caused failures: %s' % failed_tokens)