def index(request): cred = credentials.Certificate('service_key.json') try: app = firebase_admin.get_app() except ValueError: app = firebase_admin.initialize_app(cred, {'databaseURL': 'https://kagandroidapp.firebaseio.com/'}) if request.method == 'POST': form = FcmForm(request.POST) if form.is_valid(): message = messaging.Message( notification=messaging.Notification( title=form.cleaned_data['title'], body=form.cleaned_data['msg'] ), android=messaging.AndroidConfig( restricted_package_name='com.simaskuprelis.kag_androidapp.dev' ), topic='test' ) print(messaging.send(message, app=app)) else: form = FcmForm() return render(request, 'index.html', {'form': form})
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 _send_android_notification(token_shops: dict, coupon_description: str): if not token_shops: return body = coupon_description or "Смотри подробнее в приложении!" android_params = messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='high') failed_tokens = [] for chunk in chunks(list(token_shops.items()), 500): registration_tokens = [] for token, shops in chunk: registration_tokens.append(token) notification = messaging.Notification( title=f"Новый купон в {', '.join(shops)}🔥", body=body) multicast_message = messaging.MulticastMessage( notification=notification, android=android_params, tokens=registration_tokens, ) batch_failed_tokens = _send_firebase_request(registration_tokens, multicast_message) failed_tokens.extend(batch_failed_tokens) batch_failed_tokens = [] users.delete_tokens(failed_tokens, is_ios=False)
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 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 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 wrapper(*args, **kw): result = func(*args, **kw) req = args[1] fcm_query = FCMModel.select(FCMModel.fcm_key).where(FCMModel.user_email == args[2].login_email) for row in fcm_query: message = messaging.Message( android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', ), data={ 'score': '850', 'time': '2:45', }, token=row.fcm_key, ) try: response = messaging.send(message) except Exception as ee: print("key is not valid.") pass PushLog.create( receiver_email=args[2].login_email, content="이거 바꿔야해 승현아", ) return result
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 send_notification(title, message, to=[], data={}): data.update({ "body": message, "title": title, 'type': 'confimar_embarque', # aqui vai a informacao sobre o tipo da notificacao 'email': '*****@*****.**', # aqui vai o email do usuário "click_action": "FLUTTER_NOTIFICATION_CLICK", 'data': json.dumps({'email': '*****@*****.**'}) }) registration_tokens = to message = messaging.MulticastMessage( notification=messaging.Notification( title=title, body=message, ), android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=5 * 60), priority='high', notification=messaging.AndroidNotification( icon='stock_ticker_update', color='#f45342', sound='default', # click_action='FLUTTER_NOTIFICATION_CLICK', ), ), data=data, tokens=registration_tokens, ) response = messaging.send_multicast(message) print('data: {}\n'.format(data)) print('{0} messages were sent successfully'.format(response.success_count))
def test_android_config(self): msg = messaging.Message(topic='topic', android=messaging.AndroidConfig( collapse_key='key', restricted_package_name='package', priority='high', ttl=123, data={ 'k1': 'v1', 'k2': 'v2' })) expected = { 'topic': 'topic', 'android': { 'collapse_key': 'key', 'restricted_package_name': 'package', 'priority': 'high', 'ttl': '123s', 'data': { 'k1': 'v1', 'k2': 'v2', }, }, } check_encoding(msg, expected)
def __send_all__(self,notification,data,dry_run=False): if not isinstance(notification, messaging.AndroidNotification): raise TypeError("notification must be of the type AndroidNotification") if not isinstance(data, dict): raise TypeError("custom data must be of the type Dictionary") topics = self.__create__topics_for__all__users__() responses = [] for i, topic in enumerate(topics): print(i) responses = messaging.send( messaging.Message( data=data, android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=notification, ), topic=topic ), dry_run=dry_run ) return responses
def push_notification_trigger_to_topic(topic, from_user=None, type='', reference_id='', reference_username=''): try: if not topic: return if not firebase_ins: firebase_admin.initialize_app(cred, {'projectId': firebase_app}) data = { 'reference_type': type, 'reference_id': str(reference_id), 'reference_username': reference_username, 'title': '' } print(data) config = messaging.AndroidConfig(priority='high') if type == 'NEW_BROADCAST': data['title'] = '{} added a new broadcast'.format( from_user.first_name) msg = messaging.Message(data=data, topic=topic, android=config) print(msg) x = messaging.send(message=msg) print(x) except Exception as e: print(e) pass
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_new_posts_notifications(node_name, user_full_name, posts_count): """ send push notifications to all devices in a node """ try: node_doc_ref = db_ref.collection(u'nodes').document(node_name) node_details = node_doc_ref.get().to_dict() connected_users = node_details.get('connected_users') notification_body = "{} added {} photos".format( user_full_name, posts_count) fcm_tokens = [ user_doc_ref.get().to_dict().get('fcm_token') for user_doc_ref in connected_users ] for token in fcm_tokens: message = messaging.Message( android=messaging.AndroidConfig( priority='normal', notification=messaging.AndroidNotification( title=node_name, body=notification_body, icon='fcm_push_icon', color='#364156'), ), token=token, ) messaging.send(message) except: pass
def send(self, **kwargs): if self: success_total = 0 failure_total = 0 ttl = kwargs.get("ttl", 3600) for lang in settings.LANGUAGES: with override(lang[0]): reg_ids = list( Device.objects.filter( user__in=self.users.all(), receive_category__key=self.category_id, active=True, language=lang[0], ).values_list("registration_id", flat=True)) data = kwargs.get("data", {}) if self.url is not None: data["url"] = self.url data["title"] = self.title data["body"] = str(self.body) message = messaging.Message( notification=messaging.Notification( title=data["title"], body=data["body"], ), data=data, android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=ttl), priority="normal", notification=messaging.AndroidNotification( color="#E62272", sound="default", ), ), ) for reg_id in reg_ids: message.token = reg_id try: messaging.send(message, dry_run=kwargs.get( "dry_run", False)) success_total += 1 except messaging.UnregisteredError: failure_total += 1 Device.objects.filter( registration_id=reg_id).delete() except exceptions.InvalidArgumentError: failure_total += 1 Device.objects.filter( registration_id=reg_id).update(active=False) except exceptions.FirebaseError: failure_total += 1 self.sent = timezone.now() self.success = success_total self.failure = failure_total self.save()
def test_android_notification(self): msg = messaging.Message(topic='topic', android=messaging.AndroidConfig( notification=messaging.AndroidNotification( title='t', body='b', icon='i', color='#112233', sound='s', tag='t', click_action='ca', title_loc_key='tlk', body_loc_key='blk', title_loc_args=['t1', 't2'], body_loc_args=['b1', 'b2']))) expected = { 'topic': 'topic', 'android': { 'notification': { 'title': 't', 'body': 'b', 'icon': 'i', 'color': '#112233', 'sound': 's', 'tag': 't', 'click_action': 'ca', 'title_loc_key': 'tlk', 'body_loc_key': 'blk', 'title_loc_args': ['t1', 't2'], 'body_loc_args': ['b1', 'b2'], }, }, } check_encoding(msg, expected)
def _check_notification(self, notification): with pytest.raises(ValueError) as excinfo: check_encoding( messaging.Message(topic='topic', android=messaging.AndroidConfig( notification=notification))) return excinfo
def __send__(self,user_id,notification,data,dry_run=False): if not isinstance(user_id, str): raise TypeError("user_id must be a string when send a single message") if not isinstance(notification, messaging.AndroidNotification): raise TypeError("notification must be of the type AndroidNotification") if not isinstance(data, dict): raise TypeError("custom data must be of the type Dictionary") registration_token = self.__get_token__(user_id) message = messaging.Message( data=data, android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=notification, ), token=registration_token ) return messaging.send(message,dry_run=dry_run)
def __send_many__(self,user_ids,notification,data,dry_run=False): if not self.__is_list_of_strings__(user_ids): raise TypeError("user_id must be a list when sending bulk message") if not isinstance(notification, messaging.AndroidNotification): raise TypeError("notification must be of the type AndroidNotification") if not isinstance(data, dict): raise TypeError("custom data must be of the type Dictionary") topic = self.__create_or_get_topic__(user_ids) message = messaging.Message( data=data, android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=notification, ), topic=topic ) return messaging.send(message,dry_run=dry_run)
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
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 test_invalid_android_notification(self, data): with pytest.raises(ValueError) as excinfo: check_encoding( messaging.Message( topic='topic', android=messaging.AndroidConfig(notification=data))) expected = 'AndroidConfig.notification must be an instance of AndroidNotification class.' assert str(excinfo.value) == expected
def test_invalid_collapse_key(self, data): with pytest.raises(ValueError) as excinfo: check_encoding( messaging.Message( topic='topic', android=messaging.AndroidConfig(collapse_key=data))) assert str( excinfo.value) == 'AndroidConfig.collapse_key must be a string.'
def test_invalid_priority(self, data): with pytest.raises(ValueError) as excinfo: check_encoding(messaging.Message( topic='topic', android=messaging.AndroidConfig(priority=data))) if isinstance(data, six.string_types): assert str(excinfo.value) == 'AndroidConfig.priority must be "high" or "normal".' else: assert str(excinfo.value) == 'AndroidConfig.priority must be a non-empty string.'
def _build_android_config(self, title_loc_key: str = ''): return messaging.AndroidConfig( # priority='high', # ttl=6*60*60, # 6 hours # notification=messaging.AndroidNotification( # title_loc_key=title_loc_key # ) )
def notifySenderMessageRead(fb, token): androidNotification = messaging.AndroidNotification( sound="default", click_action="FCM_PLUGIN_ACTIVITY") androidConfig = messaging.AndroidConfig(collapse_key="key", priority="high", notification=androidNotification) message = messaging.Message(data={"action": ACTION_MESSAGE_READ}, token=token) messaging.send(message, dry_run=False, app=fb)
def test_invalid_package_name(self, data): with pytest.raises(ValueError) as excinfo: check_encoding( messaging.Message(topic='topic', android=messaging.AndroidConfig( restricted_package_name=data))) assert str( excinfo.value ) == 'AndroidConfig.restricted_package_name must be a string.'
def send_message(title, body, topic): config = messaging.AndroidConfig(ttl=12 * 60 * 60, collapse_key=topic) msg = messaging.Message(data={ 'title': title, 'body': body }, android=config, topic=topic) return messaging.send(msg, False, app)
def test_invalid_ttl(self, data): with pytest.raises(ValueError) as excinfo: check_encoding(messaging.Message( topic='topic', android=messaging.AndroidConfig(ttl=data))) if isinstance(data, numbers.Number): assert str(excinfo.value) == ('AndroidConfig.ttl must not be negative.') else: assert str(excinfo.value) == ('AndroidConfig.ttl must be a duration in seconds or ' 'an instance of datetime.timedelta.')
def test_android_ttl(self, ttl): msg = messaging.Message(topic='topic', android=messaging.AndroidConfig(ttl=ttl[0])) expected = { 'topic': 'topic', 'android': { 'ttl': ttl[1], }, } check_encoding(msg, expected)